import { exec, spawnSync as spawnSync$2, spawn as spawn$2 } from 'node:child_process'; import * as require$$3$2 from 'net'; import require$$3$2__default from 'net'; import require$$0$4, { win32 as win32$1, posix as posix$2, isAbsolute as isAbsolute$3, resolve as resolve$5, relative as relative$3, join as join$3, normalize as normalize$2, basename as basename$2, extname as extname$1, dirname as dirname$2, sep as sep$2 } from 'path'; import * as require$$0__default from 'fs'; import require$$0__default__default, { readdir as readdir$5, promises as promises$2, readdirSync, statSync as statSync$2, existsSync, readFileSync as readFileSync$1 } from 'fs'; import * as fs$l$1 from 'node:fs'; import fs$l__default, { readFileSync, promises } from 'node:fs'; import fsp, { mkdir, writeFile, readFile, lstat as lstat$4, realpath as realpath$4, readdir as readdir$4 } from 'node:fs/promises'; import path$o$1, { resolve as resolve$4, dirname as dirname$1, extname, basename as basename$1, relative as relative$2, join as join$2, posix as posix$3, isAbsolute as isAbsolute$4 } from 'node:path'; import { fileURLToPath, pathToFileURL, URL as URL$3, parse as parse$k, URLSearchParams as URLSearchParams$1 } from 'node:url'; import { format as format$3, promisify as promisify$5, inspect } from 'node:util'; import { performance as performance$1 } from 'node:perf_hooks'; import { createRequire as createRequire$1, builtinModules as builtinModules$1 } from 'node:module'; import * as require$$0$3$1 from 'tty'; import require$$0$3__default from 'tty'; import esbuild, { build as build$3, transform as transform$4, formatMessages } from 'esbuild-wasm'; import require$$0$5 from 'events'; import require$$5 from 'assert'; import require$$0$6 from 'util'; import require$$0$9, { fileURLToPath as fileURLToPath$1 } from 'url'; import require$$1$1 from 'http'; import require$$0$7 from 'stream'; import require$$2$1 from 'os'; import require$$2$1$1 from 'child_process'; import os$3$1 from 'node:os'; import * as crypto$2 from 'node:crypto'; import { createHash as createHash$4 } from 'node:crypto'; import { promises as promises$1 } from 'node:dns'; import require$$3$1$1 from 'crypto'; import { Buffer as Buffer$1 } from 'node:buffer'; import require$$0$8, { createRequire as createRequire$2 } from 'module'; import assert$1$1 from 'node:assert'; import process$1, { env as env$2 } from 'node:process'; import v8 from 'node:v8'; import require$$1 from 'worker_threads'; import require$$0$a from 'zlib'; import require$$0$b from 'buffer'; import require$$1$2 from 'https'; import require$$4$1 from 'tls'; import { createServer as createServer$3, STATUS_CODES } from 'node:http'; import { createServer as createServer$2 } from 'node:https'; import * as qs from 'querystring'; import readline from 'node:readline'; import { gzip } from 'node:zlib'; import * as svelte$1 from '../compiler.js'; import { VERSION as VERSION$2 } from '../compiler.js'; import require$$1$3 from 'fs/promises'; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. 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. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol */ var __assign = function() { __assign = Object.assign || function __assign(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; }; return __assign.apply(this, arguments); }; function __awaiter(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()); }); } function __generator(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 (g && (g = 0, op[0] && (_ = 0)), _) 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 }; } } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; const { version: version$8 } = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url)).toString()); const VERSION$1 = version$8; const DEFAULT_MAIN_FIELDS = [ 'module', 'jsnext:main', 'jsnext', ]; // Baseline support browserslist // "defaults and supports es6-module and supports es6-module-dynamic-import" // Higher browser versions may be needed for extra features. const ESBUILD_MODULES_TARGET = [ 'es2020', 'edge88', 'firefox78', 'chrome87', 'safari14', ]; const DEFAULT_EXTENSIONS$2 = [ '.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json', ]; const DEFAULT_CONFIG_FILES = [ 'vite.config.js', 'vite.config.mjs', 'vite.config.ts', 'vite.config.cjs', 'vite.config.mts', 'vite.config.cts', ]; const JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/; const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/; const OPTIMIZABLE_ENTRY_RE = /\.[cm]?[jt]s$/; const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/; /** * Prefix for resolved fs paths, since windows paths may not be valid as URLs. */ const FS_PREFIX = `/@fs/`; /** * Prefix for resolved Ids that are not valid browser import specifiers */ const VALID_ID_PREFIX = `/@id/`; /** * Plugins that use 'virtual modules' (e.g. for helper functions), prefix the * module ID with `\0`, a convention from the rollup ecosystem. * This prevents other plugins from trying to process the id (like node resolution), * and core features like sourcemaps can use this info to differentiate between * virtual modules and regular files. * `\0` is not a permitted char in import URLs so we have to replace them during * import analysis. The id will be decoded back before entering the plugins pipeline. * These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual * modules in the browser end up encoded as `/@id/__x00__{id}` */ const NULL_BYTE_PLACEHOLDER = `__x00__`; const CLIENT_PUBLIC_PATH = `/@vite/client`; const ENV_PUBLIC_PATH = `/@vite/env`; const VITE_PACKAGE_DIR$1 = resolve$4( // import.meta.url is `dist/node/constants.js` after bundle fileURLToPath(import.meta.url), '../../..'); const CLIENT_ENTRY$1 = resolve$4(VITE_PACKAGE_DIR$1, 'dist/client/client.mjs'); const ENV_ENTRY$1 = resolve$4(VITE_PACKAGE_DIR$1, 'dist/client/env.mjs'); const CLIENT_DIR$1 = path$o$1.dirname(CLIENT_ENTRY$1); // ** READ THIS ** before editing `KNOWN_ASSET_TYPES`. // If you add an asset to `KNOWN_ASSET_TYPES`, make sure to also add it // to the TypeScript declaration file `packages/vite/client.d.ts` and // add a mime type to the `registerCustomMime` in // `packages/vite/src/node/plugin/assets.ts` if mime type cannot be // looked up by mrmime. const KNOWN_ASSET_TYPES = [ // images 'png', 'jpe?g', 'jfif', 'pjpeg', 'pjp', 'gif', 'svg', 'ico', 'webp', 'avif', // media 'mp4', 'webm', 'ogg', 'mp3', 'wav', 'flac', 'aac', 'opus', // fonts 'woff2?', 'eot', 'ttf', 'otf', // other 'webmanifest', 'pdf', 'txt', ]; const DEFAULT_ASSETS_RE = new RegExp(`\\.(` + KNOWN_ASSET_TYPES.join('|') + `)(\\?.*)?$`); const DEP_VERSION_RE = /[?&](v=[\w.-]+)\b/; const loopbackHosts = new Set([ 'localhost', '127.0.0.1', '::1', '0000:0000:0000:0000:0000:0000:0000:0001', ]); const wildcardHosts = new Set([ '0.0.0.0', '::', '0000:0000:0000:0000:0000:0000:0000:0000', ]); const DEFAULT_DEV_PORT = 5173; /* @license Rollup.js v3.29.4 Thu, 28 Sep 2023 04:54:30 GMT - commit 4e92d60fa90cead39481e3703d26e5d812f43bd1 https://github.com/rollup/rollup Released under the MIT License. */ var version$1$3 = "3.29.4"; const comma$2 = ','.charCodeAt(0); const semicolon$3 = ';'.charCodeAt(0); const chars$1$2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; const intToChar$4 = new Uint8Array(64); // 64 possible chars. const charToInt$4 = new Uint8Array(128); // z is 122 in ASCII for (let i = 0; i < chars$1$2.length; i++) { const c = chars$1$2.charCodeAt(i); intToChar$4[i] = c; charToInt$4[c] = i; } // Provide a fallback for older environments. const td$2 = typeof TextDecoder !== 'undefined' ? /* #__PURE__ */ new TextDecoder() : typeof Buffer !== 'undefined' ? { decode(buf) { const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); return out.toString(); }, } : { decode(buf) { let out = ''; for (let i = 0; i < buf.length; i++) { out += String.fromCharCode(buf[i]); } return out; }, }; function decode$1(mappings) { const state = new Int32Array(5); const decoded = []; let index = 0; do { const semi = indexOf$1(mappings, index); const line = []; let sorted = true; let lastCol = 0; state[0] = 0; for (let i = index; i < semi; i++) { let seg; i = decodeInteger$1(mappings, i, state, 0); // genColumn const col = state[0]; if (col < lastCol) sorted = false; lastCol = col; if (hasMoreVlq$1(mappings, i, semi)) { i = decodeInteger$1(mappings, i, state, 1); // sourcesIndex i = decodeInteger$1(mappings, i, state, 2); // sourceLine i = decodeInteger$1(mappings, i, state, 3); // sourceColumn if (hasMoreVlq$1(mappings, i, semi)) { i = decodeInteger$1(mappings, i, state, 4); // namesIndex seg = [col, state[1], state[2], state[3], state[4]]; } else { seg = [col, state[1], state[2], state[3]]; } } else { seg = [col]; } line.push(seg); } if (!sorted) sort$1(line); decoded.push(line); index = semi + 1; } while (index <= mappings.length); return decoded; } function indexOf$1(mappings, index) { const idx = mappings.indexOf(';', index); return idx === -1 ? mappings.length : idx; } function decodeInteger$1(mappings, pos, state, j) { let value = 0; let shift = 0; let integer = 0; do { const c = mappings.charCodeAt(pos++); integer = charToInt$4[c]; value |= (integer & 31) << shift; shift += 5; } while (integer & 32); const shouldNegate = value & 1; value >>>= 1; if (shouldNegate) { value = -0x80000000 | -value; } state[j] += value; return pos; } function hasMoreVlq$1(mappings, i, length) { if (i >= length) return false; return mappings.charCodeAt(i) !== comma$2; } function sort$1(line) { line.sort(sortComparator$2); } function sortComparator$2(a, b) { return a[0] - b[0]; } function encode$3(decoded) { const state = new Int32Array(5); const bufLength = 1024 * 16; const subLength = bufLength - 36; const buf = new Uint8Array(bufLength); const sub = buf.subarray(0, subLength); let pos = 0; let out = ''; for (let i = 0; i < decoded.length; i++) { const line = decoded[i]; if (i > 0) { if (pos === bufLength) { out += td$2.decode(buf); pos = 0; } buf[pos++] = semicolon$3; } if (line.length === 0) continue; state[0] = 0; for (let j = 0; j < line.length; j++) { const segment = line[j]; // We can push up to 5 ints, each int can take at most 7 chars, and we // may push a comma. if (pos > subLength) { out += td$2.decode(sub); buf.copyWithin(0, subLength, pos); pos -= subLength; } if (j > 0) buf[pos++] = comma$2; pos = encodeInteger$2(buf, pos, state, segment, 0); // genColumn if (segment.length === 1) continue; pos = encodeInteger$2(buf, pos, state, segment, 1); // sourcesIndex pos = encodeInteger$2(buf, pos, state, segment, 2); // sourceLine pos = encodeInteger$2(buf, pos, state, segment, 3); // sourceColumn if (segment.length === 4) continue; pos = encodeInteger$2(buf, pos, state, segment, 4); // namesIndex } } return out + td$2.decode(buf.subarray(0, pos)); } function encodeInteger$2(buf, pos, state, segment, j) { const next = segment[j]; let num = next - state[j]; state[j] = next; num = num < 0 ? (-num << 1) | 1 : num << 1; do { let clamped = num & 0b011111; num >>>= 5; if (num > 0) clamped |= 0b100000; buf[pos++] = intToChar$4[clamped]; } while (num > 0); return pos; } let BitSet$3 = class BitSet { constructor(arg) { this.bits = arg instanceof BitSet ? arg.bits.slice() : []; } add(n) { this.bits[n >> 5] |= 1 << (n & 31); } has(n) { return !!(this.bits[n >> 5] & (1 << (n & 31))); } }; let Chunk$1$1 = class Chunk { constructor(start, end, content) { this.start = start; this.end = end; this.original = content; this.intro = ''; this.outro = ''; this.content = content; this.storeName = false; this.edited = false; { this.previous = null; this.next = null; } } appendLeft(content) { this.outro += content; } appendRight(content) { this.intro = this.intro + content; } clone() { const chunk = new Chunk(this.start, this.end, this.original); chunk.intro = this.intro; chunk.outro = this.outro; chunk.content = this.content; chunk.storeName = this.storeName; chunk.edited = this.edited; return chunk; } contains(index) { return this.start < index && index < this.end; } eachNext(fn) { let chunk = this; while (chunk) { fn(chunk); chunk = chunk.next; } } eachPrevious(fn) { let chunk = this; while (chunk) { fn(chunk); chunk = chunk.previous; } } edit(content, storeName, contentOnly) { this.content = content; if (!contentOnly) { this.intro = ''; this.outro = ''; } this.storeName = storeName; this.edited = true; return this; } prependLeft(content) { this.outro = content + this.outro; } prependRight(content) { this.intro = content + this.intro; } split(index) { const sliceIndex = index - this.start; const originalBefore = this.original.slice(0, sliceIndex); const originalAfter = this.original.slice(sliceIndex); this.original = originalBefore; const newChunk = new Chunk(index, this.end, originalAfter); newChunk.outro = this.outro; this.outro = ''; this.end = index; if (this.edited) { // after split we should save the edit content record into the correct chunk // to make sure sourcemap correct // For example: // ' test'.trim() // split -> ' ' + 'test' // ✔️ edit -> '' + 'test' // ✖️ edit -> 'test' + '' // TODO is this block necessary?... newChunk.edit('', false); this.content = ''; } else { this.content = originalBefore; } newChunk.next = this.next; if (newChunk.next) newChunk.next.previous = newChunk; newChunk.previous = this; this.next = newChunk; return newChunk; } toString() { return this.intro + this.content + this.outro; } trimEnd(rx) { this.outro = this.outro.replace(rx, ''); if (this.outro.length) return true; const trimmed = this.content.replace(rx, ''); if (trimmed.length) { if (trimmed !== this.content) { this.split(this.start + trimmed.length).edit('', undefined, true); if (this.edited) { // save the change, if it has been edited this.edit(trimmed, this.storeName, true); } } return true; } else { this.edit('', undefined, true); this.intro = this.intro.replace(rx, ''); if (this.intro.length) return true; } } trimStart(rx) { this.intro = this.intro.replace(rx, ''); if (this.intro.length) return true; const trimmed = this.content.replace(rx, ''); if (trimmed.length) { if (trimmed !== this.content) { const newChunk = this.split(this.end - trimmed.length); if (this.edited) { // save the change, if it has been edited newChunk.edit(trimmed, this.storeName, true); } this.edit('', undefined, true); } return true; } else { this.edit('', undefined, true); this.outro = this.outro.replace(rx, ''); if (this.outro.length) return true; } } }; function getBtoa$3() { if (typeof window !== 'undefined' && typeof window.btoa === 'function') { return (str) => window.btoa(unescape(encodeURIComponent(str))); } else if (typeof Buffer === 'function') { return (str) => Buffer.from(str, 'utf-8').toString('base64'); } else { return () => { throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); }; } } const btoa$3 = /*#__PURE__*/ getBtoa$3(); let SourceMap$4 = class SourceMap { constructor(properties) { this.version = 3; this.file = properties.file; this.sources = properties.sources; this.sourcesContent = properties.sourcesContent; this.names = properties.names; this.mappings = encode$3(properties.mappings); if (typeof properties.x_google_ignoreList !== 'undefined') { this.x_google_ignoreList = properties.x_google_ignoreList; } } toString() { return JSON.stringify(this); } toUrl() { return 'data:application/json;charset=utf-8;base64,' + btoa$3(this.toString()); } }; function guessIndent$3(code) { const lines = code.split('\n'); const tabbed = lines.filter((line) => /^\t+/.test(line)); const spaced = lines.filter((line) => /^ {2,}/.test(line)); if (tabbed.length === 0 && spaced.length === 0) { return null; } // More lines tabbed than spaced? Assume tabs, and // default to tabs in the case of a tie (or nothing // to go on) if (tabbed.length >= spaced.length) { return '\t'; } // Otherwise, we need to guess the multiple const min = spaced.reduce((previous, current) => { const numSpaces = /^ +/.exec(current)[0].length; return Math.min(numSpaces, previous); }, Infinity); return new Array(min + 1).join(' '); } function getRelativePath$3(from, to) { const fromParts = from.split(/[/\\]/); const toParts = to.split(/[/\\]/); fromParts.pop(); // get dirname while (fromParts[0] === toParts[0]) { fromParts.shift(); toParts.shift(); } if (fromParts.length) { let i = fromParts.length; while (i--) fromParts[i] = '..'; } return fromParts.concat(toParts).join('/'); } const toString$1$2 = Object.prototype.toString; function isObject$1$2(thing) { return toString$1$2.call(thing) === '[object Object]'; } function getLocator$1$1(source) { const originalLines = source.split('\n'); const lineOffsets = []; for (let i = 0, pos = 0; i < originalLines.length; i++) { lineOffsets.push(pos); pos += originalLines[i].length + 1; } return function locate(index) { let i = 0; let j = lineOffsets.length; while (i < j) { const m = (i + j) >> 1; if (index < lineOffsets[m]) { j = m; } else { i = m + 1; } } const line = i - 1; const column = index - lineOffsets[line]; return { line, column }; }; } const wordRegex$1 = /\w/; let Mappings$3 = class Mappings { constructor(hires) { this.hires = hires; this.generatedCodeLine = 0; this.generatedCodeColumn = 0; this.raw = []; this.rawSegments = this.raw[this.generatedCodeLine] = []; this.pending = null; } addEdit(sourceIndex, content, loc, nameIndex) { if (content.length) { const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; if (nameIndex >= 0) { segment.push(nameIndex); } this.rawSegments.push(segment); } else if (this.pending) { this.rawSegments.push(this.pending); } this.advance(content); this.pending = null; } addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { let originalCharIndex = chunk.start; let first = true; // when iterating each char, check if it's in a word boundary let charInHiresBoundary = false; while (originalCharIndex < chunk.end) { if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; if (this.hires === 'boundary') { // in hires "boundary", group segments per word boundary than per char if (wordRegex$1.test(original[originalCharIndex])) { // for first char in the boundary found, start the boundary by pushing a segment if (!charInHiresBoundary) { this.rawSegments.push(segment); charInHiresBoundary = true; } } else { // for non-word char, end the boundary by pushing a segment this.rawSegments.push(segment); charInHiresBoundary = false; } } else { this.rawSegments.push(segment); } } if (original[originalCharIndex] === '\n') { loc.line += 1; loc.column = 0; this.generatedCodeLine += 1; this.raw[this.generatedCodeLine] = this.rawSegments = []; this.generatedCodeColumn = 0; first = true; } else { loc.column += 1; this.generatedCodeColumn += 1; first = false; } originalCharIndex += 1; } this.pending = null; } advance(str) { if (!str) return; const lines = str.split('\n'); if (lines.length > 1) { for (let i = 0; i < lines.length - 1; i++) { this.generatedCodeLine++; this.raw[this.generatedCodeLine] = this.rawSegments = []; } this.generatedCodeColumn = 0; } this.generatedCodeColumn += lines[lines.length - 1].length; } }; const n$4 = '\n'; const warned$3 = { insertLeft: false, insertRight: false, storeName: false, }; let MagicString$3 = class MagicString { constructor(string, options = {}) { const chunk = new Chunk$1$1(0, string.length, string); Object.defineProperties(this, { original: { writable: true, value: string }, outro: { writable: true, value: '' }, intro: { writable: true, value: '' }, firstChunk: { writable: true, value: chunk }, lastChunk: { writable: true, value: chunk }, lastSearchedChunk: { writable: true, value: chunk }, byStart: { writable: true, value: {} }, byEnd: { writable: true, value: {} }, filename: { writable: true, value: options.filename }, indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, sourcemapLocations: { writable: true, value: new BitSet$3() }, storedNames: { writable: true, value: {} }, indentStr: { writable: true, value: undefined }, ignoreList: { writable: true, value: options.ignoreList }, }); this.byStart[0] = chunk; this.byEnd[string.length] = chunk; } addSourcemapLocation(char) { this.sourcemapLocations.add(char); } append(content) { if (typeof content !== 'string') throw new TypeError('outro content must be a string'); this.outro += content; return this; } appendLeft(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byEnd[index]; if (chunk) { chunk.appendLeft(content); } else { this.intro += content; } return this; } appendRight(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byStart[index]; if (chunk) { chunk.appendRight(content); } else { this.outro += content; } return this; } clone() { const cloned = new MagicString(this.original, { filename: this.filename }); let originalChunk = this.firstChunk; let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); while (originalChunk) { cloned.byStart[clonedChunk.start] = clonedChunk; cloned.byEnd[clonedChunk.end] = clonedChunk; const nextOriginalChunk = originalChunk.next; const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); if (nextClonedChunk) { clonedChunk.next = nextClonedChunk; nextClonedChunk.previous = clonedChunk; clonedChunk = nextClonedChunk; } originalChunk = nextOriginalChunk; } cloned.lastChunk = clonedChunk; if (this.indentExclusionRanges) { cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); } cloned.sourcemapLocations = new BitSet$3(this.sourcemapLocations); cloned.intro = this.intro; cloned.outro = this.outro; return cloned; } generateDecodedMap(options) { options = options || {}; const sourceIndex = 0; const names = Object.keys(this.storedNames); const mappings = new Mappings$3(options.hires); const locate = getLocator$1$1(this.original); if (this.intro) { mappings.advance(this.intro); } this.firstChunk.eachNext((chunk) => { const loc = locate(chunk.start); if (chunk.intro.length) mappings.advance(chunk.intro); if (chunk.edited) { mappings.addEdit( sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1, ); } else { mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); } if (chunk.outro.length) mappings.advance(chunk.outro); }); return { file: options.file ? options.file.split(/[/\\]/).pop() : undefined, sources: [ options.source ? getRelativePath$3(options.file || '', options.source) : options.file || '', ], sourcesContent: options.includeContent ? [this.original] : undefined, names, mappings: mappings.raw, x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined, }; } generateMap(options) { return new SourceMap$4(this.generateDecodedMap(options)); } _ensureindentStr() { if (this.indentStr === undefined) { this.indentStr = guessIndent$3(this.original); } } _getRawIndentString() { this._ensureindentStr(); return this.indentStr; } getIndentString() { this._ensureindentStr(); return this.indentStr === null ? '\t' : this.indentStr; } indent(indentStr, options) { const pattern = /^[^\r\n]/gm; if (isObject$1$2(indentStr)) { options = indentStr; indentStr = undefined; } if (indentStr === undefined) { this._ensureindentStr(); indentStr = this.indentStr || '\t'; } if (indentStr === '') return this; // noop options = options || {}; // Process exclusion ranges const isExcluded = {}; if (options.exclude) { const exclusions = typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; exclusions.forEach((exclusion) => { for (let i = exclusion[0]; i < exclusion[1]; i += 1) { isExcluded[i] = true; } }); } let shouldIndentNextCharacter = options.indentStart !== false; const replacer = (match) => { if (shouldIndentNextCharacter) return `${indentStr}${match}`; shouldIndentNextCharacter = true; return match; }; this.intro = this.intro.replace(pattern, replacer); let charIndex = 0; let chunk = this.firstChunk; while (chunk) { const end = chunk.end; if (chunk.edited) { if (!isExcluded[charIndex]) { chunk.content = chunk.content.replace(pattern, replacer); if (chunk.content.length) { shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; } } } else { charIndex = chunk.start; while (charIndex < end) { if (!isExcluded[charIndex]) { const char = this.original[charIndex]; if (char === '\n') { shouldIndentNextCharacter = true; } else if (char !== '\r' && shouldIndentNextCharacter) { shouldIndentNextCharacter = false; if (charIndex === chunk.start) { chunk.prependRight(indentStr); } else { this._splitChunk(chunk, charIndex); chunk = chunk.next; chunk.prependRight(indentStr); } } } charIndex += 1; } } charIndex = chunk.end; chunk = chunk.next; } this.outro = this.outro.replace(pattern, replacer); return this; } insert() { throw new Error( 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)', ); } insertLeft(index, content) { if (!warned$3.insertLeft) { console.warn( 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead', ); // eslint-disable-line no-console warned$3.insertLeft = true; } return this.appendLeft(index, content); } insertRight(index, content) { if (!warned$3.insertRight) { console.warn( 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead', ); // eslint-disable-line no-console warned$3.insertRight = true; } return this.prependRight(index, content); } move(start, end, index) { if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself'); this._split(start); this._split(end); this._split(index); const first = this.byStart[start]; const last = this.byEnd[end]; const oldLeft = first.previous; const oldRight = last.next; const newRight = this.byStart[index]; if (!newRight && last === this.lastChunk) return this; const newLeft = newRight ? newRight.previous : this.lastChunk; if (oldLeft) oldLeft.next = oldRight; if (oldRight) oldRight.previous = oldLeft; if (newLeft) newLeft.next = first; if (newRight) newRight.previous = last; if (!first.previous) this.firstChunk = last.next; if (!last.next) { this.lastChunk = first.previous; this.lastChunk.next = null; } first.previous = newLeft; last.next = newRight || null; if (!newLeft) this.firstChunk = first; if (!newRight) this.lastChunk = last; return this; } overwrite(start, end, content, options) { options = options || {}; return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); } update(start, end, content, options) { if (typeof content !== 'string') throw new TypeError('replacement content must be a string'); while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; if (end > this.original.length) throw new Error('end is out of bounds'); if (start === end) throw new Error( 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead', ); this._split(start); this._split(end); if (options === true) { if (!warned$3.storeName) { console.warn( 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string', ); // eslint-disable-line no-console warned$3.storeName = true; } options = { storeName: true }; } const storeName = options !== undefined ? options.storeName : false; const overwrite = options !== undefined ? options.overwrite : false; if (storeName) { const original = this.original.slice(start, end); Object.defineProperty(this.storedNames, original, { writable: true, value: true, enumerable: true, }); } const first = this.byStart[start]; const last = this.byEnd[end]; if (first) { let chunk = first; while (chunk !== last) { if (chunk.next !== this.byStart[chunk.end]) { throw new Error('Cannot overwrite across a split point'); } chunk = chunk.next; chunk.edit('', false); } first.edit(content, storeName, !overwrite); } else { // must be inserting at the end const newChunk = new Chunk$1$1(start, end, '').edit(content, storeName); // TODO last chunk in the array may not be the last chunk, if it's moved... last.next = newChunk; newChunk.previous = last; } return this; } prepend(content) { if (typeof content !== 'string') throw new TypeError('outro content must be a string'); this.intro = content + this.intro; return this; } prependLeft(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byEnd[index]; if (chunk) { chunk.prependLeft(content); } else { this.intro = content + this.intro; } return this; } prependRight(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byStart[index]; if (chunk) { chunk.prependRight(content); } else { this.outro = content + this.outro; } return this; } remove(start, end) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; if (start === end) return this; if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); if (start > end) throw new Error('end must be greater than start'); this._split(start); this._split(end); let chunk = this.byStart[start]; while (chunk) { chunk.intro = ''; chunk.outro = ''; chunk.edit(''); chunk = end > chunk.end ? this.byStart[chunk.end] : null; } return this; } lastChar() { if (this.outro.length) return this.outro[this.outro.length - 1]; let chunk = this.lastChunk; do { if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; if (chunk.content.length) return chunk.content[chunk.content.length - 1]; if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; } while ((chunk = chunk.previous)); if (this.intro.length) return this.intro[this.intro.length - 1]; return ''; } lastLine() { let lineIndex = this.outro.lastIndexOf(n$4); if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); let lineStr = this.outro; let chunk = this.lastChunk; do { if (chunk.outro.length > 0) { lineIndex = chunk.outro.lastIndexOf(n$4); if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; lineStr = chunk.outro + lineStr; } if (chunk.content.length > 0) { lineIndex = chunk.content.lastIndexOf(n$4); if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; lineStr = chunk.content + lineStr; } if (chunk.intro.length > 0) { lineIndex = chunk.intro.lastIndexOf(n$4); if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; lineStr = chunk.intro + lineStr; } } while ((chunk = chunk.previous)); lineIndex = this.intro.lastIndexOf(n$4); if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; return this.intro + lineStr; } slice(start = 0, end = this.original.length) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; let result = ''; // find start chunk let chunk = this.firstChunk; while (chunk && (chunk.start > start || chunk.end <= start)) { // found end chunk before start if (chunk.start < end && chunk.end >= end) { return result; } chunk = chunk.next; } if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); const startChunk = chunk; while (chunk) { if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { result += chunk.intro; } const containsEnd = chunk.start < end && chunk.end >= end; if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); const sliceStart = startChunk === chunk ? start - chunk.start : 0; const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; result += chunk.content.slice(sliceStart, sliceEnd); if (chunk.outro && (!containsEnd || chunk.end === end)) { result += chunk.outro; } if (containsEnd) { break; } chunk = chunk.next; } return result; } // TODO deprecate this? not really very useful snip(start, end) { const clone = this.clone(); clone.remove(0, start); clone.remove(end, clone.original.length); return clone; } _split(index) { if (this.byStart[index] || this.byEnd[index]) return; let chunk = this.lastSearchedChunk; const searchForward = index > chunk.end; while (chunk) { if (chunk.contains(index)) return this._splitChunk(chunk, index); chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; } } _splitChunk(chunk, index) { if (chunk.edited && chunk.content.length) { // zero-length edited chunks are a special case (overlapping replacements) const loc = getLocator$1$1(this.original)(index); throw new Error( `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`, ); } const newChunk = chunk.split(index); this.byEnd[index] = chunk; this.byStart[index] = newChunk; this.byEnd[newChunk.end] = newChunk; if (chunk === this.lastChunk) this.lastChunk = newChunk; this.lastSearchedChunk = chunk; return true; } toString() { let str = this.intro; let chunk = this.firstChunk; while (chunk) { str += chunk.toString(); chunk = chunk.next; } return str + this.outro; } isEmpty() { let chunk = this.firstChunk; do { if ( (chunk.intro.length && chunk.intro.trim()) || (chunk.content.length && chunk.content.trim()) || (chunk.outro.length && chunk.outro.trim()) ) return false; } while ((chunk = chunk.next)); return true; } length() { let chunk = this.firstChunk; let length = 0; do { length += chunk.intro.length + chunk.content.length + chunk.outro.length; } while ((chunk = chunk.next)); return length; } trimLines() { return this.trim('[\\r\\n]'); } trim(charType) { return this.trimStart(charType).trimEnd(charType); } trimEndAborted(charType) { const rx = new RegExp((charType || '\\s') + '+$'); this.outro = this.outro.replace(rx, ''); if (this.outro.length) return true; let chunk = this.lastChunk; do { const end = chunk.end; const aborted = chunk.trimEnd(rx); // if chunk was trimmed, we have a new lastChunk if (chunk.end !== end) { if (this.lastChunk === chunk) { this.lastChunk = chunk.next; } this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) return true; chunk = chunk.previous; } while (chunk); return false; } trimEnd(charType) { this.trimEndAborted(charType); return this; } trimStartAborted(charType) { const rx = new RegExp('^' + (charType || '\\s') + '+'); this.intro = this.intro.replace(rx, ''); if (this.intro.length) return true; let chunk = this.firstChunk; do { const end = chunk.end; const aborted = chunk.trimStart(rx); if (chunk.end !== end) { // special case... if (chunk === this.lastChunk) this.lastChunk = chunk.next; this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) return true; chunk = chunk.next; } while (chunk); return false; } trimStart(charType) { this.trimStartAborted(charType); return this; } hasChanged() { return this.original !== this.toString(); } _replaceRegexp(searchValue, replacement) { function getReplacement(match, str) { if (typeof replacement === 'string') { return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter if (i === '$') return '$'; if (i === '&') return match[0]; const num = +i; if (num < match.length) return match[+i]; return `$${i}`; }); } else { return replacement(...match, match.index, str, match.groups); } } function matchAll(re, str) { let match; const matches = []; while ((match = re.exec(str))) { matches.push(match); } return matches; } if (searchValue.global) { const matches = matchAll(searchValue, this.original); matches.forEach((match) => { if (match.index != null) this.overwrite( match.index, match.index + match[0].length, getReplacement(match, this.original), ); }); } else { const match = this.original.match(searchValue); if (match && match.index != null) this.overwrite( match.index, match.index + match[0].length, getReplacement(match, this.original), ); } return this; } _replaceString(string, replacement) { const { original } = this; const index = original.indexOf(string); if (index !== -1) { this.overwrite(index, index + string.length, replacement); } return this; } replace(searchValue, replacement) { if (typeof searchValue === 'string') { return this._replaceString(searchValue, replacement); } return this._replaceRegexp(searchValue, replacement); } _replaceAllString(string, replacement) { const { original } = this; const stringLength = string.length; for ( let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength) ) { this.overwrite(index, index + stringLength, replacement); } return this; } replaceAll(searchValue, replacement) { if (typeof searchValue === 'string') { return this._replaceAllString(searchValue, replacement); } if (!searchValue.global) { throw new TypeError( 'MagicString.prototype.replaceAll called with a non-global RegExp argument', ); } return this._replaceRegexp(searchValue, replacement); } }; const hasOwnProp = Object.prototype.hasOwnProperty; let Bundle$1 = class Bundle { constructor(options = {}) { this.intro = options.intro || ''; this.separator = options.separator !== undefined ? options.separator : '\n'; this.sources = []; this.uniqueSources = []; this.uniqueSourceIndexByFilename = {}; } addSource(source) { if (source instanceof MagicString$3) { return this.addSource({ content: source, filename: source.filename, separator: this.separator, }); } if (!isObject$1$2(source) || !source.content) { throw new Error( 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`', ); } ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => { if (!hasOwnProp.call(source, option)) source[option] = source.content[option]; }); if (source.separator === undefined) { // TODO there's a bunch of this sort of thing, needs cleaning up source.separator = this.separator; } if (source.filename) { if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) { this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length; this.uniqueSources.push({ filename: source.filename, content: source.content.original }); } else { const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]]; if (source.content.original !== uniqueSource.content) { throw new Error(`Illegal source: same filename (${source.filename}), different contents`); } } } this.sources.push(source); return this; } append(str, options) { this.addSource({ content: new MagicString$3(str), separator: (options && options.separator) || '', }); return this; } clone() { const bundle = new Bundle({ intro: this.intro, separator: this.separator, }); this.sources.forEach((source) => { bundle.addSource({ filename: source.filename, content: source.content.clone(), separator: source.separator, }); }); return bundle; } generateDecodedMap(options = {}) { const names = []; let x_google_ignoreList = undefined; this.sources.forEach((source) => { Object.keys(source.content.storedNames).forEach((name) => { if (!~names.indexOf(name)) names.push(name); }); }); const mappings = new Mappings$3(options.hires); if (this.intro) { mappings.advance(this.intro); } this.sources.forEach((source, i) => { if (i > 0) { mappings.advance(this.separator); } const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1; const magicString = source.content; const locate = getLocator$1$1(magicString.original); if (magicString.intro) { mappings.advance(magicString.intro); } magicString.firstChunk.eachNext((chunk) => { const loc = locate(chunk.start); if (chunk.intro.length) mappings.advance(chunk.intro); if (source.filename) { if (chunk.edited) { mappings.addEdit( sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1, ); } else { mappings.addUneditedChunk( sourceIndex, chunk, magicString.original, loc, magicString.sourcemapLocations, ); } } else { mappings.advance(chunk.content); } if (chunk.outro.length) mappings.advance(chunk.outro); }); if (magicString.outro) { mappings.advance(magicString.outro); } if (source.ignoreList && sourceIndex !== -1) { if (x_google_ignoreList === undefined) { x_google_ignoreList = []; } x_google_ignoreList.push(sourceIndex); } }); return { file: options.file ? options.file.split(/[/\\]/).pop() : undefined, sources: this.uniqueSources.map((source) => { return options.file ? getRelativePath$3(options.file, source.filename) : source.filename; }), sourcesContent: this.uniqueSources.map((source) => { return options.includeContent ? source.content : null; }), names, mappings: mappings.raw, x_google_ignoreList, }; } generateMap(options) { return new SourceMap$4(this.generateDecodedMap(options)); } getIndentString() { const indentStringCounts = {}; this.sources.forEach((source) => { const indentStr = source.content._getRawIndentString(); if (indentStr === null) return; if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0; indentStringCounts[indentStr] += 1; }); return ( Object.keys(indentStringCounts).sort((a, b) => { return indentStringCounts[a] - indentStringCounts[b]; })[0] || '\t' ); } indent(indentStr) { if (!arguments.length) { indentStr = this.getIndentString(); } if (indentStr === '') return this; // noop let trailingNewline = !this.intro || this.intro.slice(-1) === '\n'; this.sources.forEach((source, i) => { const separator = source.separator !== undefined ? source.separator : this.separator; const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator)); source.content.indent(indentStr, { exclude: source.indentExclusionRanges, indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator ) }); trailingNewline = source.content.lastChar() === '\n'; }); if (this.intro) { this.intro = indentStr + this.intro.replace(/^[^\n]/gm, (match, index) => { return index > 0 ? indentStr + match : match; }); } return this; } prepend(str) { this.intro = str + this.intro; return this; } toString() { const body = this.sources .map((source, i) => { const separator = source.separator !== undefined ? source.separator : this.separator; const str = (i > 0 ? separator : '') + source.content.toString(); return str; }) .join(''); return this.intro + body; } isEmpty() { if (this.intro.length && this.intro.trim()) return false; if (this.sources.some((source) => !source.content.isEmpty())) return false; return true; } length() { return this.sources.reduce( (length, source) => length + source.content.length(), this.intro.length, ); } trimLines() { return this.trim('[\\r\\n]'); } trim(charType) { return this.trimStart(charType).trimEnd(charType); } trimStart(charType) { const rx = new RegExp('^' + (charType || '\\s') + '+'); this.intro = this.intro.replace(rx, ''); if (!this.intro) { let source; let i = 0; do { source = this.sources[i++]; if (!source) { break; } } while (!source.content.trimStartAborted(charType)); } return this; } trimEnd(charType) { const rx = new RegExp((charType || '\\s') + '+$'); let source; let i = this.sources.length - 1; do { source = this.sources[i--]; if (!source) { this.intro = this.intro.replace(rx, ''); break; } } while (!source.content.trimEndAborted(charType)); return this; } }; const ANY_SLASH_REGEX = /[/\\]/; function relative$1(from, to) { const fromParts = from.split(ANY_SLASH_REGEX).filter(Boolean); const toParts = to.split(ANY_SLASH_REGEX).filter(Boolean); if (fromParts[0] === '.') fromParts.shift(); if (toParts[0] === '.') toParts.shift(); while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) { fromParts.shift(); toParts.shift(); } while (toParts[0] === '..' && fromParts.length > 0) { toParts.shift(); fromParts.pop(); } while (fromParts.pop()) { toParts.unshift('..'); } return toParts.join('/'); } const needsEscapeRegEx$1 = /[\n\r'\\\u2028\u2029]/; const quoteNewlineRegEx$1 = /([\n\r'\u2028\u2029])/g; const backSlashRegEx$1 = /\\/g; function escapeId$1(id) { if (!needsEscapeRegEx$1.test(id)) return id; return id.replace(backSlashRegEx$1, '\\\\').replace(quoteNewlineRegEx$1, '\\$1'); } const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[/\\|])/; const RELATIVE_PATH_REGEX = /^\.?\.(\/|$)/; function isAbsolute$2(path) { return ABSOLUTE_PATH_REGEX.test(path); } function isRelative$1(path) { return RELATIVE_PATH_REGEX.test(path); } const BACKSLASH_REGEX = /\\/g; function normalize$1(path) { return path.replace(BACKSLASH_REGEX, '/'); } function getAliasName(id) { const base = basename$1(id); return base.slice(0, Math.max(0, base.length - extname(id).length)); } function relativeId(id) { if (!isAbsolute$2(id)) return id; return relative$1(resolve$4(), id); } function isPathFragment(name) { // starting with "/", "./", "../", "C:/" return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute$2(name)); } const UPPER_DIR_REGEX = /^(\.\.\/)*\.\.$/; function getImportPath(importerId, targetPath, stripJsExtension, ensureFileName) { while (targetPath.startsWith('../')) { targetPath = targetPath.slice(3); importerId = '_/' + importerId; } let relativePath = normalize$1(relative$1(dirname$1(importerId), targetPath)); if (stripJsExtension && relativePath.endsWith('.js')) { relativePath = relativePath.slice(0, -3); } if (ensureFileName) { if (relativePath === '') return '../' + basename$1(targetPath); if (UPPER_DIR_REGEX.test(relativePath)) { return [...relativePath.split('/'), '..', basename$1(targetPath)].join('/'); } } return relativePath ? (relativePath.startsWith('..') ? relativePath : './' + relativePath) : '.'; } class ExternalChunk { constructor(module, options, inputBase) { this.options = options; this.inputBase = inputBase; this.defaultVariableName = ''; this.namespaceVariableName = ''; this.variableName = ''; this.fileName = null; this.importAssertions = null; this.id = module.id; this.moduleInfo = module.info; this.renormalizeRenderPath = module.renormalizeRenderPath; this.suggestedVariableName = module.suggestedVariableName; } getFileName() { if (this.fileName) { return this.fileName; } const { paths } = this.options; return (this.fileName = (typeof paths === 'function' ? paths(this.id) : paths[this.id]) || (this.renormalizeRenderPath ? normalize$1(relative$2(this.inputBase, this.id)) : this.id)); } getImportAssertions(snippets) { return (this.importAssertions || (this.importAssertions = formatAssertions$1(this.options.format === 'es' && this.options.externalImportAssertions && this.moduleInfo.assertions, snippets))); } getImportPath(importer) { return escapeId$1(this.renormalizeRenderPath ? getImportPath(importer, this.getFileName(), this.options.format === 'amd', false) : this.getFileName()); } } function formatAssertions$1(assertions, { getObject }) { if (!assertions) { return null; } const assertionEntries = Object.entries(assertions).map(([key, value]) => [key, `'${value}'`]); if (assertionEntries.length > 0) { return getObject(assertionEntries, { lineBreakIndent: null }); } return null; } function getOrCreate(map, key, init) { const existing = map.get(key); if (existing !== undefined) { return existing; } const value = init(); map.set(key, value); return value; } function getNewSet() { return new Set(); } function getNewArray() { return []; } const UnknownKey = Symbol('Unknown Key'); const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key'); const UnknownInteger = Symbol('Unknown Integer'); const SymbolToStringTag = Symbol('Symbol.toStringTag'); const EMPTY_PATH = []; const UNKNOWN_PATH = [UnknownKey]; // For deoptimizations, this means we are modifying an unknown property but did // not lose track of the object or are creating a setter/getter; // For assignment effects it means we do not check for setter/getter effects // but only if something is mutated that is included, which is relevant for // Object.defineProperty const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey]; const UNKNOWN_INTEGER_PATH = [UnknownInteger]; const EntitiesKey = Symbol('Entities'); class PathTracker { constructor() { this.entityPaths = Object.create(null, { [EntitiesKey]: { value: new Set() } }); } trackEntityAtPathAndGetIfTracked(path, entity) { const trackedEntities = this.getEntities(path); if (trackedEntities.has(entity)) return true; trackedEntities.add(entity); return false; } withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) { const trackedEntities = this.getEntities(path); if (trackedEntities.has(entity)) return returnIfTracked; trackedEntities.add(entity); const result = onUntracked(); trackedEntities.delete(entity); return result; } getEntities(path) { let currentPaths = this.entityPaths; for (const pathSegment of path) { currentPaths = currentPaths[pathSegment] = currentPaths[pathSegment] || Object.create(null, { [EntitiesKey]: { value: new Set() } }); } return currentPaths[EntitiesKey]; } } const SHARED_RECURSION_TRACKER = new PathTracker(); class DiscriminatedPathTracker { constructor() { this.entityPaths = Object.create(null, { [EntitiesKey]: { value: new Map() } }); } trackEntityAtPathAndGetIfTracked(path, discriminator, entity) { let currentPaths = this.entityPaths; for (const pathSegment of path) { currentPaths = currentPaths[pathSegment] = currentPaths[pathSegment] || Object.create(null, { [EntitiesKey]: { value: new Map() } }); } const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet)); if (trackedEntities.has(entity)) return true; trackedEntities.add(entity); return false; } } const UnknownValue = Symbol('Unknown Value'); const UnknownTruthyValue = Symbol('Unknown Truthy Value'); class ExpressionEntity { constructor() { this.included = false; } deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) { deoptimizeInteraction(interaction); } deoptimizePath(_path) { } /** * If possible it returns a stringifyable literal value for this node that * can be used for inlining or comparing values. Otherwise, it should return * UnknownValue. */ getLiteralValueAtPath(_path, _recursionTracker, _origin) { return UnknownValue; } getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) { return UNKNOWN_RETURN_EXPRESSION; } hasEffectsOnInteractionAtPath(_path, _interaction, _context) { return true; } include(_context, _includeChildrenRecursively, _options) { this.included = true; } includeCallArguments(context, parameters) { for (const argument of parameters) { argument.include(context, false); } } shouldBeIncluded(_context) { return true; } } const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity { })(); const UNKNOWN_RETURN_EXPRESSION = [ UNKNOWN_EXPRESSION, false ]; const deoptimizeInteraction = (interaction) => { for (const argument of interaction.args) { argument?.deoptimizePath(UNKNOWN_PATH); } }; const INTERACTION_ACCESSED = 0; const INTERACTION_ASSIGNED = 1; const INTERACTION_CALLED = 2; const NODE_INTERACTION_UNKNOWN_ACCESS = { args: [null], type: INTERACTION_ACCESSED }; const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = { args: [null, UNKNOWN_EXPRESSION], type: INTERACTION_ASSIGNED }; // While this is technically a call without arguments, we can compare against // this reference in places where precise values or this argument would make a // difference const NODE_INTERACTION_UNKNOWN_CALL = { args: [null], type: INTERACTION_CALLED, withNew: false }; class Variable extends ExpressionEntity { constructor(name) { super(); this.name = name; this.alwaysRendered = false; this.forbiddenNames = null; this.initReached = false; this.isId = false; this.isReassigned = false; this.kind = null; this.renderBaseName = null; this.renderName = null; } /** * Binds identifiers that reference this variable to this variable. * Necessary to be able to change variable names. */ addReference(_identifier) { } /** * Prevent this variable from being renamed to this name to avoid name * collisions */ forbidName(name) { (this.forbiddenNames || (this.forbiddenNames = new Set())).add(name); } getBaseVariableName() { return this.renderBaseName || this.renderName || this.name; } getName(getPropertyAccess, useOriginalName) { if (useOriginalName?.(this)) { return this.name; } const name = this.renderName || this.name; return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name; } hasEffectsOnInteractionAtPath(path, { type }, _context) { return type !== INTERACTION_ACCESSED || path.length > 0; } /** * Marks this variable as being part of the bundle, which is usually the case when one of * its identifiers becomes part of the bundle. Returns true if it has not been included * previously. * Once a variable is included, it should take care all its declarations are included. */ include() { this.included = true; } markCalledFromTryStatement() { } setRenderNames(baseName, name) { this.renderBaseName = baseName; this.renderName = name; } } class ExternalVariable extends Variable { constructor(module, name) { super(name); this.referenced = false; this.module = module; this.isNamespace = name === '*'; } addReference(identifier) { this.referenced = true; if (this.name === 'default' || this.name === '*') { this.module.suggestName(identifier.name); } } hasEffectsOnInteractionAtPath(path, { type }) { return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0); } include() { if (!this.included) { this.included = true; this.module.used = true; } } } const BLANK = Object.freeze(Object.create(null)); const EMPTY_OBJECT = Object.freeze({}); const EMPTY_ARRAY = Object.freeze([]); const EMPTY_SET = Object.freeze(new (class extends Set { add() { throw new Error('Cannot add to empty set'); } })()); const RESERVED_NAMES = new Set([ 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'implements', 'import', 'in', 'instanceof', 'interface', 'let', 'NaN', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'static', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'undefined', 'var', 'void', 'while', 'with', 'yield' ]); const RESERVED_NAMES$1 = RESERVED_NAMES; const illegalCharacters = /[^\w$]/g; const startsWithDigit = (value) => /\d/.test(value[0]); const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES$1.has(value) || value === 'arguments'; function isLegal(value) { if (needsEscape(value)) { return false; } return !illegalCharacters.test(value); } function makeLegal(value) { value = value .replace(/-(\w)/g, (_, letter) => letter.toUpperCase()) .replace(illegalCharacters, '_'); if (needsEscape(value)) value = `_${value}`; return value || '_'; } const LOGLEVEL_SILENT = 'silent'; const LOGLEVEL_ERROR = 'error'; const LOGLEVEL_WARN = 'warn'; const LOGLEVEL_INFO = 'info'; const LOGLEVEL_DEBUG = 'debug'; const logLevelPriority = { [LOGLEVEL_DEBUG]: 0, [LOGLEVEL_INFO]: 1, [LOGLEVEL_SILENT]: 3, [LOGLEVEL_WARN]: 2 }; /** @typedef {import('./types').Location} Location */ /** * @param {import('./types').Range} range * @param {number} index */ function rangeContains(range, index) { return range.start <= index && index < range.end; } /** * @param {string} source * @param {import('./types').Options} [options] */ function getLocator$3(source, options = {}) { const { offsetLine = 0, offsetColumn = 0 } = options; let start = 0; const ranges = source.split('\n').map((line, i) => { const end = start + line.length + 1; /** @type {import('./types').Range} */ const range = { start, end, line: i }; start = end; return range; }); let i = 0; /** * @param {string | number} search * @param {number} [index] * @returns {Location | undefined} */ function locator(search, index) { if (typeof search === 'string') { search = source.indexOf(search, index ?? 0); } if (search === -1) return undefined; let range = ranges[i]; const d = search >= range.end ? 1 : -1; while (range) { if (rangeContains(range, search)) { return { line: offsetLine + range.line, column: offsetColumn + search - range.start, character: search }; } i += d; range = ranges[i]; } } return locator; } /** * @param {string} source * @param {string | number} search * @param {import('./types').Options} [options] * @returns {Location | undefined} */ function locate(source, search, options) { return getLocator$3(source, options)(search, options && options.startIndex); } function spaces(index) { let result = ''; while (index--) result += ' '; return result; } function tabsToSpaces(value) { return value.replace(/^\t+/, match => match.split('\t').join(' ')); } const LINE_TRUNCATE_LENGTH = 120; const MIN_CHARACTERS_SHOWN_AFTER_LOCATION = 10; const ELLIPSIS = '...'; function getCodeFrame(source, line, column) { let lines = source.split('\n'); // Needed if a plugin did not generate correct sourcemaps if (line > lines.length) return ''; const maxLineLength = Math.max(tabsToSpaces(lines[line - 1].slice(0, column)).length + MIN_CHARACTERS_SHOWN_AFTER_LOCATION + ELLIPSIS.length, LINE_TRUNCATE_LENGTH); const frameStart = Math.max(0, line - 3); let frameEnd = Math.min(line + 2, lines.length); lines = lines.slice(frameStart, frameEnd); while (!/\S/.test(lines[lines.length - 1])) { lines.pop(); frameEnd -= 1; } const digits = String(frameEnd).length; return lines .map((sourceLine, index) => { const isErrorLine = frameStart + index + 1 === line; let lineNumber = String(index + frameStart + 1); while (lineNumber.length < digits) lineNumber = ` ${lineNumber}`; let displayedLine = tabsToSpaces(sourceLine); if (displayedLine.length > maxLineLength) { displayedLine = `${displayedLine.slice(0, maxLineLength - ELLIPSIS.length)}${ELLIPSIS}`; } if (isErrorLine) { const indicator = spaces(digits + 2 + tabsToSpaces(sourceLine.slice(0, column)).length) + '^'; return `${lineNumber}: ${displayedLine}\n${indicator}`; } return `${lineNumber}: ${displayedLine}`; }) .join('\n'); } function printQuotedStringList(list, verbs) { const isSingleItem = list.length <= 1; const quotedList = list.map(item => `"${item}"`); let output = isSingleItem ? quotedList[0] : `${quotedList.slice(0, -1).join(', ')} and ${quotedList.slice(-1)[0]}`; if (verbs) { output += ` ${isSingleItem ? verbs[0] : verbs[1]}`; } return output; } function isValidUrl(url) { try { new URL(url); } catch { return false; } return true; } function getRollupUrl(snippet) { return `https://rollupjs.org/${snippet}`; } function addTrailingSlashIfMissed(url) { if (!url.endsWith('/')) { return url + '/'; } return url; } // troubleshooting const URL_AVOIDING_EVAL = 'troubleshooting/#avoiding-eval'; const URL_NAME_IS_NOT_EXPORTED = 'troubleshooting/#error-name-is-not-exported-by-module'; const URL_THIS_IS_UNDEFINED = 'troubleshooting/#error-this-is-undefined'; const URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY = 'troubleshooting/#warning-treating-module-as-external-dependency'; const URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT = 'troubleshooting/#warning-sourcemap-is-likely-to-be-incorrect'; // configuration-options const URL_MAXPARALLELFILEOPS = 'configuration-options/#maxparallelfileops'; const URL_OUTPUT_AMD_ID = 'configuration-options/#output-amd-id'; const URL_OUTPUT_AMD_BASEPATH = 'configuration-options/#output-amd-basepath'; const URL_OUTPUT_DIR = 'configuration-options/#output-dir'; const URL_OUTPUT_DYNAMICIMPORTFUNCTION = 'configuration-options/#output-dynamicimportfunction'; const URL_OUTPUT_EXPORTS = 'configuration-options/#output-exports'; const URL_OUTPUT_EXTEND = 'configuration-options/#output-extend'; const URL_OUTPUT_FORMAT = 'configuration-options/#output-format'; const URL_OUTPUT_GENERATEDCODE = 'configuration-options/#output-generatedcode'; const URL_OUTPUT_EXPERIMENTALDEEPCHUNKOPTIMIZATION = 'configuration-options/#output-experimentaldeepdynamicchunkoptimization'; const URL_OUTPUT_GENERATEDCODE_CONSTBINDINGS = 'configuration-options/#output-generatedcode-constbindings'; const URL_OUTPUT_GENERATEDCODE_SYMBOLS = 'configuration-options/#output-generatedcode-symbols'; const URL_OUTPUT_GLOBALS = 'configuration-options/#output-globals'; const URL_OUTPUT_INLINEDYNAMICIMPORTS = 'configuration-options/#output-inlinedynamicimports'; const URL_OUTPUT_INTEROP = 'configuration-options/#output-interop'; const URL_OUTPUT_MANUALCHUNKS = 'configuration-options/#output-manualchunks'; const URL_OUTPUT_NAME = 'configuration-options/#output-name'; const URL_OUTPUT_PRESERVEMODULES = 'configuration-options/#output-preservemodules'; const URL_OUTPUT_SOURCEMAPBASEURL = 'configuration-options/#output-sourcemapbaseurl'; const URL_OUTPUT_SOURCEMAPFILE = 'configuration-options/#output-sourcemapfile'; const URL_PRESERVEENTRYSIGNATURES = 'configuration-options/#preserveentrysignatures'; const URL_TREESHAKE = 'configuration-options/#treeshake'; const URL_TREESHAKE_MODULESIDEEFFECTS = 'configuration-options/#treeshake-modulesideeffects'; const URL_WATCH = 'configuration-options/#watch'; const URL_RENDERDYNAMICIMPORT = 'plugin-development/#renderdynamicimport'; const URL_THIS_GETMODULEIDS = 'plugin-development/#this-getmoduleids'; const URL_THIS_GETMODULEINFO = 'plugin-development/#this-getmoduleinfo'; function error$4(base) { if (!(base instanceof Error)) { base = Object.assign(new Error(base.message), base); Object.defineProperty(base, 'name', { value: 'RollupError' }); } throw base; } function augmentCodeLocation(properties, pos, source, id) { if (typeof pos === 'object') { const { line, column } = pos; properties.loc = { column, file: id, line }; } else { properties.pos = pos; const { line, column } = locate(source, pos, { offsetLine: 1 }); properties.loc = { column, file: id, line }; } if (properties.frame === undefined) { const { line, column } = properties.loc; properties.frame = getCodeFrame(source, line, column); } } // Error codes should be sorted alphabetically while errors should be sorted by // error code below const ADDON_ERROR = 'ADDON_ERROR', ALREADY_CLOSED = 'ALREADY_CLOSED', AMBIGUOUS_EXTERNAL_NAMESPACES = 'AMBIGUOUS_EXTERNAL_NAMESPACES', ANONYMOUS_PLUGIN_CACHE = 'ANONYMOUS_PLUGIN_CACHE', ASSET_NOT_FINALISED = 'ASSET_NOT_FINALISED', ASSET_NOT_FOUND = 'ASSET_NOT_FOUND', ASSET_SOURCE_ALREADY_SET = 'ASSET_SOURCE_ALREADY_SET', ASSET_SOURCE_MISSING = 'ASSET_SOURCE_MISSING', BAD_LOADER = 'BAD_LOADER', CANNOT_CALL_NAMESPACE = 'CANNOT_CALL_NAMESPACE', CANNOT_EMIT_FROM_OPTIONS_HOOK = 'CANNOT_EMIT_FROM_OPTIONS_HOOK', CHUNK_NOT_GENERATED = 'CHUNK_NOT_GENERATED', CHUNK_INVALID = 'CHUNK_INVALID', CIRCULAR_DEPENDENCY = 'CIRCULAR_DEPENDENCY', CIRCULAR_REEXPORT = 'CIRCULAR_REEXPORT', CYCLIC_CROSS_CHUNK_REEXPORT = 'CYCLIC_CROSS_CHUNK_REEXPORT', DEPRECATED_FEATURE = 'DEPRECATED_FEATURE', DUPLICATE_PLUGIN_NAME = 'DUPLICATE_PLUGIN_NAME', EMPTY_BUNDLE = 'EMPTY_BUNDLE', EVAL = 'EVAL', EXTERNAL_MODULES_CANNOT_BE_INCLUDED_IN_MANUAL_CHUNKS = 'EXTERNAL_MODULES_CANNOT_BE_INCLUDED_IN_MANUAL_CHUNKS', EXTERNAL_MODULES_CANNOT_BE_TRANSFORMED_TO_MODULES = 'EXTERNAL_MODULES_CANNOT_BE_TRANSFORMED_TO_MODULES', EXTERNAL_SYNTHETIC_EXPORTS = 'EXTERNAL_SYNTHETIC_EXPORTS', FILE_NAME_CONFLICT = 'FILE_NAME_CONFLICT', FILE_NOT_FOUND = 'FILE_NOT_FOUND', FIRST_SIDE_EFFECT = 'FIRST_SIDE_EFFECT', ILLEGAL_IDENTIFIER_AS_NAME = 'ILLEGAL_IDENTIFIER_AS_NAME', ILLEGAL_REASSIGNMENT = 'ILLEGAL_REASSIGNMENT', INCONSISTENT_IMPORT_ASSERTIONS = 'INCONSISTENT_IMPORT_ASSERTIONS', INPUT_HOOK_IN_OUTPUT_PLUGIN = 'INPUT_HOOK_IN_OUTPUT_PLUGIN', INVALID_CHUNK = 'INVALID_CHUNK', INVALID_EXPORT_OPTION = 'INVALID_EXPORT_OPTION', INVALID_EXTERNAL_ID = 'INVALID_EXTERNAL_ID', INVALID_LOG_POSITION = 'INVALID_LOG_POSITION', INVALID_OPTION = 'INVALID_OPTION', INVALID_PLUGIN_HOOK = 'INVALID_PLUGIN_HOOK', INVALID_ROLLUP_PHASE = 'INVALID_ROLLUP_PHASE', INVALID_SETASSETSOURCE = 'INVALID_SETASSETSOURCE', INVALID_TLA_FORMAT = 'INVALID_TLA_FORMAT', MISSING_EXPORT = 'MISSING_EXPORT', MISSING_GLOBAL_NAME = 'MISSING_GLOBAL_NAME', MISSING_IMPLICIT_DEPENDANT = 'MISSING_IMPLICIT_DEPENDANT', MISSING_NAME_OPTION_FOR_IIFE_EXPORT = 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT', MISSING_NODE_BUILTINS = 'MISSING_NODE_BUILTINS', MISSING_OPTION = 'MISSING_OPTION', MIXED_EXPORTS = 'MIXED_EXPORTS', MODULE_LEVEL_DIRECTIVE = 'MODULE_LEVEL_DIRECTIVE', NAMESPACE_CONFLICT = 'NAMESPACE_CONFLICT', NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE = 'NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE', OPTIMIZE_CHUNK_STATUS = 'OPTIMIZE_CHUNK_STATUS', PARSE_ERROR = 'PARSE_ERROR', PLUGIN_ERROR = 'PLUGIN_ERROR', SHIMMED_EXPORT = 'SHIMMED_EXPORT', SOURCEMAP_BROKEN = 'SOURCEMAP_BROKEN', SOURCEMAP_ERROR = 'SOURCEMAP_ERROR', SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT = 'SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT', THIS_IS_UNDEFINED = 'THIS_IS_UNDEFINED', UNEXPECTED_NAMED_IMPORT = 'UNEXPECTED_NAMED_IMPORT', UNKNOWN_OPTION = 'UNKNOWN_OPTION', UNRESOLVED_ENTRY = 'UNRESOLVED_ENTRY', UNRESOLVED_IMPORT = 'UNRESOLVED_IMPORT', UNUSED_EXTERNAL_IMPORT = 'UNUSED_EXTERNAL_IMPORT', VALIDATION_ERROR = 'VALIDATION_ERROR'; function logAddonNotGenerated(message, hook, plugin) { return { code: ADDON_ERROR, message: `Could not retrieve "${hook}". Check configuration of plugin "${plugin}". \tError Message: ${message}` }; } function logAlreadyClosed() { return { code: ALREADY_CLOSED, message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.' }; } function logAmbiguousExternalNamespaces(binding, reexportingModule, usedModule, sources) { return { binding, code: AMBIGUOUS_EXTERNAL_NAMESPACES, ids: sources, message: `Ambiguous external namespace resolution: "${relativeId(reexportingModule)}" re-exports "${binding}" from one of the external modules ${printQuotedStringList(sources.map(module => relativeId(module)))}, guessing "${relativeId(usedModule)}".`, reexporter: reexportingModule }; } function logAnonymousPluginCache() { return { code: ANONYMOUS_PLUGIN_CACHE, message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.' }; } function logAssetNotFinalisedForFileName(name) { return { code: ASSET_NOT_FINALISED, message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first. If you reference assets via import.meta.ROLLUP_FILE_URL_, you need to either have set their source after "renderStart" or need to provide an explicit "fileName" when emitting them.` }; } function logAssetReferenceIdNotFoundForSetSource(assetReferenceId) { return { code: ASSET_NOT_FOUND, message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".` }; } function logAssetSourceAlreadySet(name) { return { code: ASSET_SOURCE_ALREADY_SET, message: `Unable to set the source for asset "${name}", source already set.` }; } function logNoAssetSourceSet(assetName) { return { code: ASSET_SOURCE_MISSING, message: `Plugin error creating asset "${assetName}" - no asset source set.` }; } function logBadLoader(id) { return { code: BAD_LOADER, message: `Error loading "${relativeId(id)}": plugin load hook should return a string, a { code, map } object, or nothing/null.` }; } function logCannotCallNamespace(name) { return { code: CANNOT_CALL_NAMESPACE, message: `Cannot call a namespace ("${name}").` }; } function logCannotEmitFromOptionsHook() { return { code: CANNOT_EMIT_FROM_OPTIONS_HOOK, message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.` }; } function logChunkNotGeneratedForFileName(name) { return { code: CHUNK_NOT_GENERATED, message: `Plugin error - Unable to get file name for emitted chunk "${name}". You can only get file names once chunks have been generated after the "renderStart" hook.` }; } function logChunkInvalid({ fileName, code }, exception) { const errorProperties = { code: CHUNK_INVALID, message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.` }; augmentCodeLocation(errorProperties, exception.loc, code, fileName); return errorProperties; } function logCircularDependency(cyclePath) { return { code: CIRCULAR_DEPENDENCY, ids: cyclePath, message: `Circular dependency: ${cyclePath.map(relativeId).join(' -> ')}` }; } function logCircularReexport(exportName, exporter) { return { code: CIRCULAR_REEXPORT, exporter, message: `"${exportName}" cannot be exported from "${relativeId(exporter)}" as it is a reexport that references itself.` }; } function logCyclicCrossChunkReexport(exportName, exporter, reexporter, importer, preserveModules) { return { code: CYCLIC_CROSS_CHUNK_REEXPORT, exporter, id: importer, message: `Export "${exportName}" of module "${relativeId(exporter)}" was reexported through module "${relativeId(reexporter)}" while both modules are dependencies of each other and will end up in different chunks by current Rollup settings. This scenario is not well supported at the moment as it will produce a circular dependency between chunks and will likely lead to broken execution order.\nEither change the import in "${relativeId(importer)}" to point directly to the exporting module or ${preserveModules ? 'do not use "output.preserveModules"' : 'reconfigure "output.manualChunks"'} to ensure these modules end up in the same chunk.`, reexporter }; } function logDeprecation(deprecation, urlSnippet, plugin) { return { code: DEPRECATED_FEATURE, message: deprecation, url: getRollupUrl(urlSnippet), ...(plugin ? { plugin } : {}) }; } function logDuplicatePluginName(plugin) { return { code: DUPLICATE_PLUGIN_NAME, message: `The plugin name ${plugin} is being used twice in the same build. Plugin names must be distinct or provide a cacheKey (please post an issue to the plugin if you are a plugin user).` }; } function logEmptyChunk(chunkName) { return { code: EMPTY_BUNDLE, message: `Generated an empty chunk: "${chunkName}".`, names: [chunkName] }; } function logEval(id) { return { code: EVAL, id, message: `Use of eval in "${relativeId(id)}" is strongly discouraged as it poses security risks and may cause issues with minification.`, url: getRollupUrl(URL_AVOIDING_EVAL) }; } function logExternalSyntheticExports(id, importer) { return { code: EXTERNAL_SYNTHETIC_EXPORTS, exporter: id, message: `External "${id}" cannot have "syntheticNamedExports" enabled (imported by "${relativeId(importer)}").` }; } function logFileNameConflict(fileName) { return { code: FILE_NAME_CONFLICT, message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.` }; } function logFileReferenceIdNotFoundForFilename(assetReferenceId) { return { code: FILE_NOT_FOUND, message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".` }; } function logFirstSideEffect(source, id, { line, column }) { return { code: FIRST_SIDE_EFFECT, message: `First side effect in ${relativeId(id)} is at (${line}:${column})\n${getCodeFrame(source, line, column)}` }; } function logIllegalIdentifierAsName(name) { return { code: ILLEGAL_IDENTIFIER_AS_NAME, message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`, url: getRollupUrl(URL_OUTPUT_EXTEND) }; } function logIllegalImportReassignment(name, importingId) { return { code: ILLEGAL_REASSIGNMENT, message: `Illegal reassignment of import "${name}" in "${relativeId(importingId)}".` }; } function logInconsistentImportAssertions(existingAssertions, newAssertions, source, importer) { return { code: INCONSISTENT_IMPORT_ASSERTIONS, message: `Module "${relativeId(importer)}" tried to import "${relativeId(source)}" with ${formatAssertions(newAssertions)} assertions, but it was already imported elsewhere with ${formatAssertions(existingAssertions)} assertions. Please ensure that import assertions for the same module are always consistent.` }; } const formatAssertions = (assertions) => { const entries = Object.entries(assertions); if (entries.length === 0) return 'no'; return entries.map(([key, value]) => `"${key}": "${value}"`).join(', '); }; function logInputHookInOutputPlugin(pluginName, hookName) { return { code: INPUT_HOOK_IN_OUTPUT_PLUGIN, message: `The "${hookName}" hook used by the output plugin ${pluginName} is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.` }; } function logCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) { return { code: INVALID_CHUNK, message: `Cannot assign "${relativeId(moduleId)}" to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.` }; } function logInvalidExportOptionValue(optionValue) { return { code: INVALID_EXPORT_OPTION, message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}".`, url: getRollupUrl(URL_OUTPUT_EXPORTS) }; } function logIncompatibleExportOptionValue(optionValue, keys, entryModule) { return { code: INVALID_EXPORT_OPTION, message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${printQuotedStringList(keys)}`, url: getRollupUrl(URL_OUTPUT_EXPORTS) }; } function logInternalIdCannotBeExternal(source, importer) { return { code: INVALID_EXTERNAL_ID, message: `"${source}" is imported as an external by "${relativeId(importer)}", but is already an existing non-external module id.` }; } function logInvalidLogPosition(plugin) { return { code: INVALID_LOG_POSITION, message: `Plugin "${plugin}" tried to add a file position to a log or warning. This is only supported in the "transform" hook at the moment and will be ignored.` }; } function logInvalidOption(option, urlSnippet, explanation, value) { return { code: INVALID_OPTION, message: `Invalid value ${value === undefined ? '' : `${JSON.stringify(value)} `}for option "${option}" - ${explanation}.`, url: getRollupUrl(urlSnippet) }; } function logInvalidAddonPluginHook(hook, plugin) { return { code: INVALID_PLUGIN_HOOK, hook, message: `Error running plugin hook "${hook}" for plugin "${plugin}", expected a string, a function hook or an object with a "handler" string or function.`, plugin }; } function logInvalidFunctionPluginHook(hook, plugin) { return { code: INVALID_PLUGIN_HOOK, hook, message: `Error running plugin hook "${hook}" for plugin "${plugin}", expected a function hook or an object with a "handler" function.`, plugin }; } function logInvalidRollupPhaseForAddWatchFile() { return { code: INVALID_ROLLUP_PHASE, message: `Cannot call "addWatchFile" after the build has finished.` }; } function logInvalidRollupPhaseForChunkEmission() { return { code: INVALID_ROLLUP_PHASE, message: `Cannot emit chunks after module loading has finished.` }; } function logInvalidSetAssetSourceCall() { return { code: INVALID_SETASSETSOURCE, message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.` }; } function logInvalidFormatForTopLevelAwait(id, format) { return { code: INVALID_TLA_FORMAT, id, message: `Module format "${format}" does not support top-level await. Use the "es" or "system" output formats rather.` }; } function logMissingExport(binding, importingModule, exporter) { const isJson = extname(exporter) === '.json'; return { binding, code: MISSING_EXPORT, exporter, id: importingModule, message: `"${binding}" is not exported by "${relativeId(exporter)}", imported by "${relativeId(importingModule)}".${isJson ? ' (Note that you need @rollup/plugin-json to import JSON files)' : ''}`, url: getRollupUrl(URL_NAME_IS_NOT_EXPORTED) }; } function logMissingGlobalName(externalId, guess) { return { code: MISSING_GLOBAL_NAME, id: externalId, message: `No name was provided for external module "${externalId}" in "output.globals" – guessing "${guess}".`, names: [guess], url: getRollupUrl(URL_OUTPUT_GLOBALS) }; } function logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) { return { code: MISSING_IMPLICIT_DEPENDANT, message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.` }; } function logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) { return { code: MISSING_IMPLICIT_DEPENDANT, message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.` }; } function logImplicitDependantIsNotIncluded(module) { const implicitDependencies = [...module.implicitlyLoadedBefore] .map(dependency => relativeId(dependency.id)) .sort(); return { code: MISSING_IMPLICIT_DEPENDANT, message: `Module "${relativeId(module.id)}" that should be implicitly loaded before ${printQuotedStringList(implicitDependencies)} is not included in the module graph. Either it was not imported by an included module or only via a tree-shaken dynamic import, or no imported bindings were used and it had otherwise no side-effects.` }; } function logMissingNameOptionForIifeExport() { return { code: MISSING_NAME_OPTION_FOR_IIFE_EXPORT, message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`, url: getRollupUrl(URL_OUTPUT_NAME) }; } function logMissingNameOptionForUmdExport() { return { code: MISSING_NAME_OPTION_FOR_IIFE_EXPORT, message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.', url: getRollupUrl(URL_OUTPUT_NAME) }; } function logMissingNodeBuiltins(externalBuiltins) { return { code: MISSING_NODE_BUILTINS, ids: externalBuiltins, message: `Creating a browser bundle that depends on Node.js built-in modules (${printQuotedStringList(externalBuiltins)}). You might need to include https://github.com/FredKSchott/rollup-plugin-polyfill-node` }; } // eslint-disable-next-line unicorn/prevent-abbreviations function logMissingFileOrDirOption() { return { code: MISSING_OPTION, message: 'You must specify "output.file" or "output.dir" for the build.', url: getRollupUrl(URL_OUTPUT_DIR) }; } function logMixedExport(facadeModuleId, name) { return { code: MIXED_EXPORTS, id: facadeModuleId, message: `Entry module "${relativeId(facadeModuleId)}" is using named and default exports together. Consumers of your bundle will have to use \`${name || 'chunk'}.default\` to access the default export, which may not be what you want. Use \`output.exports: "named"\` to disable this warning.`, url: getRollupUrl(URL_OUTPUT_EXPORTS) }; } function logModuleLevelDirective(directive, id) { return { code: MODULE_LEVEL_DIRECTIVE, id, message: `Module level directives cause errors when bundled, "${directive}" in "${relativeId(id)}" was ignored.` }; } function logNamespaceConflict(binding, reexportingModuleId, sources) { return { binding, code: NAMESPACE_CONFLICT, ids: sources, message: `Conflicting namespaces: "${relativeId(reexportingModuleId)}" re-exports "${binding}" from one of the modules ${printQuotedStringList(sources.map(moduleId => relativeId(moduleId)))} (will be ignored).`, reexporter: reexportingModuleId }; } function logNoTransformMapOrAstWithoutCode(pluginName) { return { code: NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE, message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` + 'a "code". This will be ignored.' }; } function logOptimizeChunkStatus(chunks, smallChunks, pointInTime) { return { code: OPTIMIZE_CHUNK_STATUS, message: `${pointInTime}, there are\n` + `${chunks} chunks, of which\n` + `${smallChunks} are below minChunkSize.` }; } function logParseError(error, moduleId) { let message = error.message.replace(/ \(\d+:\d+\)$/, ''); if (moduleId.endsWith('.json')) { message += ' (Note that you need @rollup/plugin-json to import JSON files)'; } else if (!moduleId.endsWith('.js')) { message += ' (Note that you need plugins to import files that are not JavaScript)'; } return { cause: error, code: PARSE_ERROR, id: moduleId, message }; } function logPluginError(error, plugin, { hook, id } = {}) { const code = error.code; if (!error.pluginCode && code != null && (typeof code !== 'string' || (typeof code === 'string' && !code.startsWith('PLUGIN_')))) { error.pluginCode = code; } error.code = PLUGIN_ERROR; error.plugin = plugin; if (hook) { error.hook = hook; } if (id) { error.id = id; } return error; } function logShimmedExport(id, binding) { return { binding, code: SHIMMED_EXPORT, exporter: id, message: `Missing export "${binding}" has been shimmed in module "${relativeId(id)}".` }; } function logSourcemapBroken(plugin) { return { code: SOURCEMAP_BROKEN, message: `Sourcemap is likely to be incorrect: a plugin (${plugin}) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help`, plugin, url: getRollupUrl(URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT) }; } function logConflictingSourcemapSources(filename) { return { code: SOURCEMAP_BROKEN, message: `Multiple conflicting contents for sourcemap source ${filename}` }; } function logInvalidSourcemapForError(error, id, column, line, pos) { return { cause: error, code: SOURCEMAP_ERROR, id, loc: { column, file: id, line }, message: `Error when using sourcemap for reporting an error: ${error.message}`, pos }; } function logSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) { return { code: SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT, exporter: id, message: `Module "${relativeId(id)}" that is marked with \`syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}\` needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default' ? `an explicit export named "${syntheticNamedExportsOption}"` : 'a default export'} that does not reexport an unresolved named export of the same module.` }; } function logThisIsUndefined() { return { code: THIS_IS_UNDEFINED, message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`, url: getRollupUrl(URL_THIS_IS_UNDEFINED) }; } function logUnexpectedNamedImport(id, imported, isReexport) { const importType = isReexport ? 'reexport' : 'import'; return { code: UNEXPECTED_NAMED_IMPORT, exporter: id, message: `The named export "${imported}" was ${importType}ed from the external module "${relativeId(id)}" even though its interop type is "defaultOnly". Either remove or change this ${importType} or change the value of the "output.interop" option.`, url: getRollupUrl(URL_OUTPUT_INTEROP) }; } function logUnexpectedNamespaceReexport(id) { return { code: UNEXPECTED_NAMED_IMPORT, exporter: id, message: `There was a namespace "*" reexport from the external module "${relativeId(id)}" even though its interop type is "defaultOnly". This will be ignored as namespace reexports only reexport named exports. If this is not intended, either remove or change this reexport or change the value of the "output.interop" option.`, url: getRollupUrl(URL_OUTPUT_INTEROP) }; } function logUnknownOption(optionType, unknownOptions, validOptions) { return { code: UNKNOWN_OPTION, message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${validOptions.join(', ')}` }; } function logEntryCannotBeExternal(unresolvedId) { return { code: UNRESOLVED_ENTRY, message: `Entry module "${relativeId(unresolvedId)}" cannot be external.` }; } function logExternalModulesCannotBeIncludedInManualChunks(source) { return { code: EXTERNAL_MODULES_CANNOT_BE_INCLUDED_IN_MANUAL_CHUNKS, message: `"${source}" cannot be included in manualChunks because it is resolved as an external module by the "external" option or plugins.` }; } function logExternalModulesCannotBeTransformedToModules(source) { return { code: EXTERNAL_MODULES_CANNOT_BE_TRANSFORMED_TO_MODULES, message: `${source} is resolved as a module now, but it was an external module before. Please check whether there are conflicts in your Rollup options "external" and "manualChunks", manualChunks cannot include external modules.` }; } function logUnresolvedEntry(unresolvedId) { return { code: UNRESOLVED_ENTRY, message: `Could not resolve entry module "${relativeId(unresolvedId)}".` }; } function logUnresolvedImport(source, importer) { return { code: UNRESOLVED_IMPORT, exporter: source, id: importer, message: `Could not resolve "${source}" from "${relativeId(importer)}"` }; } function logUnresolvedImportTreatedAsExternal(source, importer) { return { code: UNRESOLVED_IMPORT, exporter: source, id: importer, message: `"${source}" is imported by "${relativeId(importer)}", but could not be resolved – treating it as an external dependency.`, url: getRollupUrl(URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY) }; } function logUnusedExternalImports(externalId, names, importers) { return { code: UNUSED_EXTERNAL_IMPORT, exporter: externalId, ids: importers, message: `${printQuotedStringList(names, [ 'is', 'are' ])} imported from external module "${externalId}" but never used in ${printQuotedStringList(importers.map(importer => relativeId(importer)))}.`, names }; } function logFailedValidation(message) { return { code: VALIDATION_ERROR, message }; } function warnDeprecation(deprecation, urlSnippet, activeDeprecation, options, plugin) { warnDeprecationWithOptions(deprecation, urlSnippet, activeDeprecation, options.onLog, options.strictDeprecations, plugin); } function warnDeprecationWithOptions(deprecation, urlSnippet, activeDeprecation, log, strictDeprecations, plugin) { if (activeDeprecation || strictDeprecations) { const warning = logDeprecation(deprecation, urlSnippet, plugin); if (strictDeprecations) { return error$4(warning); } log(LOGLEVEL_WARN, warning); } } class ExternalModule { constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, assertions) { this.options = options; this.id = id; this.renormalizeRenderPath = renormalizeRenderPath; this.dynamicImporters = []; this.execIndex = Infinity; this.exportedVariables = new Map(); this.importers = []; this.reexported = false; this.used = false; this.declarations = new Map(); this.mostCommonSuggestion = 0; this.nameSuggestions = new Map(); this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop()); const { importers, dynamicImporters } = this; const info = (this.info = { assertions, ast: null, code: null, dynamicallyImportedIdResolutions: EMPTY_ARRAY, dynamicallyImportedIds: EMPTY_ARRAY, get dynamicImporters() { return dynamicImporters.sort(); }, exportedBindings: null, exports: null, hasDefaultExport: null, get hasModuleSideEffects() { warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', URL_THIS_GETMODULEINFO, true, options); return info.moduleSideEffects; }, id, implicitlyLoadedAfterOneOf: EMPTY_ARRAY, implicitlyLoadedBefore: EMPTY_ARRAY, importedIdResolutions: EMPTY_ARRAY, importedIds: EMPTY_ARRAY, get importers() { return importers.sort(); }, isEntry: false, isExternal: true, isIncluded: null, meta, moduleSideEffects, syntheticNamedExports: false }); // Hide the deprecated key so that it only warns when accessed explicitly Object.defineProperty(this.info, 'hasModuleSideEffects', { enumerable: false }); } getVariableForExportName(name) { const declaration = this.declarations.get(name); if (declaration) return [declaration]; const externalVariable = new ExternalVariable(this, name); this.declarations.set(name, externalVariable); this.exportedVariables.set(externalVariable, name); return [externalVariable]; } suggestName(name) { const value = (this.nameSuggestions.get(name) ?? 0) + 1; this.nameSuggestions.set(name, value); if (value > this.mostCommonSuggestion) { this.mostCommonSuggestion = value; this.suggestedVariableName = name; } } warnUnusedImports() { const unused = [...this.declarations] .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced) .map(([name]) => name); if (unused.length === 0) return; const importersSet = new Set(); for (const name of unused) { for (const importer of this.declarations.get(name).module.importers) { importersSet.add(importer); } } const importersArray = [...importersSet]; this.options.onLog(LOGLEVEL_WARN, logUnusedExternalImports(this.id, unused, importersArray)); } } function getDefaultExportFromCjs$3 (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function getAugmentedNamespace$1(n) { if (n.__esModule) return n; var f = n.default; if (typeof f == "function") { var a = function a () { if (this instanceof a) { return Reflect.construct(f, arguments, this.constructor); } return f.apply(this, arguments); }; a.prototype = f.prototype; } else a = {}; Object.defineProperty(a, '__esModule', {value: true}); Object.keys(n).forEach(function (k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, get: function () { return n[k]; } }); }); return a; } var utils$3$3 = {}; const path$1$3 = require$$0$4; const WIN_SLASH$3 = '\\\\/'; const WIN_NO_SLASH$3 = `[^${WIN_SLASH$3}]`; /** * Posix glob regex */ const DOT_LITERAL$3 = '\\.'; const PLUS_LITERAL$3 = '\\+'; const QMARK_LITERAL$3 = '\\?'; const SLASH_LITERAL$3 = '\\/'; const ONE_CHAR$3 = '(?=.)'; const QMARK$3 = '[^/]'; const END_ANCHOR$3 = `(?:${SLASH_LITERAL$3}|$)`; const START_ANCHOR$3 = `(?:^|${SLASH_LITERAL$3})`; const DOTS_SLASH$3 = `${DOT_LITERAL$3}{1,2}${END_ANCHOR$3}`; const NO_DOT$3 = `(?!${DOT_LITERAL$3})`; const NO_DOTS$3 = `(?!${START_ANCHOR$3}${DOTS_SLASH$3})`; const NO_DOT_SLASH$3 = `(?!${DOT_LITERAL$3}{0,1}${END_ANCHOR$3})`; const NO_DOTS_SLASH$3 = `(?!${DOTS_SLASH$3})`; const QMARK_NO_DOT$3 = `[^.${SLASH_LITERAL$3}]`; const STAR$3 = `${QMARK$3}*?`; const POSIX_CHARS$3 = { DOT_LITERAL: DOT_LITERAL$3, PLUS_LITERAL: PLUS_LITERAL$3, QMARK_LITERAL: QMARK_LITERAL$3, SLASH_LITERAL: SLASH_LITERAL$3, ONE_CHAR: ONE_CHAR$3, QMARK: QMARK$3, END_ANCHOR: END_ANCHOR$3, DOTS_SLASH: DOTS_SLASH$3, NO_DOT: NO_DOT$3, NO_DOTS: NO_DOTS$3, NO_DOT_SLASH: NO_DOT_SLASH$3, NO_DOTS_SLASH: NO_DOTS_SLASH$3, QMARK_NO_DOT: QMARK_NO_DOT$3, STAR: STAR$3, START_ANCHOR: START_ANCHOR$3 }; /** * Windows glob regex */ const WINDOWS_CHARS$3 = { ...POSIX_CHARS$3, SLASH_LITERAL: `[${WIN_SLASH$3}]`, QMARK: WIN_NO_SLASH$3, STAR: `${WIN_NO_SLASH$3}*?`, DOTS_SLASH: `${DOT_LITERAL$3}{1,2}(?:[${WIN_SLASH$3}]|$)`, NO_DOT: `(?!${DOT_LITERAL$3})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH$3}])${DOT_LITERAL$3}{1,2}(?:[${WIN_SLASH$3}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL$3}{0,1}(?:[${WIN_SLASH$3}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL$3}{1,2}(?:[${WIN_SLASH$3}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH$3}]`, START_ANCHOR: `(?:^|[${WIN_SLASH$3}])`, END_ANCHOR: `(?:[${WIN_SLASH$3}]|$)` }; /** * POSIX Bracket Regex */ const POSIX_REGEX_SOURCE$1$3 = { 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 constants$2$3 = { MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1$3, // regular expressions 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, // Replace globs with equivalent patterns to reduce parsing time. REPLACEMENTS: { '***': '*', '**/**': '**', '**/**/**': '**' }, // Digits CHAR_0: 48, /* 0 */ CHAR_9: 57, /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 65, /* A */ CHAR_LOWERCASE_A: 97, /* a */ CHAR_UPPERCASE_Z: 90, /* Z */ CHAR_LOWERCASE_Z: 122, /* z */ CHAR_LEFT_PARENTHESES: 40, /* ( */ CHAR_RIGHT_PARENTHESES: 41, /* ) */ CHAR_ASTERISK: 42, /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: 38, /* & */ CHAR_AT: 64, /* @ */ CHAR_BACKWARD_SLASH: 92, /* \ */ CHAR_CARRIAGE_RETURN: 13, /* \r */ 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, /* \f */ 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, /* \n */ CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ 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, /* \t */ CHAR_UNDERSCORE: 95, /* _ */ CHAR_VERTICAL_LINE: 124, /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ SEP: path$1$3.sep, /** * Create EXTGLOB_CHARS */ extglobChars(chars) { return { '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, '?': { type: 'qmark', open: '(?:', close: ')?' }, '+': { type: 'plus', open: '(?:', close: ')+' }, '*': { type: 'star', open: '(?:', close: ')*' }, '@': { type: 'at', open: '(?:', close: ')' } }; }, /** * Create GLOB_CHARS */ globChars(win32) { return win32 === true ? WINDOWS_CHARS$3 : POSIX_CHARS$3; } }; (function (exports) { const path = require$$0$4; const win32 = process.platform === 'win32'; const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = constants$2$3; exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); exports.removeBackslashes = str => { return str.replace(REGEX_REMOVE_BACKSLASH, match => { return match === '\\' ? '' : match; }); }; exports.supportsLookbehinds = () => { const segs = process.version.slice(1).split('.').map(Number); if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { return true; } return false; }; exports.isWindows = options => { if (options && typeof options.windows === 'boolean') { return options.windows; } return win32 === true || path.sep === '\\'; }; exports.escapeLast = (input, char, lastIdx) => { const idx = input.lastIndexOf(char, lastIdx); if (idx === -1) return input; if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); return `${input.slice(0, idx)}\\${input.slice(idx)}`; }; exports.removePrefix = (input, state = {}) => { let output = input; if (output.startsWith('./')) { output = output.slice(2); state.prefix = './'; } return output; }; exports.wrapOutput = (input, state = {}, options = {}) => { const prepend = options.contains ? '' : '^'; const append = options.contains ? '' : '$'; let output = `${prepend}(?:${input})${append}`; if (state.negated === true) { output = `(?:^(?!${output}).*$)`; } return output; }; } (utils$3$3)); const utils$2$3 = utils$3$3; const { CHAR_ASTERISK: CHAR_ASTERISK$3, /* * */ CHAR_AT: CHAR_AT$3, /* @ */ CHAR_BACKWARD_SLASH: CHAR_BACKWARD_SLASH$3, /* \ */ CHAR_COMMA: CHAR_COMMA$4, /* , */ CHAR_DOT: CHAR_DOT$4, /* . */ CHAR_EXCLAMATION_MARK: CHAR_EXCLAMATION_MARK$3, /* ! */ CHAR_FORWARD_SLASH: CHAR_FORWARD_SLASH$3, /* / */ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$4, /* { */ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$4, /* ( */ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$4, /* [ */ CHAR_PLUS: CHAR_PLUS$3, /* + */ CHAR_QUESTION_MARK: CHAR_QUESTION_MARK$3, /* ? */ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$4, /* } */ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$4, /* ) */ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$4 /* ] */ } = constants$2$3; const isPathSeparator$3 = code => { return code === CHAR_FORWARD_SLASH$3 || code === CHAR_BACKWARD_SLASH$3; }; const depth$3 = token => { if (token.isPrefix !== true) { token.depth = token.isGlobstar ? Infinity : 1; } }; /** * Quickly scans a glob pattern and returns an object with a handful of * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). * * ```js * const pm = require('picomatch'); * console.log(pm.scan('foo/bar/*.js')); * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } * ``` * @param {String} `str` * @param {Object} `options` * @return {Object} Returns an object with tokens and regex source string. * @api public */ const scan$1$3 = (input, options) => { const opts = options || {}; const length = input.length - 1; const scanToEnd = opts.parts === true || opts.scanToEnd === true; const slashes = []; const tokens = []; const parts = []; let str = input; let index = -1; let start = 0; let lastIndex = 0; let isBrace = false; let isBracket = false; let isGlob = false; let isExtglob = false; let isGlobstar = false; let braceEscaped = false; let backslashes = false; let negated = false; let negatedExtglob = false; let finished = false; let braces = 0; let prev; let code; let token = { value: '', depth: 0, isGlob: false }; const eos = () => index >= length; const peek = () => str.charCodeAt(index + 1); const advance = () => { prev = code; return str.charCodeAt(++index); }; while (index < length) { code = advance(); let next; if (code === CHAR_BACKWARD_SLASH$3) { backslashes = token.backslashes = true; code = advance(); if (code === CHAR_LEFT_CURLY_BRACE$4) { braceEscaped = true; } continue; } if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$4) { braces++; while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH$3) { backslashes = token.backslashes = true; advance(); continue; } if (code === CHAR_LEFT_CURLY_BRACE$4) { braces++; continue; } if (braceEscaped !== true && code === CHAR_DOT$4 && (code = advance()) === CHAR_DOT$4) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (braceEscaped !== true && code === CHAR_COMMA$4) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_RIGHT_CURLY_BRACE$4) { braces--; if (braces === 0) { braceEscaped = false; isBrace = token.isBrace = true; finished = true; break; } } } if (scanToEnd === true) { continue; } break; } if (code === CHAR_FORWARD_SLASH$3) { slashes.push(index); tokens.push(token); token = { value: '', depth: 0, isGlob: false }; if (finished === true) continue; if (prev === CHAR_DOT$4 && index === (start + 1)) { start += 2; continue; } lastIndex = index + 1; continue; } if (opts.noext !== true) { const isExtglobChar = code === CHAR_PLUS$3 || code === CHAR_AT$3 || code === CHAR_ASTERISK$3 || code === CHAR_QUESTION_MARK$3 || code === CHAR_EXCLAMATION_MARK$3; if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$4) { isGlob = token.isGlob = true; isExtglob = token.isExtglob = true; finished = true; if (code === CHAR_EXCLAMATION_MARK$3 && index === start) { negatedExtglob = true; } if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH$3) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES$4) { isGlob = token.isGlob = true; finished = true; break; } } continue; } break; } } if (code === CHAR_ASTERISK$3) { if (prev === CHAR_ASTERISK$3) isGlobstar = token.isGlobstar = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_QUESTION_MARK$3) { isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_LEFT_SQUARE_BRACKET$4) { while (eos() !== true && (next = advance())) { if (next === CHAR_BACKWARD_SLASH$3) { backslashes = token.backslashes = true; advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET$4) { isBracket = token.isBracket = true; isGlob = token.isGlob = true; finished = true; break; } } if (scanToEnd === true) { continue; } break; } if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK$3 && index === start) { negated = token.negated = true; start++; continue; } if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$4) { isGlob = token.isGlob = true; if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_LEFT_PARENTHESES$4) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES$4) { finished = true; break; } } continue; } break; } if (isGlob === true) { finished = true; if (scanToEnd === true) { continue; } break; } } if (opts.noext === true) { isExtglob = false; isGlob = false; } let base = str; let prefix = ''; let glob = ''; if (start > 0) { prefix = str.slice(0, start); str = str.slice(start); lastIndex -= start; } if (base && isGlob === true && lastIndex > 0) { base = str.slice(0, lastIndex); glob = str.slice(lastIndex); } else if (isGlob === true) { base = ''; glob = str; } else { base = str; } if (base && base !== '' && base !== '/' && base !== str) { if (isPathSeparator$3(base.charCodeAt(base.length - 1))) { base = base.slice(0, -1); } } if (opts.unescape === true) { if (glob) glob = utils$2$3.removeBackslashes(glob); if (base && backslashes === true) { base = utils$2$3.removeBackslashes(base); } } const state = { prefix, input, start, base, glob, isBrace, isBracket, isGlob, isExtglob, isGlobstar, negated, negatedExtglob }; if (opts.tokens === true) { state.maxDepth = 0; if (!isPathSeparator$3(code)) { tokens.push(token); } state.tokens = tokens; } if (opts.parts === true || opts.tokens === true) { let prevIndex; for (let idx = 0; idx < slashes.length; idx++) { const n = prevIndex ? prevIndex + 1 : start; const i = slashes[idx]; const value = input.slice(n, i); if (opts.tokens) { if (idx === 0 && start !== 0) { tokens[idx].isPrefix = true; tokens[idx].value = prefix; } else { tokens[idx].value = value; } depth$3(tokens[idx]); state.maxDepth += tokens[idx].depth; } if (idx !== 0 || value !== '') { parts.push(value); } prevIndex = i; } if (prevIndex && prevIndex + 1 < input.length) { const value = input.slice(prevIndex + 1); parts.push(value); if (opts.tokens) { tokens[tokens.length - 1].value = value; depth$3(tokens[tokens.length - 1]); state.maxDepth += tokens[tokens.length - 1].depth; } } state.slashes = slashes; state.parts = parts; } return state; }; var scan_1$3 = scan$1$3; const constants$1$3 = constants$2$3; const utils$1$3 = utils$3$3; /** * Constants */ const { MAX_LENGTH: MAX_LENGTH$4, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$4, REGEX_NON_SPECIAL_CHARS: REGEX_NON_SPECIAL_CHARS$3, REGEX_SPECIAL_CHARS_BACKREF: REGEX_SPECIAL_CHARS_BACKREF$3, REPLACEMENTS: REPLACEMENTS$3 } = constants$1$3; /** * Helpers */ const expandRange$3 = (args, options) => { if (typeof options.expandRange === 'function') { return options.expandRange(...args, options); } args.sort(); const value = `[${args.join('-')}]`; return value; }; /** * Create the message for a syntax error */ const syntaxError$3 = (type, char) => { return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; }; /** * Parse the given input string. * @param {String} input * @param {Object} options * @return {Object} */ const parse$2$3 = (input, options) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } input = REPLACEMENTS$3[input] || input; const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$4, opts.maxLength) : MAX_LENGTH$4; let len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } const bos = { type: 'bos', value: '', output: opts.prepend || '' }; const tokens = [bos]; const capture = opts.capture ? '' : '?:'; const win32 = utils$1$3.isWindows(options); // create constants based on platform, for windows or posix const PLATFORM_CHARS = constants$1$3.globChars(win32); const EXTGLOB_CHARS = constants$1$3.extglobChars(PLATFORM_CHARS); const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS; const globstar = opts => { return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const nodot = opts.dot ? '' : NO_DOT; const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; let star = opts.bash === true ? globstar(opts) : STAR; if (opts.capture) { star = `(${star})`; } // minimatch options support if (typeof opts.noext === 'boolean') { opts.noextglob = opts.noext; } const state = { input, index: -1, start: 0, dot: opts.dot === true, consumed: '', output: '', prefix: '', backtrack: false, negated: false, brackets: 0, braces: 0, parens: 0, quotes: 0, globstar: false, tokens }; input = utils$1$3.removePrefix(input, state); len = input.length; const extglobs = []; const braces = []; const stack = []; let prev = bos; let value; /** * Tokenizing helpers */ const eos = () => state.index === len - 1; const peek = state.peek = (n = 1) => input[state.index + n]; const advance = state.advance = () => input[++state.index] || ''; const remaining = () => input.slice(state.index + 1); const consume = (value = '', num = 0) => { state.consumed += value; state.index += num; }; const append = token => { state.output += token.output != null ? token.output : token.value; consume(token.value); }; const negate = () => { let count = 1; while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { advance(); state.start++; count++; } if (count % 2 === 0) { return false; } state.negated = true; state.start++; return true; }; const increment = type => { state[type]++; stack.push(type); }; const decrement = type => { state[type]--; stack.pop(); }; /** * Push tokens onto the tokens array. This helper speeds up * tokenizing by 1) helping us avoid backtracking as much as possible, * and 2) helping us avoid creating extra tokens when consecutive * characters are plain text. This improves performance and simplifies * lookbehinds. */ const push = tok => { if (prev.type === 'globstar') { const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { state.output = state.output.slice(0, -prev.output.length); prev.type = 'star'; prev.value = '*'; prev.output = star; state.output += prev.output; } } if (extglobs.length && tok.type !== 'paren') { extglobs[extglobs.length - 1].inner += tok.value; } if (tok.value || tok.output) append(tok); if (prev && prev.type === 'text' && tok.type === 'text') { prev.value += tok.value; prev.output = (prev.output || '') + tok.value; return; } tok.prev = prev; tokens.push(tok); prev = tok; }; const extglobOpen = (type, value) => { const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; token.prev = prev; token.parens = state.parens; token.output = state.output; const output = (opts.capture ? '(' : '') + token.open; increment('parens'); push({ type, value, output: state.output ? '' : ONE_CHAR }); push({ type: 'paren', extglob: true, value: advance(), output }); extglobs.push(token); }; const extglobClose = token => { let output = token.close + (opts.capture ? ')' : ''); let rest; if (token.type === 'negate') { let extglobStar = star; if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { extglobStar = globstar(opts); } if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { output = token.close = `)$))${extglobStar}`; } if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. // In this case, we need to parse the string and use it in the output of the original pattern. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. // // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. const expression = parse$2$3(rest, { ...options, fastpaths: false }).output; output = token.close = `)${expression})${extglobStar})`; } if (token.prev.type === 'bos') { state.negatedExtglob = true; } } push({ type: 'paren', extglob: true, value, output }); decrement('parens'); }; /** * Fast paths */ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { let backslashes = false; let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF$3, (m, esc, chars, first, rest, index) => { if (first === '\\') { backslashes = true; return m; } if (first === '?') { if (esc) { return esc + first + (rest ? QMARK.repeat(rest.length) : ''); } if (index === 0) { return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); } return QMARK.repeat(chars.length); } if (first === '.') { return DOT_LITERAL.repeat(chars.length); } if (first === '*') { if (esc) { return esc + first + (rest ? star : ''); } return star; } return esc ? m : `\\${m}`; }); if (backslashes === true) { if (opts.unescape === true) { output = output.replace(/\\/g, ''); } else { output = output.replace(/\\+/g, m => { return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); }); } } if (output === input && opts.contains === true) { state.output = input; return state; } state.output = utils$1$3.wrapOutput(output, state, options); return state; } /** * Tokenize input until we reach end-of-string */ while (!eos()) { value = advance(); if (value === '\u0000') { continue; } /** * Escaped characters */ if (value === '\\') { const next = peek(); if (next === '/' && opts.bash !== true) { continue; } if (next === '.' || next === ';') { continue; } if (!next) { value += '\\'; push({ type: 'text', value }); continue; } // collapse slashes to reduce potential for exploits const match = /^\\+/.exec(remaining()); let slashes = 0; if (match && match[0].length > 2) { slashes = match[0].length; state.index += slashes; if (slashes % 2 !== 0) { value += '\\'; } } if (opts.unescape === true) { value = advance(); } else { value += advance(); } if (state.brackets === 0) { push({ type: 'text', value }); continue; } } /** * If we're inside a regex character class, continue * until we reach the closing bracket. */ if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { if (opts.posix !== false && value === ':') { const inner = prev.value.slice(1); if (inner.includes('[')) { prev.posix = true; if (inner.includes(':')) { const idx = prev.value.lastIndexOf('['); const pre = prev.value.slice(0, idx); const rest = prev.value.slice(idx + 2); const posix = POSIX_REGEX_SOURCE$4[rest]; if (posix) { prev.value = pre + posix; state.backtrack = true; advance(); if (!bos.output && tokens.indexOf(prev) === 1) { bos.output = ONE_CHAR; } continue; } } } } if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { value = `\\${value}`; } if (value === ']' && (prev.value === '[' || prev.value === '[^')) { value = `\\${value}`; } if (opts.posix === true && value === '!' && prev.value === '[') { value = '^'; } prev.value += value; append({ value }); continue; } /** * If we're inside a quoted string, continue * until we reach the closing double quote. */ if (state.quotes === 1 && value !== '"') { value = utils$1$3.escapeRegex(value); prev.value += value; append({ value }); continue; } /** * Double quotes */ if (value === '"') { state.quotes = state.quotes === 1 ? 0 : 1; if (opts.keepQuotes === true) { push({ type: 'text', value }); } continue; } /** * Parentheses */ if (value === '(') { increment('parens'); push({ type: 'paren', value }); continue; } if (value === ')') { if (state.parens === 0 && opts.strictBrackets === true) { throw new SyntaxError(syntaxError$3('opening', '(')); } const extglob = extglobs[extglobs.length - 1]; if (extglob && state.parens === extglob.parens + 1) { extglobClose(extglobs.pop()); continue; } push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); decrement('parens'); continue; } /** * Square brackets */ if (value === '[') { if (opts.nobracket === true || !remaining().includes(']')) { if (opts.nobracket !== true && opts.strictBrackets === true) { throw new SyntaxError(syntaxError$3('closing', ']')); } value = `\\${value}`; } else { increment('brackets'); } push({ type: 'bracket', value }); continue; } if (value === ']') { if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { push({ type: 'text', value, output: `\\${value}` }); continue; } if (state.brackets === 0) { if (opts.strictBrackets === true) { throw new SyntaxError(syntaxError$3('opening', '[')); } push({ type: 'text', value, output: `\\${value}` }); continue; } decrement('brackets'); const prevValue = prev.value.slice(1); if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { value = `/${value}`; } prev.value += value; append({ value }); // when literal brackets are explicitly disabled // assume we should match with a regex character class if (opts.literalBrackets === false || utils$1$3.hasRegexChars(prevValue)) { continue; } const escaped = utils$1$3.escapeRegex(prev.value); state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled // assume we should escape the brackets to match literal characters if (opts.literalBrackets === true) { state.output += escaped; prev.value = escaped; continue; } // when the user specifies nothing, try to match both prev.value = `(${capture}${escaped}|${prev.value})`; state.output += prev.value; continue; } /** * Braces */ if (value === '{' && opts.nobrace !== true) { increment('braces'); const open = { type: 'brace', value, output: '(', outputIndex: state.output.length, tokensIndex: state.tokens.length }; braces.push(open); push(open); continue; } if (value === '}') { const brace = braces[braces.length - 1]; if (opts.nobrace === true || !brace) { push({ type: 'text', value, output: value }); continue; } let output = ')'; if (brace.dots === true) { const arr = tokens.slice(); const range = []; for (let i = arr.length - 1; i >= 0; i--) { tokens.pop(); if (arr[i].type === 'brace') { break; } if (arr[i].type !== 'dots') { range.unshift(arr[i].value); } } output = expandRange$3(range, opts); state.backtrack = true; } if (brace.comma !== true && brace.dots !== true) { const out = state.output.slice(0, brace.outputIndex); const toks = state.tokens.slice(brace.tokensIndex); brace.value = brace.output = '\\{'; value = output = '\\}'; state.output = out; for (const t of toks) { state.output += (t.output || t.value); } } push({ type: 'brace', value, output }); decrement('braces'); braces.pop(); continue; } /** * Pipes */ if (value === '|') { if (extglobs.length > 0) { extglobs[extglobs.length - 1].conditions++; } push({ type: 'text', value }); continue; } /** * Commas */ if (value === ',') { let output = value; const brace = braces[braces.length - 1]; if (brace && stack[stack.length - 1] === 'braces') { brace.comma = true; output = '|'; } push({ type: 'comma', value, output }); continue; } /** * Slashes */ if (value === '/') { // if the beginning of the glob is "./", advance the start // to the current index, and don't add the "./" characters // to the state. This greatly simplifies lookbehinds when // checking for BOS characters like "!" and "." (not "./") if (prev.type === 'dot' && state.index === state.start + 1) { state.start = state.index + 1; state.consumed = ''; state.output = ''; tokens.pop(); prev = bos; // reset "prev" to the first token continue; } push({ type: 'slash', value, output: SLASH_LITERAL }); continue; } /** * Dots */ if (value === '.') { if (state.braces > 0 && prev.type === 'dot') { if (prev.value === '.') prev.output = DOT_LITERAL; const brace = braces[braces.length - 1]; prev.type = 'dots'; prev.output += value; prev.value += value; brace.dots = true; continue; } if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { push({ type: 'text', value, output: DOT_LITERAL }); continue; } push({ type: 'dot', value, output: DOT_LITERAL }); continue; } /** * Question marks */ if (value === '?') { const isGroup = prev && prev.value === '('; if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('qmark', value); continue; } if (prev && prev.type === 'paren') { const next = peek(); let output = value; if (next === '<' && !utils$1$3.supportsLookbehinds()) { throw new Error('Node.js v10 or higher is required for regex lookbehinds'); } if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { output = `\\${value}`; } push({ type: 'text', value, output }); continue; } if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { push({ type: 'qmark', value, output: QMARK_NO_DOT }); continue; } push({ type: 'qmark', value, output: QMARK }); continue; } /** * Exclamation */ if (value === '!') { if (opts.noextglob !== true && peek() === '(') { if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { extglobOpen('negate', value); continue; } } if (opts.nonegate !== true && state.index === 0) { negate(); continue; } } /** * Plus */ if (value === '+') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('plus', value); continue; } if ((prev && prev.value === '(') || opts.regex === false) { push({ type: 'plus', value, output: PLUS_LITERAL }); continue; } if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { push({ type: 'plus', value }); continue; } push({ type: 'plus', value: PLUS_LITERAL }); continue; } /** * Plain text */ if (value === '@') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { push({ type: 'at', extglob: true, value, output: '' }); continue; } push({ type: 'text', value }); continue; } /** * Plain text */ if (value !== '*') { if (value === '$' || value === '^') { value = `\\${value}`; } const match = REGEX_NON_SPECIAL_CHARS$3.exec(remaining()); if (match) { value += match[0]; state.index += match[0].length; } push({ type: 'text', value }); continue; } /** * Stars */ if (prev && (prev.type === 'globstar' || prev.star === true)) { prev.type = 'star'; prev.star = true; prev.value += value; prev.output = star; state.backtrack = true; state.globstar = true; consume(value); continue; } let rest = remaining(); if (opts.noextglob !== true && /^\([^?]/.test(rest)) { extglobOpen('star', value); continue; } if (prev.type === 'star') { if (opts.noglobstar === true) { consume(value); continue; } const prior = prev.prev; const before = prior.prev; const isStart = prior.type === 'slash' || prior.type === 'bos'; const afterStar = before && (before.type === 'star' || before.type === 'globstar'); if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { push({ type: 'star', value, output: '' }); continue; } const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { push({ type: 'star', value, output: '' }); continue; } // strip consecutive `/**/` while (rest.slice(0, 3) === '/**') { const after = input[state.index + 4]; if (after && after !== '/') { break; } rest = rest.slice(3); consume('/**', 3); } if (prior.type === 'bos' && eos()) { prev.type = 'globstar'; prev.value += value; prev.output = globstar(opts); state.output = prev.output; state.globstar = true; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); prev.value += value; state.globstar = true; state.output += prior.output + prev.output; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { const end = rest[1] !== void 0 ? '|$' : ''; state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; prev.value += value; state.output += prior.output + prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } if (prior.type === 'bos' && rest[0] === '/') { prev.type = 'globstar'; prev.value += value; prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; state.output = prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } // remove single star from output state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar prev.type = 'globstar'; prev.output = globstar(opts); prev.value += value; // reset output with globstar state.output += prev.output; state.globstar = true; consume(value); continue; } const token = { type: 'star', value, output: star }; if (opts.bash === true) { token.output = '.*?'; if (prev.type === 'bos' || prev.type === 'slash') { token.output = nodot + token.output; } push(token); continue; } if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { token.output = value; push(token); continue; } if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { if (prev.type === 'dot') { state.output += NO_DOT_SLASH; prev.output += NO_DOT_SLASH; } else if (opts.dot === true) { state.output += NO_DOTS_SLASH; prev.output += NO_DOTS_SLASH; } else { state.output += nodot; prev.output += nodot; } if (peek() !== '*') { state.output += ONE_CHAR; prev.output += ONE_CHAR; } } push(token); } while (state.brackets > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$3('closing', ']')); state.output = utils$1$3.escapeLast(state.output, '['); decrement('brackets'); } while (state.parens > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$3('closing', ')')); state.output = utils$1$3.escapeLast(state.output, '('); decrement('parens'); } while (state.braces > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$3('closing', '}')); state.output = utils$1$3.escapeLast(state.output, '{'); decrement('braces'); } if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); } // rebuild the output if we had to backtrack at any point if (state.backtrack === true) { state.output = ''; for (const token of state.tokens) { state.output += token.output != null ? token.output : token.value; if (token.suffix) { state.output += token.suffix; } } } return state; }; /** * Fast paths for creating regular expressions for common glob patterns. * This can significantly speed up processing and has very little downside * impact when none of the fast paths match. */ parse$2$3.fastpaths = (input, options) => { const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$4, opts.maxLength) : MAX_LENGTH$4; const len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } input = REPLACEMENTS$3[input] || input; const win32 = utils$1$3.isWindows(options); // create constants based on platform, for windows or posix const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants$1$3.globChars(win32); const nodot = opts.dot ? NO_DOTS : NO_DOT; const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; const capture = opts.capture ? '' : '?:'; const state = { negated: false, prefix: '' }; let star = opts.bash === true ? '.*?' : STAR; if (opts.capture) { star = `(${star})`; } const globstar = opts => { if (opts.noglobstar === true) return star; return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const create = str => { switch (str) { case '*': return `${nodot}${ONE_CHAR}${star}`; case '.*': return `${DOT_LITERAL}${ONE_CHAR}${star}`; case '*.*': return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '*/*': return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; case '**': return nodot + globstar(opts); case '**/*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; case '**/*.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '**/.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; default: { const match = /^(.*?)\.(\w+)$/.exec(str); if (!match) return; const source = create(match[1]); if (!source) return; return source + DOT_LITERAL + match[2]; } } }; const output = utils$1$3.removePrefix(input, state); let source = create(output); if (source && opts.strictSlashes !== true) { source += `${SLASH_LITERAL}?`; } return source; }; var parse_1$6 = parse$2$3; const path$p = require$$0$4; const scan$4 = scan_1$3; const parse$1$3 = parse_1$6; const utils$n = utils$3$3; const constants$9 = constants$2$3; const isObject$6 = val => val && typeof val === 'object' && !Array.isArray(val); /** * Creates a matcher function from one or more glob patterns. The * returned function takes a string to match as its first argument, * and returns true if the string is a match. The returned matcher * function also takes a boolean as the second argument that, when true, * returns an object with additional information. * * ```js * const picomatch = require('picomatch'); * // picomatch(glob[, options]); * * const isMatch = picomatch('*.!(*a)'); * console.log(isMatch('a.a')); //=> false * console.log(isMatch('a.b')); //=> true * ``` * @name picomatch * @param {String|Array} `globs` One or more glob patterns. * @param {Object=} `options` * @return {Function=} Returns a matcher function. * @api public */ const picomatch$1$3 = (glob, options, returnState = false) => { if (Array.isArray(glob)) { const fns = glob.map(input => picomatch$1$3(input, options, returnState)); const arrayMatcher = str => { for (const isMatch of fns) { const state = isMatch(str); if (state) return state; } return false; }; return arrayMatcher; } const isState = isObject$6(glob) && glob.tokens && glob.input; if (glob === '' || (typeof glob !== 'string' && !isState)) { throw new TypeError('Expected pattern to be a non-empty string'); } const opts = options || {}; const posix = utils$n.isWindows(options); const regex = isState ? picomatch$1$3.compileRe(glob, options) : picomatch$1$3.makeRe(glob, options, false, true); const state = regex.state; delete regex.state; let isIgnored = () => false; if (opts.ignore) { const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; isIgnored = picomatch$1$3(opts.ignore, ignoreOpts, returnState); } const matcher = (input, returnObject = false) => { const { isMatch, match, output } = picomatch$1$3.test(input, regex, options, { glob, posix }); const result = { glob, state, regex, posix, input, output, match, isMatch }; if (typeof opts.onResult === 'function') { opts.onResult(result); } if (isMatch === false) { result.isMatch = false; return returnObject ? result : false; } if (isIgnored(input)) { if (typeof opts.onIgnore === 'function') { opts.onIgnore(result); } result.isMatch = false; return returnObject ? result : false; } if (typeof opts.onMatch === 'function') { opts.onMatch(result); } return returnObject ? result : true; }; if (returnState) { matcher.state = state; } return matcher; }; /** * Test `input` with the given `regex`. This is used by the main * `picomatch()` function to test the input string. * * ```js * const picomatch = require('picomatch'); * // picomatch.test(input, regex[, options]); * * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } * ``` * @param {String} `input` String to test. * @param {RegExp} `regex` * @return {Object} Returns an object with matching info. * @api public */ picomatch$1$3.test = (input, regex, options, { glob, posix } = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected input to be a string'); } if (input === '') { return { isMatch: false, output: '' }; } const opts = options || {}; const format = opts.format || (posix ? utils$n.toPosixSlashes : null); let match = input === glob; let output = (match && format) ? format(input) : input; if (match === false) { output = format ? format(input) : input; match = output === glob; } if (match === false || opts.capture === true) { if (opts.matchBase === true || opts.basename === true) { match = picomatch$1$3.matchBase(input, regex, options, posix); } else { match = regex.exec(output); } } return { isMatch: Boolean(match), match, output }; }; /** * Match the basename of a filepath. * * ```js * const picomatch = require('picomatch'); * // picomatch.matchBase(input, glob[, options]); * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true * ``` * @param {String} `input` String to test. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). * @return {Boolean} * @api public */ picomatch$1$3.matchBase = (input, glob, options, posix = utils$n.isWindows(options)) => { const regex = glob instanceof RegExp ? glob : picomatch$1$3.makeRe(glob, options); return regex.test(path$p.basename(input)); }; /** * Returns true if **any** of the given glob `patterns` match the specified `string`. * * ```js * const picomatch = require('picomatch'); * // picomatch.isMatch(string, patterns[, options]); * * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true * console.log(picomatch.isMatch('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). * @return {Boolean} Returns true if any patterns match `str` * @api public */ picomatch$1$3.isMatch = (str, patterns, options) => picomatch$1$3(patterns, options)(str); /** * Parse a glob pattern to create the source string for a regular * expression. * * ```js * const picomatch = require('picomatch'); * const result = picomatch.parse(pattern[, options]); * ``` * @param {String} `pattern` * @param {Object} `options` * @return {Object} Returns an object with useful properties and output to be used as a regex source string. * @api public */ picomatch$1$3.parse = (pattern, options) => { if (Array.isArray(pattern)) return pattern.map(p => picomatch$1$3.parse(p, options)); return parse$1$3(pattern, { ...options, fastpaths: false }); }; /** * Scan a glob pattern to separate the pattern into segments. * * ```js * const picomatch = require('picomatch'); * // picomatch.scan(input[, options]); * * const result = picomatch.scan('!./foo/*.js'); * console.log(result); * { prefix: '!./', * input: '!./foo/*.js', * start: 3, * base: 'foo', * glob: '*.js', * isBrace: false, * isBracket: false, * isGlob: true, * isExtglob: false, * isGlobstar: false, * negated: true } * ``` * @param {String} `input` Glob pattern to scan. * @param {Object} `options` * @return {Object} Returns an object with * @api public */ picomatch$1$3.scan = (input, options) => scan$4(input, options); /** * Compile a regular expression from the `state` object returned by the * [parse()](#parse) method. * * @param {Object} `state` * @param {Object} `options` * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. * @return {RegExp} * @api public */ picomatch$1$3.compileRe = (state, options, returnOutput = false, returnState = false) => { if (returnOutput === true) { return state.output; } const opts = options || {}; const prepend = opts.contains ? '' : '^'; const append = opts.contains ? '' : '$'; let source = `${prepend}(?:${state.output})${append}`; if (state && state.negated === true) { source = `^(?!${source}).*$`; } const regex = picomatch$1$3.toRegex(source, options); if (returnState === true) { regex.state = state; } return regex; }; /** * Create a regular expression from a parsed glob pattern. * * ```js * const picomatch = require('picomatch'); * const state = picomatch.parse('*.js'); * // picomatch.compileRe(state[, options]); * * console.log(picomatch.compileRe(state)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `state` The object returned from the `.parse` method. * @param {Object} `options` * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. * @return {RegExp} Returns a regex created from the given pattern. * @api public */ picomatch$1$3.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { if (!input || typeof input !== 'string') { throw new TypeError('Expected a non-empty string'); } let parsed = { negated: false, fastpaths: true }; if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { parsed.output = parse$1$3.fastpaths(input, options); } if (!parsed.output) { parsed = parse$1$3(input, options); } return picomatch$1$3.compileRe(parsed, options, returnOutput, returnState); }; /** * Create a regular expression from the given regex source string. * * ```js * const picomatch = require('picomatch'); * // picomatch.toRegex(source[, options]); * * const { output } = picomatch.parse('*.js'); * console.log(picomatch.toRegex(output)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `source` Regular expression source string. * @param {Object} `options` * @return {RegExp} * @api public */ picomatch$1$3.toRegex = (source, options) => { try { const opts = options || {}; return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); } catch (err) { if (options && options.debug === true) throw err; return /$^/; } }; /** * Picomatch constants. * @return {Object} */ picomatch$1$3.constants = constants$9; /** * Expose "picomatch" */ var picomatch_1$3 = picomatch$1$3; var picomatch$8 = picomatch_1$3; const pm$1 = /*@__PURE__*/getDefaultExportFromCjs$3(picomatch$8); const extractors$1 = { ArrayPattern(names, param) { for (const element of param.elements) { if (element) extractors$1[element.type](names, element); } }, AssignmentPattern(names, param) { extractors$1[param.left.type](names, param.left); }, Identifier(names, param) { names.push(param.name); }, MemberExpression() { }, ObjectPattern(names, param) { for (const prop of param.properties) { // @ts-ignore Typescript reports that this is not a valid type if (prop.type === 'RestElement') { extractors$1.RestElement(names, prop); } else { extractors$1[prop.value.type](names, prop.value); } } }, RestElement(names, param) { extractors$1[param.argument.type](names, param.argument); } }; const extractAssignedNames$1 = function extractAssignedNames(param) { const names = []; extractors$1[param.type](names, param); return names; }; // Helper since Typescript can't detect readonly arrays with Array.isArray function isArray$1$2(arg) { return Array.isArray(arg); } function ensureArray$1$1(thing) { if (isArray$1$2(thing)) return thing; if (thing == null) return []; return [thing]; } const normalizePath$7 = function normalizePath(filename) { return filename.split(win32$1.sep).join(posix$2.sep); }; function getMatcherString$3(id, resolutionBase) { if (resolutionBase === false || isAbsolute$3(id) || id.startsWith('**')) { return normalizePath$7(id); } // resolve('') is valid and will default to process.cwd() const basePath = normalizePath$7(resolve$5(resolutionBase || '')) // escape all possible (posix + win) path characters that might interfere with regex .replace(/[-^$*+?.()|[\]{}]/g, '\\$&'); // Note that we use posix.join because: // 1. the basePath has been normalized to use / // 2. the incoming glob (id) matcher, also uses / // otherwise Node will force backslash (\) on windows return posix$2.join(basePath, normalizePath$7(id)); } const createFilter$4 = function createFilter(include, exclude, options) { const resolutionBase = options && options.resolve; const getMatcher = (id) => id instanceof RegExp ? id : { test: (what) => { // this refactor is a tad overly verbose but makes for easy debugging const pattern = getMatcherString$3(id, resolutionBase); const fn = pm$1(pattern, { dot: true }); const result = fn(what); return result; } }; const includeMatchers = ensureArray$1$1(include).map(getMatcher); const excludeMatchers = ensureArray$1$1(exclude).map(getMatcher); return function result(id) { if (typeof id !== 'string') return false; if (/\0/.test(id)) return false; const pathId = normalizePath$7(id); for (let i = 0; i < excludeMatchers.length; ++i) { const matcher = excludeMatchers[i]; if (matcher.test(pathId)) return false; } for (let i = 0; i < includeMatchers.length; ++i) { const matcher = includeMatchers[i]; if (matcher.test(pathId)) return true; } return !includeMatchers.length; }; }; const reservedWords$1$2 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'; const builtins$4 = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'; const forbiddenIdentifiers$3 = new Set(`${reservedWords$1$2} ${builtins$4}`.split(' ')); forbiddenIdentifiers$3.add(''); function createInclusionContext() { return { brokenFlow: false, hasBreak: false, hasContinue: false, includedCallArguments: new Set(), includedLabels: new Set() }; } function createHasEffectsContext() { return { accessed: new PathTracker(), assigned: new PathTracker(), brokenFlow: false, called: new DiscriminatedPathTracker(), hasBreak: false, hasContinue: false, ignore: { breaks: false, continues: false, labels: new Set(), returnYield: false, this: false }, includedLabels: new Set(), instantiated: new DiscriminatedPathTracker(), replacedVariableInits: new Map() }; } function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) { return Object.create(inheritedDescriptions, memberDescriptions); } const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity { getLiteralValueAtPath() { return undefined; } })(); const returnsUnknown = { value: { hasEffectsWhenCalled: null, returns: UNKNOWN_EXPRESSION } }; const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity { getReturnExpressionWhenCalledAtPath(path) { if (path.length === 1) { return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]); } return UNKNOWN_RETURN_EXPRESSION; } hasEffectsOnInteractionAtPath(path, interaction, context) { if (interaction.type === INTERACTION_ACCESSED) { return path.length > 1; } if (interaction.type === INTERACTION_CALLED && path.length === 1) { return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context); } return true; } })(); const returnsBoolean = { value: { hasEffectsWhenCalled: null, returns: UNKNOWN_LITERAL_BOOLEAN } }; const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity { getReturnExpressionWhenCalledAtPath(path) { if (path.length === 1) { return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]); } return UNKNOWN_RETURN_EXPRESSION; } hasEffectsOnInteractionAtPath(path, interaction, context) { if (interaction.type === INTERACTION_ACCESSED) { return path.length > 1; } if (interaction.type === INTERACTION_CALLED && path.length === 1) { return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context); } return true; } })(); const returnsNumber = { value: { hasEffectsWhenCalled: null, returns: UNKNOWN_LITERAL_NUMBER } }; const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity { getReturnExpressionWhenCalledAtPath(path) { if (path.length === 1) { return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]); } return UNKNOWN_RETURN_EXPRESSION; } hasEffectsOnInteractionAtPath(path, interaction, context) { if (interaction.type === INTERACTION_ACCESSED) { return path.length > 1; } if (interaction.type === INTERACTION_CALLED && path.length === 1) { return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context); } return true; } })(); const returnsString = { value: { hasEffectsWhenCalled: null, returns: UNKNOWN_LITERAL_STRING } }; const stringReplace = { value: { hasEffectsWhenCalled({ args }, context) { const argument1 = args[2]; return (args.length < 3 || (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, { deoptimizeCache() { } }) === 'symbol' && argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context))); }, returns: UNKNOWN_LITERAL_STRING } }; const objectMembers = assembleMemberDescriptions({ hasOwnProperty: returnsBoolean, isPrototypeOf: returnsBoolean, propertyIsEnumerable: returnsBoolean, toLocaleString: returnsString, toString: returnsString, valueOf: returnsUnknown }); const literalBooleanMembers = assembleMemberDescriptions({ valueOf: returnsBoolean }, objectMembers); const literalNumberMembers = assembleMemberDescriptions({ toExponential: returnsString, toFixed: returnsString, toLocaleString: returnsString, toPrecision: returnsString, valueOf: returnsNumber }, objectMembers); /** * RegExp are stateful when they have the global or sticky flags set. * But if we actually don't use them, the side effect does not matter. * the check logic in `hasEffectsOnInteractionAtPath`. */ const literalRegExpMembers = assembleMemberDescriptions({ exec: returnsUnknown, test: returnsBoolean }, objectMembers); const literalStringMembers = assembleMemberDescriptions({ anchor: returnsString, at: returnsUnknown, big: returnsString, blink: returnsString, bold: returnsString, charAt: returnsString, charCodeAt: returnsNumber, codePointAt: returnsUnknown, concat: returnsString, endsWith: returnsBoolean, fixed: returnsString, fontcolor: returnsString, fontsize: returnsString, includes: returnsBoolean, indexOf: returnsNumber, italics: returnsString, lastIndexOf: returnsNumber, link: returnsString, localeCompare: returnsNumber, match: returnsUnknown, matchAll: returnsUnknown, normalize: returnsString, padEnd: returnsString, padStart: returnsString, repeat: returnsString, replace: stringReplace, replaceAll: stringReplace, search: returnsNumber, slice: returnsString, small: returnsString, split: returnsUnknown, startsWith: returnsBoolean, strike: returnsString, sub: returnsString, substr: returnsString, substring: returnsString, sup: returnsString, toLocaleLowerCase: returnsString, toLocaleUpperCase: returnsString, toLowerCase: returnsString, toString: returnsString, toUpperCase: returnsString, trim: returnsString, trimEnd: returnsString, trimLeft: returnsString, trimRight: returnsString, trimStart: returnsString, valueOf: returnsString }, objectMembers); function getLiteralMembersForValue(value) { if (value instanceof RegExp) { return literalRegExpMembers; } switch (typeof value) { case 'boolean': { return literalBooleanMembers; } case 'number': { return literalNumberMembers; } case 'string': { return literalStringMembers; } } return Object.create(null); } function hasMemberEffectWhenCalled(members, memberName, interaction, context) { if (typeof memberName !== 'string' || !members[memberName]) { return true; } return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false; } function getMemberReturnExpressionWhenCalled(members, memberName) { if (typeof memberName !== 'string' || !members[memberName]) return UNKNOWN_RETURN_EXPRESSION; return [members[memberName].returns, false]; } // AST walker module for Mozilla Parser API compatible trees function skipThrough$1(node, st, c) { c(node, st); } function ignore$1(_node, _st, _c) {} // Node walkers. var base$1 = {}; base$1.Program = base$1.BlockStatement = base$1.StaticBlock = function (node, st, c) { for (var i = 0, list = node.body; i < list.length; i += 1) { var stmt = list[i]; c(stmt, st, "Statement"); } }; base$1.Statement = skipThrough$1; base$1.EmptyStatement = ignore$1; base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression = function (node, st, c) { return c(node.expression, st, "Expression"); }; base$1.IfStatement = function (node, st, c) { c(node.test, st, "Expression"); c(node.consequent, st, "Statement"); if (node.alternate) { c(node.alternate, st, "Statement"); } }; base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); }; base$1.BreakStatement = base$1.ContinueStatement = ignore$1; base$1.WithStatement = function (node, st, c) { c(node.object, st, "Expression"); c(node.body, st, "Statement"); }; base$1.SwitchStatement = function (node, st, c) { c(node.discriminant, st, "Expression"); for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) { var cs = list$1[i$1]; if (cs.test) { c(cs.test, st, "Expression"); } for (var i = 0, list = cs.consequent; i < list.length; i += 1) { var cons = list[i]; c(cons, st, "Statement"); } } }; base$1.SwitchCase = function (node, st, c) { if (node.test) { c(node.test, st, "Expression"); } for (var i = 0, list = node.consequent; i < list.length; i += 1) { var cons = list[i]; c(cons, st, "Statement"); } }; base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) { if (node.argument) { c(node.argument, st, "Expression"); } }; base$1.ThrowStatement = base$1.SpreadElement = function (node, st, c) { return c(node.argument, st, "Expression"); }; base$1.TryStatement = function (node, st, c) { c(node.block, st, "Statement"); if (node.handler) { c(node.handler, st); } if (node.finalizer) { c(node.finalizer, st, "Statement"); } }; base$1.CatchClause = function (node, st, c) { if (node.param) { c(node.param, st, "Pattern"); } c(node.body, st, "Statement"); }; base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) { c(node.test, st, "Expression"); c(node.body, st, "Statement"); }; base$1.ForStatement = function (node, st, c) { if (node.init) { c(node.init, st, "ForInit"); } if (node.test) { c(node.test, st, "Expression"); } if (node.update) { c(node.update, st, "Expression"); } c(node.body, st, "Statement"); }; base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) { c(node.left, st, "ForInit"); c(node.right, st, "Expression"); c(node.body, st, "Statement"); }; base$1.ForInit = function (node, st, c) { if (node.type === "VariableDeclaration") { c(node, st); } else { c(node, st, "Expression"); } }; base$1.DebuggerStatement = ignore$1; base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); }; base$1.VariableDeclaration = function (node, st, c) { for (var i = 0, list = node.declarations; i < list.length; i += 1) { var decl = list[i]; c(decl, st); } }; base$1.VariableDeclarator = function (node, st, c) { c(node.id, st, "Pattern"); if (node.init) { c(node.init, st, "Expression"); } }; base$1.Function = function (node, st, c) { if (node.id) { c(node.id, st, "Pattern"); } for (var i = 0, list = node.params; i < list.length; i += 1) { var param = list[i]; c(param, st, "Pattern"); } c(node.body, st, node.expression ? "Expression" : "Statement"); }; base$1.Pattern = function (node, st, c) { if (node.type === "Identifier") { c(node, st, "VariablePattern"); } else if (node.type === "MemberExpression") { c(node, st, "MemberPattern"); } else { c(node, st); } }; base$1.VariablePattern = ignore$1; base$1.MemberPattern = skipThrough$1; base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); }; base$1.ArrayPattern = function (node, st, c) { for (var i = 0, list = node.elements; i < list.length; i += 1) { var elt = list[i]; if (elt) { c(elt, st, "Pattern"); } } }; base$1.ObjectPattern = function (node, st, c) { for (var i = 0, list = node.properties; i < list.length; i += 1) { var prop = list[i]; if (prop.type === "Property") { if (prop.computed) { c(prop.key, st, "Expression"); } c(prop.value, st, "Pattern"); } else if (prop.type === "RestElement") { c(prop.argument, st, "Pattern"); } } }; base$1.Expression = skipThrough$1; base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore$1; base$1.ArrayExpression = function (node, st, c) { for (var i = 0, list = node.elements; i < list.length; i += 1) { var elt = list[i]; if (elt) { c(elt, st, "Expression"); } } }; base$1.ObjectExpression = function (node, st, c) { for (var i = 0, list = node.properties; i < list.length; i += 1) { var prop = list[i]; c(prop, st); } }; base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration; base$1.SequenceExpression = function (node, st, c) { for (var i = 0, list = node.expressions; i < list.length; i += 1) { var expr = list[i]; c(expr, st, "Expression"); } }; base$1.TemplateLiteral = function (node, st, c) { for (var i = 0, list = node.quasis; i < list.length; i += 1) { var quasi = list[i]; c(quasi, st); } for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1) { var expr = list$1[i$1]; c(expr, st, "Expression"); } }; base$1.TemplateElement = ignore$1; base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) { c(node.argument, st, "Expression"); }; base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) { c(node.left, st, "Expression"); c(node.right, st, "Expression"); }; base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) { c(node.left, st, "Pattern"); c(node.right, st, "Expression"); }; base$1.ConditionalExpression = function (node, st, c) { c(node.test, st, "Expression"); c(node.consequent, st, "Expression"); c(node.alternate, st, "Expression"); }; base$1.NewExpression = base$1.CallExpression = function (node, st, c) { c(node.callee, st, "Expression"); if (node.arguments) { for (var i = 0, list = node.arguments; i < list.length; i += 1) { var arg = list[i]; c(arg, st, "Expression"); } } }; base$1.MemberExpression = function (node, st, c) { c(node.object, st, "Expression"); if (node.computed) { c(node.property, st, "Expression"); } }; base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) { if (node.declaration) { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); } if (node.source) { c(node.source, st, "Expression"); } }; base$1.ExportAllDeclaration = function (node, st, c) { if (node.exported) { c(node.exported, st); } c(node.source, st, "Expression"); }; base$1.ImportDeclaration = function (node, st, c) { for (var i = 0, list = node.specifiers; i < list.length; i += 1) { var spec = list[i]; c(spec, st); } c(node.source, st, "Expression"); }; base$1.ImportExpression = function (node, st, c) { c(node.source, st, "Expression"); }; base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore$1; base$1.TaggedTemplateExpression = function (node, st, c) { c(node.tag, st, "Expression"); c(node.quasi, st, "Expression"); }; base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); }; base$1.Class = function (node, st, c) { if (node.id) { c(node.id, st, "Pattern"); } if (node.superClass) { c(node.superClass, st, "Expression"); } c(node.body, st); }; base$1.ClassBody = function (node, st, c) { for (var i = 0, list = node.body; i < list.length; i += 1) { var elt = list[i]; c(elt, st); } }; base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) { if (node.computed) { c(node.key, st, "Expression"); } if (node.value) { c(node.value, st, "Expression"); } }; const ArrowFunctionExpression$1 = 'ArrowFunctionExpression'; const BinaryExpression$1 = 'BinaryExpression'; const BlockStatement$1 = 'BlockStatement'; const CallExpression$1 = 'CallExpression'; const ChainExpression$1 = 'ChainExpression'; const ConditionalExpression$1 = 'ConditionalExpression'; const ExportDefaultDeclaration$1 = 'ExportDefaultDeclaration'; const ExportNamedDeclaration$1 = 'ExportNamedDeclaration'; const ExpressionStatement$1 = 'ExpressionStatement'; const FunctionDeclaration$1 = 'FunctionDeclaration'; const Identifier$1 = 'Identifier'; const LogicalExpression$1 = 'LogicalExpression'; const NewExpression$1 = 'NewExpression'; const Program$1 = 'Program'; const Property$1 = 'Property'; const ReturnStatement$1 = 'ReturnStatement'; const SequenceExpression$1 = 'SequenceExpression'; const VariableDeclarator$1 = 'VariableDeclarator'; const VariableDeclaration$1 = 'VariableDeclaration'; // this looks ridiculous, but it prevents sourcemap tooling from mistaking // this for an actual sourceMappingURL let SOURCEMAPPING_URL = 'sourceMa'; SOURCEMAPPING_URL += 'ppingURL'; const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]'; const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${SOURCEMAPPING_URL}=.+`); const ANNOTATION_KEY = '_rollupAnnotations'; const INVALID_COMMENT_KEY = '_rollupRemoved'; function handlePureAnnotationsOfNode(node, state, type = node.type) { const { annotations, code } = state; // eslint-disable-next-line unicorn/consistent-destructuring let comment = annotations[state.annotationIndex]; while (comment && node.start >= comment.end) { markPureNode(node, comment, code); comment = annotations[++state.annotationIndex]; } if (comment && comment.end <= node.end) { base$1[type](node, state, handlePureAnnotationsOfNode); // eslint-disable-next-line unicorn/consistent-destructuring while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) { ++state.annotationIndex; annotateNode(node, comment, false); } } } const neitherWithespaceNorBrackets = /[^\s(]/g; const noWhitespace = /\S/g; function markPureNode(node, comment, code) { const annotatedNodes = []; let invalidAnnotation; const codeInBetween = code.slice(comment.end, node.start); if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) { const parentStart = node.start; while (true) { annotatedNodes.push(node); switch (node.type) { case ExpressionStatement$1: case ChainExpression$1: { node = node.expression; continue; } case SequenceExpression$1: { // if there are parentheses, the annotation would apply to the entire expression if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) { node = node.expressions[0]; continue; } invalidAnnotation = true; break; } case ConditionalExpression$1: { // if there are parentheses, the annotation would apply to the entire expression if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) { node = node.test; continue; } invalidAnnotation = true; break; } case LogicalExpression$1: case BinaryExpression$1: { // if there are parentheses, the annotation would apply to the entire expression if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) { node = node.left; continue; } invalidAnnotation = true; break; } case ExportNamedDeclaration$1: case ExportDefaultDeclaration$1: { node = node.declaration; continue; } case VariableDeclaration$1: { const declaration = node; if (declaration.kind === 'const') { // jsdoc only applies to the first declaration node = declaration.declarations[0].init; continue; } invalidAnnotation = true; break; } case VariableDeclarator$1: { node = node.init; continue; } case FunctionDeclaration$1: case ArrowFunctionExpression$1: case CallExpression$1: case NewExpression$1: { break; } default: { invalidAnnotation = true; } } break; } } else { invalidAnnotation = true; } if (invalidAnnotation) { annotateNode(node, comment, false); } else { for (const node of annotatedNodes) { annotateNode(node, comment, true); } } } function doesNotMatchOutsideComment(code, forbiddenChars) { let nextMatch; while ((nextMatch = forbiddenChars.exec(code)) !== null) { if (nextMatch[0] === '/') { const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex); if (charCodeAfterSlash === 42 /*"*"*/) { forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2; continue; } else if (charCodeAfterSlash === 47 /*"/"*/) { forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1; continue; } } forbiddenChars.lastIndex = 0; return false; } return true; } const annotationsRegexes = [ ['pure', /[#@]__PURE__/], ['noSideEffects', /[#@]__NO_SIDE_EFFECTS__/] ]; function addAnnotations(comments, esTreeAst, code) { const annotations = []; const sourceMappingComments = []; for (const comment of comments) { for (const [annotationType, regex] of annotationsRegexes) { if (regex.test(comment.value)) { annotations.push({ ...comment, annotationType }); } } if (SOURCEMAPPING_URL_RE.test(comment.value)) { sourceMappingComments.push(comment); } } for (const comment of sourceMappingComments) { annotateNode(esTreeAst, comment, false); } handlePureAnnotationsOfNode(esTreeAst, { annotationIndex: 0, annotations, code }); } function annotateNode(node, comment, valid) { const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY; const property = node[key]; if (property) { property.push(comment); } else { node[key] = [comment]; } } const keys = { // TODO this should be removed once ImportExpression follows official ESTree // specs with "null" as default ImportExpression: ['arguments'], Literal: [], Program: ['body'] }; function getAndCreateKeys(esTreeNode) { keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */); return keys[esTreeNode.type]; } const INCLUDE_PARAMETERS = 'variables'; let NodeBase$2 = class NodeBase extends ExpressionEntity { constructor(esTreeNode, parent, parentScope, keepEsTreeNode = false) { super(); /** * Nodes can apply custom deoptimizations once they become part of the * executed code. To do this, they must initialize this as false, implement * applyDeoptimizations and call this from include and hasEffects if they have * custom handlers */ this.deoptimized = false; // Nodes can opt-in to keep the AST if needed during the build pipeline. // Avoid true when possible as large AST takes up memory. this.esTreeNode = keepEsTreeNode ? esTreeNode : null; this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode); this.parent = parent; this.context = parent.context; this.createScope(parentScope); this.parseNode(esTreeNode); this.initialise(); this.context.magicString.addSourcemapLocation(this.start); this.context.magicString.addSourcemapLocation(this.end); } addExportedVariables(_variables, _exportNamesByVariable) { } /** * Override this to bind assignments to variables and do any initialisations * that require the scopes to be populated with variables. */ bind() { for (const key of this.keys) { const value = this[key]; if (Array.isArray(value)) { for (const child of value) { child?.bind(); } } else if (value) { value.bind(); } } } /** * Override if this node should receive a different scope than the parent * scope. */ createScope(parentScope) { this.scope = parentScope; } hasEffects(context) { if (!this.deoptimized) this.applyDeoptimizations(); for (const key of this.keys) { const value = this[key]; if (value === null) continue; if (Array.isArray(value)) { for (const child of value) { if (child?.hasEffects(context)) return true; } } else if (value.hasEffects(context)) return true; } return false; } hasEffectsAsAssignmentTarget(context, _checkAccess) { return (this.hasEffects(context) || this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context)); } include(context, includeChildrenRecursively, _options) { if (!this.deoptimized) this.applyDeoptimizations(); this.included = true; for (const key of this.keys) { const value = this[key]; if (value === null) continue; if (Array.isArray(value)) { for (const child of value) { child?.include(context, includeChildrenRecursively); } } else { value.include(context, includeChildrenRecursively); } } } includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) { this.include(context, includeChildrenRecursively); } /** * Override to perform special initialisation steps after the scope is * initialised */ initialise() { } insertSemicolon(code) { if (code.original[this.end - 1] !== ';') { code.appendLeft(this.end, ';'); } } parseNode(esTreeNode, keepEsTreeNodeKeys) { for (const [key, value] of Object.entries(esTreeNode)) { // That way, we can override this function to add custom initialisation and then call super.parseNode if (this.hasOwnProperty(key)) continue; if (key.charCodeAt(0) === 95 /* _ */) { if (key === ANNOTATION_KEY) { const annotations = value; this.annotations = annotations; if (this.context.options.treeshake.annotations) { this.annotationNoSideEffects = annotations.some(comment => comment.annotationType === 'noSideEffects'); this.annotationPure = annotations.some(comment => comment.annotationType === 'pure'); } } else if (key === INVALID_COMMENT_KEY) { for (const { start, end } of value) this.context.magicString.remove(start, end); } } else if (typeof value !== 'object' || value === null) { this[key] = value; } else if (Array.isArray(value)) { this[key] = []; for (const child of value) { this[key].push(child === null ? null : new (this.context.getNodeConstructor(child.type))(child, this, this.scope, keepEsTreeNodeKeys?.includes(key))); } } else { this[key] = new (this.context.getNodeConstructor(value.type))(value, this, this.scope, keepEsTreeNodeKeys?.includes(key)); } } } render(code, options) { for (const key of this.keys) { const value = this[key]; if (value === null) continue; if (Array.isArray(value)) { for (const child of value) { child?.render(code, options); } } else { value.render(code, options); } } } setAssignedValue(value) { this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED }; } shouldBeIncluded(context) { return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext())); } /** * Just deoptimize everything by default so that when e.g. we do not track * something properly, it is deoptimized. * @protected */ applyDeoptimizations() { this.deoptimized = true; for (const key of this.keys) { const value = this[key]; if (value === null) continue; if (Array.isArray(value)) { for (const child of value) { child?.deoptimizePath(UNKNOWN_PATH); } } else { value.deoptimizePath(UNKNOWN_PATH); } } this.context.requestTreeshakingPass(); } }; class SpreadElement extends NodeBase$2 { deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { if (path.length > 0) { this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker); } } hasEffects(context) { if (!this.deoptimized) this.applyDeoptimizations(); const { propertyReadSideEffects } = this.context.options .treeshake; return (this.argument.hasEffects(context) || (propertyReadSideEffects && (propertyReadSideEffects === 'always' || this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context)))); } applyDeoptimizations() { this.deoptimized = true; // Only properties of properties of the argument could become subject to reassignment // This will also reassign the return values of iterators this.argument.deoptimizePath([UnknownKey, UnknownKey]); this.context.requestTreeshakingPass(); } } class Method extends ExpressionEntity { constructor(description) { super(); this.description = description; } deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) { if (type === INTERACTION_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) { args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH); } } getReturnExpressionWhenCalledAtPath(path, { args }) { if (path.length > 0) { return UNKNOWN_RETURN_EXPRESSION; } return [ this.description.returnsPrimitive || (this.description.returns === 'self' ? args[0] || UNKNOWN_EXPRESSION : this.description.returns()), false ]; } hasEffectsOnInteractionAtPath(path, interaction, context) { const { type } = interaction; if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) { return true; } if (type === INTERACTION_CALLED) { const { args } = interaction; if (this.description.mutatesSelfAsArray === true && args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) { return true; } if (this.description.callsArgs) { for (const argumentIndex of this.description.callsArgs) { if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) { return true; } } } } return false; } } const METHOD_RETURNS_BOOLEAN = [ new Method({ callsArgs: null, mutatesSelfAsArray: false, returns: null, returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN }) ]; const METHOD_RETURNS_STRING = [ new Method({ callsArgs: null, mutatesSelfAsArray: false, returns: null, returnsPrimitive: UNKNOWN_LITERAL_STRING }) ]; const METHOD_RETURNS_NUMBER = [ new Method({ callsArgs: null, mutatesSelfAsArray: false, returns: null, returnsPrimitive: UNKNOWN_LITERAL_NUMBER }) ]; const METHOD_RETURNS_UNKNOWN = [ new Method({ callsArgs: null, mutatesSelfAsArray: false, returns: null, returnsPrimitive: UNKNOWN_EXPRESSION }) ]; const INTEGER_REG_EXP = /^\d+$/; class ObjectEntity extends ExpressionEntity { // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey // and we assume there are no setters or getters constructor(properties, prototypeExpression, immutable = false) { super(); this.prototypeExpression = prototypeExpression; this.immutable = immutable; this.additionalExpressionsToBeDeoptimized = new Set(); this.allProperties = []; this.deoptimizedPaths = Object.create(null); this.expressionsToBeDeoptimizedByKey = Object.create(null); this.gettersByKey = Object.create(null); this.hasLostTrack = false; this.hasUnknownDeoptimizedInteger = false; this.hasUnknownDeoptimizedProperty = false; this.propertiesAndGettersByKey = Object.create(null); this.propertiesAndSettersByKey = Object.create(null); this.settersByKey = Object.create(null); this.unknownIntegerProps = []; this.unmatchableGetters = []; this.unmatchablePropertiesAndGetters = []; this.unmatchableSetters = []; if (Array.isArray(properties)) { this.buildPropertyMaps(properties); } else { this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties; for (const propertiesForKey of Object.values(properties)) { this.allProperties.push(...propertiesForKey); } } } deoptimizeAllProperties(noAccessors) { const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty; if (noAccessors) { this.hasUnknownDeoptimizedProperty = true; } else { this.hasLostTrack = true; } if (isDeoptimized) { return; } for (const properties of [ ...Object.values(this.propertiesAndGettersByKey), ...Object.values(this.settersByKey) ]) { for (const property of properties) { property.deoptimizePath(UNKNOWN_PATH); } } // While the prototype itself cannot be mutated, each property can this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]); this.deoptimizeCachedEntities(); } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { const [key, ...subPath] = path; const { args, type } = interaction; if (this.hasLostTrack || // single paths that are deoptimized will not become getters or setters ((type === INTERACTION_CALLED || path.length > 1) && (this.hasUnknownDeoptimizedProperty || (typeof key === 'string' && this.deoptimizedPaths[key])))) { deoptimizeInteraction(interaction); return; } const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1 ? [ this.propertiesAndGettersByKey, this.propertiesAndGettersByKey, this.unmatchablePropertiesAndGetters ] : type === INTERACTION_ACCESSED ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters] : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters]; if (typeof key === 'string') { if (propertiesForExactMatchByKey[key]) { const properties = relevantPropertiesByKey[key]; if (properties) { for (const property of properties) { property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker); } } if (!this.immutable) { for (const argument of args) { if (argument) { this.additionalExpressionsToBeDeoptimized.add(argument); } } } return; } for (const property of relevantUnmatchableProperties) { property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker); } if (INTEGER_REG_EXP.test(key)) { for (const property of this.unknownIntegerProps) { property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker); } } } else { for (const properties of [ ...Object.values(relevantPropertiesByKey), relevantUnmatchableProperties ]) { for (const property of properties) { property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker); } } for (const property of this.unknownIntegerProps) { property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker); } } if (!this.immutable) { for (const argument of args) { if (argument) { this.additionalExpressionsToBeDeoptimized.add(argument); } } } this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } deoptimizeIntegerProperties() { if (this.hasLostTrack || this.hasUnknownDeoptimizedProperty || this.hasUnknownDeoptimizedInteger) { return; } this.hasUnknownDeoptimizedInteger = true; for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) { if (INTEGER_REG_EXP.test(key)) { for (const property of propertiesAndGetters) { property.deoptimizePath(UNKNOWN_PATH); } } } this.deoptimizeCachedIntegerEntities(); } // Assumption: If only a specific path is deoptimized, no accessors are created deoptimizePath(path) { if (this.hasLostTrack || this.immutable) { return; } const key = path[0]; if (path.length === 1) { if (typeof key !== 'string') { if (key === UnknownInteger) { return this.deoptimizeIntegerProperties(); } return this.deoptimizeAllProperties(key === UnknownNonAccessorKey); } if (!this.deoptimizedPaths[key]) { this.deoptimizedPaths[key] = true; // we only deoptimizeCache exact matches as in all other cases, // we do not return a literal value or return expression const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key]; if (expressionsToBeDeoptimized) { for (const expression of expressionsToBeDeoptimized) { expression.deoptimizeCache(); } } } } const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1); for (const property of typeof key === 'string' ? [ ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters), ...(this.settersByKey[key] || this.unmatchableSetters) ] : this.allProperties) { property.deoptimizePath(subPath); } this.prototypeExpression?.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path); } getLiteralValueAtPath(path, recursionTracker, origin) { if (path.length === 0) { return UnknownTruthyValue; } const key = path[0]; const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin); if (expressionAtPath) { return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin); } if (this.prototypeExpression) { return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin); } if (path.length === 1) { return undefined; } return UnknownValue; } getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) { if (path.length === 0) { return UNKNOWN_RETURN_EXPRESSION; } const [key, ...subPath] = path; const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin); if (expressionAtPath) { return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin); } if (this.prototypeExpression) { return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin); } return UNKNOWN_RETURN_EXPRESSION; } hasEffectsOnInteractionAtPath(path, interaction, context) { const [key, ...subPath] = path; if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) { const expressionAtPath = this.getMemberExpression(key); if (expressionAtPath) { return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context); } if (this.prototypeExpression) { return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context); } return true; } if (key === UnknownNonAccessorKey) return false; if (this.hasLostTrack) return true; const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters] : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters]; if (typeof key === 'string') { if (propertiesAndAccessorsByKey[key]) { const accessors = accessorsByKey[key]; if (accessors) { for (const accessor of accessors) { if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) return true; } } return false; } for (const accessor of unmatchableAccessors) { if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) { return true; } } } else { for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) { for (const accessor of accessors) { if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) return true; } } } if (this.prototypeExpression) { return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context); } return false; } buildPropertyMaps(properties) { const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this; const unmatchablePropertiesAndSetters = []; for (let index = properties.length - 1; index >= 0; index--) { const { key, kind, property } = properties[index]; allProperties.push(property); if (typeof key === 'string') { if (kind === 'set') { if (!propertiesAndSettersByKey[key]) { propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters]; settersByKey[key] = [property, ...unmatchableSetters]; } } else if (kind === 'get') { if (!propertiesAndGettersByKey[key]) { propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters]; gettersByKey[key] = [property, ...unmatchableGetters]; } } else { if (!propertiesAndSettersByKey[key]) { propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters]; } if (!propertiesAndGettersByKey[key]) { propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters]; } } } else { if (key === UnknownInteger) { unknownIntegerProps.push(property); continue; } if (kind === 'set') unmatchableSetters.push(property); if (kind === 'get') unmatchableGetters.push(property); if (kind !== 'get') unmatchablePropertiesAndSetters.push(property); if (kind !== 'set') unmatchablePropertiesAndGetters.push(property); } } } deoptimizeCachedEntities() { for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) { for (const expression of expressionsToBeDeoptimized) { expression.deoptimizeCache(); } } for (const expression of this.additionalExpressionsToBeDeoptimized) { expression.deoptimizePath(UNKNOWN_PATH); } } deoptimizeCachedIntegerEntities() { for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) { if (INTEGER_REG_EXP.test(key)) { for (const expression of expressionsToBeDeoptimized) { expression.deoptimizeCache(); } } } for (const expression of this.additionalExpressionsToBeDeoptimized) { expression.deoptimizePath(UNKNOWN_INTEGER_PATH); } } getMemberExpression(key) { if (this.hasLostTrack || this.hasUnknownDeoptimizedProperty || typeof key !== 'string' || (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) || this.deoptimizedPaths[key]) { return UNKNOWN_EXPRESSION; } const properties = this.propertiesAndGettersByKey[key]; if (properties?.length === 1) { return properties[0]; } if (properties || this.unmatchablePropertiesAndGetters.length > 0 || (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) { return UNKNOWN_EXPRESSION; } return null; } getMemberExpressionAndTrackDeopt(key, origin) { if (typeof key !== 'string') { return UNKNOWN_EXPRESSION; } const expression = this.getMemberExpression(key); if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) { const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] = this.expressionsToBeDeoptimizedByKey[key] || []); expressionsToBeDeoptimized.push(origin); } return expression; } } const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property); // This makes sure unknown properties are not handled as "undefined" but as // "unknown" but without access side effects. An exception is done for numeric // properties as we do not expect new builtin properties to be numbers, this // will improve tree-shaking for out-of-bounds array properties const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity { deoptimizeArgumentsOnInteractionAtPath(interaction, path) { if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) { deoptimizeInteraction(interaction); } } getLiteralValueAtPath(path) { // We ignore number properties as we do not expect new properties to be // numbers and also want to keep handling out-of-bound array elements as // "undefined" return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue; } hasEffectsOnInteractionAtPath(path, { type }) { return path.length > 1 || type === INTERACTION_CALLED; } })(); const OBJECT_PROTOTYPE = new ObjectEntity({ __proto__: null, hasOwnProperty: METHOD_RETURNS_BOOLEAN, isPrototypeOf: METHOD_RETURNS_BOOLEAN, propertyIsEnumerable: METHOD_RETURNS_BOOLEAN, toLocaleString: METHOD_RETURNS_STRING, toString: METHOD_RETURNS_STRING, valueOf: METHOD_RETURNS_UNKNOWN }, OBJECT_PROTOTYPE_FALLBACK, true); const NEW_ARRAY_PROPERTIES = [ { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION }, { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER } ]; const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [ new Method({ callsArgs: [0], mutatesSelfAsArray: 'deopt-only', returns: null, returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN }) ]; const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [ new Method({ callsArgs: [0], mutatesSelfAsArray: 'deopt-only', returns: null, returnsPrimitive: UNKNOWN_LITERAL_NUMBER }) ]; const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [ new Method({ callsArgs: null, mutatesSelfAsArray: true, returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE), returnsPrimitive: null }) ]; const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [ new Method({ callsArgs: null, mutatesSelfAsArray: 'deopt-only', returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE), returnsPrimitive: null }) ]; const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [ new Method({ callsArgs: [0], mutatesSelfAsArray: 'deopt-only', returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE), returnsPrimitive: null }) ]; const METHOD_MUTATES_SELF_RETURNS_NUMBER = [ new Method({ callsArgs: null, mutatesSelfAsArray: true, returns: null, returnsPrimitive: UNKNOWN_LITERAL_NUMBER }) ]; const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [ new Method({ callsArgs: null, mutatesSelfAsArray: true, returns: null, returnsPrimitive: UNKNOWN_EXPRESSION }) ]; const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [ new Method({ callsArgs: null, mutatesSelfAsArray: 'deopt-only', returns: null, returnsPrimitive: UNKNOWN_EXPRESSION }) ]; const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [ new Method({ callsArgs: [0], mutatesSelfAsArray: 'deopt-only', returns: null, returnsPrimitive: UNKNOWN_EXPRESSION }) ]; const METHOD_MUTATES_SELF_RETURNS_SELF = [ new Method({ callsArgs: null, mutatesSelfAsArray: true, returns: 'self', returnsPrimitive: null }) ]; const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [ new Method({ callsArgs: [0], mutatesSelfAsArray: true, returns: 'self', returnsPrimitive: null }) ]; const ARRAY_PROTOTYPE = new ObjectEntity({ __proto__: null, // We assume that accessors have effects as we do not track the accessed value afterwards at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN, concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY, copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF, entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY, every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN, fill: METHOD_MUTATES_SELF_RETURNS_SELF, filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY, find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN, findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER, findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN, findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER, flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY, flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY, forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN, includes: METHOD_RETURNS_BOOLEAN, indexOf: METHOD_RETURNS_NUMBER, join: METHOD_RETURNS_STRING, keys: METHOD_RETURNS_UNKNOWN, lastIndexOf: METHOD_RETURNS_NUMBER, map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY, pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN, push: METHOD_MUTATES_SELF_RETURNS_NUMBER, reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN, reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN, reverse: METHOD_MUTATES_SELF_RETURNS_SELF, shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN, slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY, some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN, sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF, splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY, toLocaleString: METHOD_RETURNS_STRING, toString: METHOD_RETURNS_STRING, unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER, values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN }, OBJECT_PROTOTYPE, true); class ArrayExpression extends NodeBase$2 { constructor() { super(...arguments); this.objectEntity = null; } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } deoptimizePath(path) { this.getObjectEntity().deoptimizePath(path); } getLiteralValueAtPath(path, recursionTracker, origin) { return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin); } getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) { return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin); } hasEffectsOnInteractionAtPath(path, interaction, context) { return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context); } applyDeoptimizations() { this.deoptimized = true; let hasSpread = false; for (let index = 0; index < this.elements.length; index++) { const element = this.elements[index]; if (element && (hasSpread || element instanceof SpreadElement)) { hasSpread = true; element.deoptimizePath(UNKNOWN_PATH); } } this.context.requestTreeshakingPass(); } getObjectEntity() { if (this.objectEntity !== null) { return this.objectEntity; } const properties = [ { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER } ]; let hasSpread = false; for (let index = 0; index < this.elements.length; index++) { const element = this.elements[index]; if (hasSpread || element instanceof SpreadElement) { if (element) { hasSpread = true; properties.unshift({ key: UnknownInteger, kind: 'init', property: element }); } } else if (element) { properties.push({ key: String(index), kind: 'init', property: element }); } else { properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION }); } } return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE)); } } class ArrayPattern extends NodeBase$2 { addExportedVariables(variables, exportNamesByVariable) { for (const element of this.elements) { element?.addExportedVariables(variables, exportNamesByVariable); } } declare(kind) { const variables = []; for (const element of this.elements) { if (element !== null) { variables.push(...element.declare(kind, UNKNOWN_EXPRESSION)); } } return variables; } // Patterns can only be deoptimized at the empty path at the moment deoptimizePath() { for (const element of this.elements) { element?.deoptimizePath(EMPTY_PATH); } } // Patterns are only checked at the emtpy path at the moment hasEffectsOnInteractionAtPath(_path, interaction, context) { for (const element of this.elements) { if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context)) return true; } return false; } markDeclarationReached() { for (const element of this.elements) { element?.markDeclarationReached(); } } } class LocalVariable extends Variable { constructor(name, declarator, init, context) { super(name); this.init = init; this.calledFromTryStatement = false; this.additionalInitializers = null; this.expressionsToBeDeoptimized = []; this.declarations = declarator ? [declarator] : []; this.deoptimizationTracker = context.deoptimizationTracker; this.module = context.module; } addDeclaration(identifier, init) { this.declarations.push(identifier); this.markInitializersForDeoptimization().push(init); } consolidateInitializers() { if (this.additionalInitializers) { for (const initializer of this.additionalInitializers) { initializer.deoptimizePath(UNKNOWN_PATH); } this.additionalInitializers = null; } } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { if (this.isReassigned) { deoptimizeInteraction(interaction); return; } recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker), undefined); } deoptimizePath(path) { if (this.isReassigned || this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) { return; } if (path.length === 0) { if (!this.isReassigned) { this.isReassigned = true; const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized; this.expressionsToBeDeoptimized = EMPTY_ARRAY; for (const expression of expressionsToBeDeoptimized) { expression.deoptimizeCache(); } this.init.deoptimizePath(UNKNOWN_PATH); } } else { this.init.deoptimizePath(path); } } getLiteralValueAtPath(path, recursionTracker, origin) { if (this.isReassigned) { return UnknownValue; } return recursionTracker.withTrackedEntityAtPath(path, this.init, () => { this.expressionsToBeDeoptimized.push(origin); return this.init.getLiteralValueAtPath(path, recursionTracker, origin); }, UnknownValue); } getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) { if (this.isReassigned) { return UNKNOWN_RETURN_EXPRESSION; } return recursionTracker.withTrackedEntityAtPath(path, this.init, () => { this.expressionsToBeDeoptimized.push(origin); return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin); }, UNKNOWN_RETURN_EXPRESSION); } hasEffectsOnInteractionAtPath(path, interaction, context) { switch (interaction.type) { case INTERACTION_ACCESSED: { if (this.isReassigned) return true; return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) && this.init.hasEffectsOnInteractionAtPath(path, interaction, context)); } case INTERACTION_ASSIGNED: { if (this.included) return true; if (path.length === 0) return false; if (this.isReassigned) return true; return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) && this.init.hasEffectsOnInteractionAtPath(path, interaction, context)); } case INTERACTION_CALLED: { if (this.isReassigned) return true; return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) && this.init.hasEffectsOnInteractionAtPath(path, interaction, context)); } } } include() { if (!this.included) { this.included = true; for (const declaration of this.declarations) { // If node is a default export, it can save a tree-shaking run to include the full declaration now if (!declaration.included) declaration.include(createInclusionContext(), false); let node = declaration.parent; while (!node.included) { // We do not want to properly include parents in case they are part of a dead branch // in which case .include() might pull in more dead code node.included = true; if (node.type === Program$1) break; node = node.parent; } } } } includeCallArguments(context, parameters) { if (this.isReassigned || context.includedCallArguments.has(this.init)) { for (const argument of parameters) { argument.include(context, false); } } else { context.includedCallArguments.add(this.init); this.init.includeCallArguments(context, parameters); context.includedCallArguments.delete(this.init); } } markCalledFromTryStatement() { this.calledFromTryStatement = true; } markInitializersForDeoptimization() { if (this.additionalInitializers === null) { this.additionalInitializers = [this.init]; this.init = UNKNOWN_EXPRESSION; this.isReassigned = true; } return this.additionalInitializers; } mergeDeclarations(variable) { const { declarations } = this; for (const declaration of variable.declarations) { declarations.push(declaration); } const additionalInitializers = this.markInitializersForDeoptimization(); additionalInitializers.push(variable.init); if (variable.additionalInitializers) { for (const initializer of variable.additionalInitializers) { additionalInitializers.push(initializer); } } } } const MAX_TRACKED_INTERACTIONS = 20; const NO_INTERACTIONS = EMPTY_ARRAY; const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]); const EMPTY_PATH_TRACKER = new PathTracker(); const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]); class ParameterVariable extends LocalVariable { constructor(name, declarator, context) { super(name, declarator, UNKNOWN_EXPRESSION, context); this.deoptimizationInteractions = []; this.deoptimizations = new PathTracker(); this.deoptimizedFields = new Set(); this.entitiesToBeDeoptimized = new Set(); } addEntityToBeDeoptimized(entity) { if (entity === UNKNOWN_EXPRESSION) { // As unknown expressions fully deoptimize all interactions, we can clear // the interaction cache at this point provided we keep this optimization // in mind when adding new interactions if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) { this.entitiesToBeDeoptimized.add(UNKNOWN_EXPRESSION); for (const { interaction } of this.deoptimizationInteractions) { deoptimizeInteraction(interaction); } this.deoptimizationInteractions = NO_INTERACTIONS; } } else if (this.deoptimizedFields.has(UnknownKey)) { // This means that we already deoptimized all interactions and no longer // track them entity.deoptimizePath(UNKNOWN_PATH); } else if (!this.entitiesToBeDeoptimized.has(entity)) { this.entitiesToBeDeoptimized.add(entity); for (const field of this.deoptimizedFields) { entity.deoptimizePath([field]); } for (const { interaction, path } of this.deoptimizationInteractions) { entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER); } } } deoptimizeArgumentsOnInteractionAtPath(interaction, path) { // For performance reasons, we fully deoptimize all deeper interactions if (path.length >= 2 || this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION) || this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS || (path.length === 1 && (this.deoptimizedFields.has(UnknownKey) || (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0]))))) { deoptimizeInteraction(interaction); return; } if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) { for (const entity of this.entitiesToBeDeoptimized) { entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER); } if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) { this.deoptimizationInteractions.push({ interaction, path }); } } } deoptimizePath(path) { if (path.length === 0 || this.deoptimizedFields.has(UnknownKey)) { return; } const key = path[0]; if (this.deoptimizedFields.has(key)) { return; } this.deoptimizedFields.add(key); for (const entity of this.entitiesToBeDeoptimized) { // We do not need a recursion tracker here as we already track whether // this field is deoptimized entity.deoptimizePath([key]); } if (key === UnknownKey) { // save some memory this.deoptimizationInteractions = NO_INTERACTIONS; this.deoptimizations = EMPTY_PATH_TRACKER; this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD; this.entitiesToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY; } } getReturnExpressionWhenCalledAtPath(path) { // We deoptimize everything that is called as that will trivially deoptimize // the corresponding return expressions as well and avoid badly performing // and complicated alternatives if (path.length === 0) { this.deoptimizePath(UNKNOWN_PATH); } else if (!this.deoptimizedFields.has(path[0])) { this.deoptimizePath([path[0]]); } return UNKNOWN_RETURN_EXPRESSION; } } const chars$5 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$'; const base$2 = 64; function toBase64(value) { let outString = ''; do { const currentDigit = value % base$2; value = (value / base$2) | 0; outString = chars$5[currentDigit] + outString; } while (value !== 0); return outString; } function getSafeName(baseName, usedNames, forbiddenNames) { let safeName = baseName; let count = 1; while (usedNames.has(safeName) || RESERVED_NAMES$1.has(safeName) || forbiddenNames?.has(safeName)) { safeName = `${baseName}$${toBase64(count++)}`; } usedNames.add(safeName); return safeName; } let Scope$1$2 = class Scope { constructor() { this.children = []; this.variables = new Map(); } addDeclaration(identifier, context, init, _isHoisted) { const name = identifier.name; let variable = this.variables.get(name); if (variable) { variable.addDeclaration(identifier, init); } else { variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context); this.variables.set(name, variable); } return variable; } contains(name) { return this.variables.has(name); } findVariable(_name) { throw new Error('Internal Error: findVariable needs to be implemented by a subclass'); } }; class ChildScope extends Scope$1$2 { constructor(parent) { super(); this.accessedOutsideVariables = new Map(); this.parent = parent; parent.children.push(this); } addAccessedDynamicImport(importExpression) { (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression); if (this.parent instanceof ChildScope) { this.parent.addAccessedDynamicImport(importExpression); } } addAccessedGlobals(globals, accessedGlobalsByScope) { const accessedGlobals = accessedGlobalsByScope.get(this) || new Set(); for (const name of globals) { accessedGlobals.add(name); } accessedGlobalsByScope.set(this, accessedGlobals); if (this.parent instanceof ChildScope) { this.parent.addAccessedGlobals(globals, accessedGlobalsByScope); } } addNamespaceMemberAccess(name, variable) { this.accessedOutsideVariables.set(name, variable); this.parent.addNamespaceMemberAccess(name, variable); } addReturnExpression(expression) { this.parent instanceof ChildScope && this.parent.addReturnExpression(expression); } addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) { for (const variable of this.accessedOutsideVariables.values()) { if (variable.included) { usedNames.add(variable.getBaseVariableName()); if (format === 'system' && exportNamesByVariable.has(variable)) { usedNames.add('exports'); } } } const accessedGlobals = accessedGlobalsByScope.get(this); if (accessedGlobals) { for (const name of accessedGlobals) { usedNames.add(name); } } } contains(name) { return this.variables.has(name) || this.parent.contains(name); } deconflict(format, exportNamesByVariable, accessedGlobalsByScope) { const usedNames = new Set(); this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope); if (this.accessedDynamicImports) { for (const importExpression of this.accessedDynamicImports) { if (importExpression.inlineNamespace) { usedNames.add(importExpression.inlineNamespace.getBaseVariableName()); } } } for (const [name, variable] of this.variables) { if (variable.included || variable.alwaysRendered) { variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames)); } } for (const scope of this.children) { scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope); } } findLexicalBoundary() { return this.parent.findLexicalBoundary(); } findVariable(name) { const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name); if (knownVariable) { return knownVariable; } const variable = this.parent.findVariable(name); this.accessedOutsideVariables.set(name, variable); return variable; } } class ParameterScope extends ChildScope { constructor(parent, context) { super(parent); this.parameters = []; this.hasRest = false; this.context = context; this.hoistedBodyVarScope = new ChildScope(this); } /** * Adds a parameter to this scope. Parameters must be added in the correct * order, i.e. from left to right. */ addParameterDeclaration(identifier) { const { name } = identifier; const variable = new ParameterVariable(name, identifier, this.context); const localVariable = this.hoistedBodyVarScope.variables.get(name); if (localVariable) { this.hoistedBodyVarScope.variables.set(name, variable); variable.mergeDeclarations(localVariable); } this.variables.set(name, variable); return variable; } addParameterVariables(parameters, hasRest) { this.parameters = parameters; for (const parameterList of parameters) { for (const parameter of parameterList) { parameter.alwaysRendered = true; } } this.hasRest = hasRest; } includeCallArguments(context, parameters) { let calledFromTryStatement = false; let argumentIncluded = false; const restParameter = this.hasRest && this.parameters[this.parameters.length - 1]; for (const checkedArgument of parameters) { if (checkedArgument instanceof SpreadElement) { for (const argument of parameters) { argument.include(context, false); } break; } } for (let index = parameters.length - 1; index >= 0; index--) { const parameterVariables = this.parameters[index] || restParameter; const argument = parameters[index]; if (parameterVariables) { calledFromTryStatement = false; if (parameterVariables.length === 0) { // handle empty destructuring argumentIncluded = true; } else { for (const variable of parameterVariables) { if (variable.included) { argumentIncluded = true; } if (variable.calledFromTryStatement) { calledFromTryStatement = true; } } } } if (!argumentIncluded && argument.shouldBeIncluded(context)) { argumentIncluded = true; } if (argumentIncluded) { argument.include(context, calledFromTryStatement); } } } } class ReturnValueScope extends ParameterScope { constructor() { super(...arguments); this.returnExpression = null; this.returnExpressions = []; } addReturnExpression(expression) { this.returnExpressions.push(expression); } getReturnExpression() { if (this.returnExpression === null) this.updateReturnExpression(); return this.returnExpression; } updateReturnExpression() { if (this.returnExpressions.length === 1) { this.returnExpression = this.returnExpressions[0]; } else { this.returnExpression = UNKNOWN_EXPRESSION; for (const expression of this.returnExpressions) { expression.deoptimizePath(UNKNOWN_PATH); } } } } /** @typedef { import('estree').Node} Node */ /** @typedef {Node | { * type: 'PropertyDefinition'; * computed: boolean; * value: Node * }} NodeWithPropertyDefinition */ /** * * @param {NodeWithPropertyDefinition} node * @param {NodeWithPropertyDefinition} parent * @returns {boolean} */ function is_reference (node, parent) { if (node.type === 'MemberExpression') { return !node.computed && is_reference(node.object, node); } if (node.type === 'Identifier') { if (!parent) return true; switch (parent.type) { // disregard `bar` in `foo.bar` case 'MemberExpression': return parent.computed || node === parent.object; // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}` case 'MethodDefinition': return parent.computed; // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}` case 'PropertyDefinition': return parent.computed || node === parent.value; // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }` case 'Property': return parent.computed || node === parent.value; // disregard the `bar` in `export { foo as bar }` or // the foo in `import { foo as bar }` case 'ExportSpecifier': case 'ImportSpecifier': return node === parent.local; // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}` case 'LabeledStatement': case 'BreakStatement': case 'ContinueStatement': return false; default: return true; } } return false; } const PureFunctionKey = Symbol('PureFunction'); const getPureFunctions = ({ treeshake }) => { const pureFunctions = Object.create(null); for (const functionName of treeshake ? treeshake.manualPureFunctions : []) { let currentFunctions = pureFunctions; for (const pathSegment of functionName.split('.')) { currentFunctions = currentFunctions[pathSegment] || (currentFunctions[pathSegment] = Object.create(null)); } currentFunctions[PureFunctionKey] = true; } return pureFunctions; }; const doNothing = () => { }; /* eslint sort-keys: "off" */ const ValueProperties = Symbol('Value Properties'); const getTruthyLiteralValue = () => UnknownTruthyValue; const returnFalse = () => false; const returnTrue = () => true; const PURE = { deoptimizeArgumentsOnCall: doNothing, getLiteralValue: getTruthyLiteralValue, hasEffectsWhenCalled: returnFalse }; const IMPURE = { deoptimizeArgumentsOnCall: doNothing, getLiteralValue: getTruthyLiteralValue, hasEffectsWhenCalled: returnTrue }; const PURE_WITH_ARRAY = { deoptimizeArgumentsOnCall: doNothing, getLiteralValue: getTruthyLiteralValue, hasEffectsWhenCalled({ args }) { return args.length > 1 && !(args[1] instanceof ArrayExpression); } }; const GETTER_ACCESS = { deoptimizeArgumentsOnCall: doNothing, getLiteralValue: getTruthyLiteralValue, hasEffectsWhenCalled({ args }, context) { const [_thisArgument, firstArgument] = args; return (!(firstArgument instanceof ExpressionEntity) || firstArgument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context)); } }; // We use shortened variables to reduce file size here /* OBJECT */ const O = { __proto__: null, [ValueProperties]: IMPURE }; /* PURE FUNCTION */ const PF = { __proto__: null, [ValueProperties]: PURE }; /* PURE FUNCTION IF FIRST ARG DOES NOT CONTAIN A GETTER */ const PF_NO_GETTER = { __proto__: null, [ValueProperties]: GETTER_ACCESS }; /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */ const MUTATES_ARG_WITHOUT_ACCESSOR = { __proto__: null, [ValueProperties]: { deoptimizeArgumentsOnCall({ args: [, firstArgument] }) { firstArgument?.deoptimizePath(UNKNOWN_PATH); }, getLiteralValue: getTruthyLiteralValue, hasEffectsWhenCalled({ args }, context) { return (args.length <= 1 || args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)); } } }; /* CONSTRUCTOR */ const C$1 = { __proto__: null, [ValueProperties]: IMPURE, prototype: O }; /* PURE CONSTRUCTOR */ const PC = { __proto__: null, [ValueProperties]: PURE, prototype: O }; const PC_WITH_ARRAY = { __proto__: null, [ValueProperties]: PURE_WITH_ARRAY, prototype: O }; const ARRAY_TYPE = { __proto__: null, [ValueProperties]: PURE, from: O, of: PF, prototype: O }; const INTL_MEMBER = { __proto__: null, [ValueProperties]: PURE, supportedLocalesOf: PC }; const knownGlobals = { // Placeholders for global objects to avoid shape mutations global: O, globalThis: O, self: O, window: O, // Common globals __proto__: null, [ValueProperties]: IMPURE, Array: { __proto__: null, [ValueProperties]: IMPURE, from: O, isArray: PF, of: PF, prototype: O }, ArrayBuffer: { __proto__: null, [ValueProperties]: PURE, isView: PF, prototype: O }, Atomics: O, BigInt: C$1, BigInt64Array: C$1, BigUint64Array: C$1, Boolean: PC, constructor: C$1, DataView: PC, Date: { __proto__: null, [ValueProperties]: PURE, now: PF, parse: PF, prototype: O, UTC: PF }, decodeURI: PF, decodeURIComponent: PF, encodeURI: PF, encodeURIComponent: PF, Error: PC, escape: PF, eval: O, EvalError: PC, Float32Array: ARRAY_TYPE, Float64Array: ARRAY_TYPE, Function: C$1, hasOwnProperty: O, Infinity: O, Int16Array: ARRAY_TYPE, Int32Array: ARRAY_TYPE, Int8Array: ARRAY_TYPE, isFinite: PF, isNaN: PF, isPrototypeOf: O, JSON: O, Map: PC_WITH_ARRAY, Math: { __proto__: null, [ValueProperties]: IMPURE, abs: PF, acos: PF, acosh: PF, asin: PF, asinh: PF, atan: PF, atan2: PF, atanh: PF, cbrt: PF, ceil: PF, clz32: PF, cos: PF, cosh: PF, exp: PF, expm1: PF, floor: PF, fround: PF, hypot: PF, imul: PF, log: PF, log10: PF, log1p: PF, log2: PF, max: PF, min: PF, pow: PF, random: PF, round: PF, sign: PF, sin: PF, sinh: PF, sqrt: PF, tan: PF, tanh: PF, trunc: PF }, NaN: O, Number: { __proto__: null, [ValueProperties]: PURE, isFinite: PF, isInteger: PF, isNaN: PF, isSafeInteger: PF, parseFloat: PF, parseInt: PF, prototype: O }, Object: { __proto__: null, [ValueProperties]: PURE, create: PF, // Technically those can throw in certain situations, but we ignore this as // code that relies on this will hopefully wrap this in a try-catch, which // deoptimizes everything anyway defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR, defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR, freeze: MUTATES_ARG_WITHOUT_ACCESSOR, getOwnPropertyDescriptor: PF, getOwnPropertyDescriptors: PF, getOwnPropertyNames: PF, getOwnPropertySymbols: PF, getPrototypeOf: PF, hasOwn: PF, is: PF, isExtensible: PF, isFrozen: PF, isSealed: PF, keys: PF, fromEntries: O, entries: PF_NO_GETTER, values: PF_NO_GETTER, prototype: O }, parseFloat: PF, parseInt: PF, Promise: { __proto__: null, [ValueProperties]: IMPURE, all: O, allSettled: O, any: O, prototype: O, race: O, reject: O, resolve: O }, propertyIsEnumerable: O, Proxy: O, RangeError: PC, ReferenceError: PC, Reflect: O, RegExp: PC, Set: PC_WITH_ARRAY, SharedArrayBuffer: C$1, String: { __proto__: null, [ValueProperties]: PURE, fromCharCode: PF, fromCodePoint: PF, prototype: O, raw: PF }, Symbol: { __proto__: null, [ValueProperties]: PURE, for: PF, keyFor: PF, prototype: O, toStringTag: { __proto__: null, [ValueProperties]: { deoptimizeArgumentsOnCall: doNothing, getLiteralValue() { return SymbolToStringTag; }, hasEffectsWhenCalled: returnTrue } } }, SyntaxError: PC, toLocaleString: O, toString: O, TypeError: PC, Uint16Array: ARRAY_TYPE, Uint32Array: ARRAY_TYPE, Uint8Array: ARRAY_TYPE, Uint8ClampedArray: ARRAY_TYPE, // Technically, this is a global, but it needs special handling // undefined: ?, unescape: PF, URIError: PC, valueOf: O, WeakMap: PC_WITH_ARRAY, WeakSet: PC_WITH_ARRAY, // Additional globals shared by Node and Browser that are not strictly part of the language clearInterval: C$1, clearTimeout: C$1, console: { __proto__: null, [ValueProperties]: IMPURE, assert: C$1, clear: C$1, count: C$1, countReset: C$1, debug: C$1, dir: C$1, dirxml: C$1, error: C$1, exception: C$1, group: C$1, groupCollapsed: C$1, groupEnd: C$1, info: C$1, log: C$1, table: C$1, time: C$1, timeEnd: C$1, timeLog: C$1, trace: C$1, warn: C$1 }, Intl: { __proto__: null, [ValueProperties]: IMPURE, Collator: INTL_MEMBER, DateTimeFormat: INTL_MEMBER, DisplayNames: INTL_MEMBER, ListFormat: INTL_MEMBER, Locale: INTL_MEMBER, NumberFormat: INTL_MEMBER, PluralRules: INTL_MEMBER, RelativeTimeFormat: INTL_MEMBER, Segmenter: INTL_MEMBER }, setInterval: C$1, setTimeout: C$1, TextDecoder: C$1, TextEncoder: C$1, URL: { __proto__: null, [ValueProperties]: IMPURE, prototype: O, canParse: PF }, URLSearchParams: C$1, // Browser specific globals AbortController: C$1, AbortSignal: C$1, addEventListener: O, alert: O, AnalyserNode: C$1, Animation: C$1, AnimationEvent: C$1, applicationCache: O, ApplicationCache: C$1, ApplicationCacheErrorEvent: C$1, atob: O, Attr: C$1, Audio: C$1, AudioBuffer: C$1, AudioBufferSourceNode: C$1, AudioContext: C$1, AudioDestinationNode: C$1, AudioListener: C$1, AudioNode: C$1, AudioParam: C$1, AudioProcessingEvent: C$1, AudioScheduledSourceNode: C$1, AudioWorkletNode: C$1, BarProp: C$1, BaseAudioContext: C$1, BatteryManager: C$1, BeforeUnloadEvent: C$1, BiquadFilterNode: C$1, Blob: C$1, BlobEvent: C$1, blur: O, BroadcastChannel: C$1, btoa: O, ByteLengthQueuingStrategy: C$1, Cache: C$1, caches: O, CacheStorage: C$1, cancelAnimationFrame: O, cancelIdleCallback: O, CanvasCaptureMediaStreamTrack: C$1, CanvasGradient: C$1, CanvasPattern: C$1, CanvasRenderingContext2D: C$1, ChannelMergerNode: C$1, ChannelSplitterNode: C$1, CharacterData: C$1, clientInformation: O, ClipboardEvent: C$1, close: O, closed: O, CloseEvent: C$1, Comment: C$1, CompositionEvent: C$1, confirm: O, ConstantSourceNode: C$1, ConvolverNode: C$1, CountQueuingStrategy: C$1, createImageBitmap: O, Credential: C$1, CredentialsContainer: C$1, crypto: O, Crypto: C$1, CryptoKey: C$1, CSS: C$1, CSSConditionRule: C$1, CSSFontFaceRule: C$1, CSSGroupingRule: C$1, CSSImportRule: C$1, CSSKeyframeRule: C$1, CSSKeyframesRule: C$1, CSSMediaRule: C$1, CSSNamespaceRule: C$1, CSSPageRule: C$1, CSSRule: C$1, CSSRuleList: C$1, CSSStyleDeclaration: C$1, CSSStyleRule: C$1, CSSStyleSheet: C$1, CSSSupportsRule: C$1, CustomElementRegistry: C$1, customElements: O, CustomEvent: { __proto__: null, [ValueProperties]: { deoptimizeArgumentsOnCall({ args }) { args[2]?.deoptimizePath(['detail']); }, getLiteralValue: getTruthyLiteralValue, hasEffectsWhenCalled: returnFalse }, prototype: O }, DataTransfer: C$1, DataTransferItem: C$1, DataTransferItemList: C$1, defaultstatus: O, defaultStatus: O, DelayNode: C$1, DeviceMotionEvent: C$1, DeviceOrientationEvent: C$1, devicePixelRatio: O, dispatchEvent: O, document: O, Document: C$1, DocumentFragment: C$1, DocumentType: C$1, DOMError: C$1, DOMException: C$1, DOMImplementation: C$1, DOMMatrix: C$1, DOMMatrixReadOnly: C$1, DOMParser: C$1, DOMPoint: C$1, DOMPointReadOnly: C$1, DOMQuad: C$1, DOMRect: C$1, DOMRectReadOnly: C$1, DOMStringList: C$1, DOMStringMap: C$1, DOMTokenList: C$1, DragEvent: C$1, DynamicsCompressorNode: C$1, Element: C$1, ErrorEvent: C$1, Event: C$1, EventSource: C$1, EventTarget: C$1, external: O, fetch: O, File: C$1, FileList: C$1, FileReader: C$1, find: O, focus: O, FocusEvent: C$1, FontFace: C$1, FontFaceSetLoadEvent: C$1, FormData: C$1, frames: O, GainNode: C$1, Gamepad: C$1, GamepadButton: C$1, GamepadEvent: C$1, getComputedStyle: O, getSelection: O, HashChangeEvent: C$1, Headers: C$1, history: O, History: C$1, HTMLAllCollection: C$1, HTMLAnchorElement: C$1, HTMLAreaElement: C$1, HTMLAudioElement: C$1, HTMLBaseElement: C$1, HTMLBodyElement: C$1, HTMLBRElement: C$1, HTMLButtonElement: C$1, HTMLCanvasElement: C$1, HTMLCollection: C$1, HTMLContentElement: C$1, HTMLDataElement: C$1, HTMLDataListElement: C$1, HTMLDetailsElement: C$1, HTMLDialogElement: C$1, HTMLDirectoryElement: C$1, HTMLDivElement: C$1, HTMLDListElement: C$1, HTMLDocument: C$1, HTMLElement: C$1, HTMLEmbedElement: C$1, HTMLFieldSetElement: C$1, HTMLFontElement: C$1, HTMLFormControlsCollection: C$1, HTMLFormElement: C$1, HTMLFrameElement: C$1, HTMLFrameSetElement: C$1, HTMLHeadElement: C$1, HTMLHeadingElement: C$1, HTMLHRElement: C$1, HTMLHtmlElement: C$1, HTMLIFrameElement: C$1, HTMLImageElement: C$1, HTMLInputElement: C$1, HTMLLabelElement: C$1, HTMLLegendElement: C$1, HTMLLIElement: C$1, HTMLLinkElement: C$1, HTMLMapElement: C$1, HTMLMarqueeElement: C$1, HTMLMediaElement: C$1, HTMLMenuElement: C$1, HTMLMetaElement: C$1, HTMLMeterElement: C$1, HTMLModElement: C$1, HTMLObjectElement: C$1, HTMLOListElement: C$1, HTMLOptGroupElement: C$1, HTMLOptionElement: C$1, HTMLOptionsCollection: C$1, HTMLOutputElement: C$1, HTMLParagraphElement: C$1, HTMLParamElement: C$1, HTMLPictureElement: C$1, HTMLPreElement: C$1, HTMLProgressElement: C$1, HTMLQuoteElement: C$1, HTMLScriptElement: C$1, HTMLSelectElement: C$1, HTMLShadowElement: C$1, HTMLSlotElement: C$1, HTMLSourceElement: C$1, HTMLSpanElement: C$1, HTMLStyleElement: C$1, HTMLTableCaptionElement: C$1, HTMLTableCellElement: C$1, HTMLTableColElement: C$1, HTMLTableElement: C$1, HTMLTableRowElement: C$1, HTMLTableSectionElement: C$1, HTMLTemplateElement: C$1, HTMLTextAreaElement: C$1, HTMLTimeElement: C$1, HTMLTitleElement: C$1, HTMLTrackElement: C$1, HTMLUListElement: C$1, HTMLUnknownElement: C$1, HTMLVideoElement: C$1, IDBCursor: C$1, IDBCursorWithValue: C$1, IDBDatabase: C$1, IDBFactory: C$1, IDBIndex: C$1, IDBKeyRange: C$1, IDBObjectStore: C$1, IDBOpenDBRequest: C$1, IDBRequest: C$1, IDBTransaction: C$1, IDBVersionChangeEvent: C$1, IdleDeadline: C$1, IIRFilterNode: C$1, Image: C$1, ImageBitmap: C$1, ImageBitmapRenderingContext: C$1, ImageCapture: C$1, ImageData: C$1, indexedDB: O, innerHeight: O, innerWidth: O, InputEvent: C$1, IntersectionObserver: C$1, IntersectionObserverEntry: C$1, isSecureContext: O, KeyboardEvent: C$1, KeyframeEffect: C$1, length: O, localStorage: O, location: O, Location: C$1, locationbar: O, matchMedia: O, MediaDeviceInfo: C$1, MediaDevices: C$1, MediaElementAudioSourceNode: C$1, MediaEncryptedEvent: C$1, MediaError: C$1, MediaKeyMessageEvent: C$1, MediaKeySession: C$1, MediaKeyStatusMap: C$1, MediaKeySystemAccess: C$1, MediaList: C$1, MediaQueryList: C$1, MediaQueryListEvent: C$1, MediaRecorder: C$1, MediaSettingsRange: C$1, MediaSource: C$1, MediaStream: C$1, MediaStreamAudioDestinationNode: C$1, MediaStreamAudioSourceNode: C$1, MediaStreamEvent: C$1, MediaStreamTrack: C$1, MediaStreamTrackEvent: C$1, menubar: O, MessageChannel: C$1, MessageEvent: C$1, MessagePort: C$1, MIDIAccess: C$1, MIDIConnectionEvent: C$1, MIDIInput: C$1, MIDIInputMap: C$1, MIDIMessageEvent: C$1, MIDIOutput: C$1, MIDIOutputMap: C$1, MIDIPort: C$1, MimeType: C$1, MimeTypeArray: C$1, MouseEvent: C$1, moveBy: O, moveTo: O, MutationEvent: C$1, MutationObserver: C$1, MutationRecord: C$1, name: O, NamedNodeMap: C$1, NavigationPreloadManager: C$1, navigator: O, Navigator: C$1, NetworkInformation: C$1, Node: C$1, NodeFilter: O, NodeIterator: C$1, NodeList: C$1, Notification: C$1, OfflineAudioCompletionEvent: C$1, OfflineAudioContext: C$1, offscreenBuffering: O, OffscreenCanvas: C$1, open: O, openDatabase: O, Option: C$1, origin: O, OscillatorNode: C$1, outerHeight: O, outerWidth: O, PageTransitionEvent: C$1, pageXOffset: O, pageYOffset: O, PannerNode: C$1, parent: O, Path2D: C$1, PaymentAddress: C$1, PaymentRequest: C$1, PaymentRequestUpdateEvent: C$1, PaymentResponse: C$1, performance: O, Performance: C$1, PerformanceEntry: C$1, PerformanceLongTaskTiming: C$1, PerformanceMark: C$1, PerformanceMeasure: C$1, PerformanceNavigation: C$1, PerformanceNavigationTiming: C$1, PerformanceObserver: C$1, PerformanceObserverEntryList: C$1, PerformancePaintTiming: C$1, PerformanceResourceTiming: C$1, PerformanceTiming: C$1, PeriodicWave: C$1, Permissions: C$1, PermissionStatus: C$1, personalbar: O, PhotoCapabilities: C$1, Plugin: C$1, PluginArray: C$1, PointerEvent: C$1, PopStateEvent: C$1, postMessage: O, Presentation: C$1, PresentationAvailability: C$1, PresentationConnection: C$1, PresentationConnectionAvailableEvent: C$1, PresentationConnectionCloseEvent: C$1, PresentationConnectionList: C$1, PresentationReceiver: C$1, PresentationRequest: C$1, print: O, ProcessingInstruction: C$1, ProgressEvent: C$1, PromiseRejectionEvent: C$1, prompt: O, PushManager: C$1, PushSubscription: C$1, PushSubscriptionOptions: C$1, queueMicrotask: O, RadioNodeList: C$1, Range: C$1, ReadableStream: C$1, RemotePlayback: C$1, removeEventListener: O, Request: C$1, requestAnimationFrame: O, requestIdleCallback: O, resizeBy: O, ResizeObserver: C$1, ResizeObserverEntry: C$1, resizeTo: O, Response: C$1, RTCCertificate: C$1, RTCDataChannel: C$1, RTCDataChannelEvent: C$1, RTCDtlsTransport: C$1, RTCIceCandidate: C$1, RTCIceTransport: C$1, RTCPeerConnection: C$1, RTCPeerConnectionIceEvent: C$1, RTCRtpReceiver: C$1, RTCRtpSender: C$1, RTCSctpTransport: C$1, RTCSessionDescription: C$1, RTCStatsReport: C$1, RTCTrackEvent: C$1, screen: O, Screen: C$1, screenLeft: O, ScreenOrientation: C$1, screenTop: O, screenX: O, screenY: O, ScriptProcessorNode: C$1, scroll: O, scrollbars: O, scrollBy: O, scrollTo: O, scrollX: O, scrollY: O, SecurityPolicyViolationEvent: C$1, Selection: C$1, ServiceWorker: C$1, ServiceWorkerContainer: C$1, ServiceWorkerRegistration: C$1, sessionStorage: O, ShadowRoot: C$1, SharedWorker: C$1, SourceBuffer: C$1, SourceBufferList: C$1, speechSynthesis: O, SpeechSynthesisEvent: C$1, SpeechSynthesisUtterance: C$1, StaticRange: C$1, status: O, statusbar: O, StereoPannerNode: C$1, stop: O, Storage: C$1, StorageEvent: C$1, StorageManager: C$1, styleMedia: O, StyleSheet: C$1, StyleSheetList: C$1, SubtleCrypto: C$1, SVGAElement: C$1, SVGAngle: C$1, SVGAnimatedAngle: C$1, SVGAnimatedBoolean: C$1, SVGAnimatedEnumeration: C$1, SVGAnimatedInteger: C$1, SVGAnimatedLength: C$1, SVGAnimatedLengthList: C$1, SVGAnimatedNumber: C$1, SVGAnimatedNumberList: C$1, SVGAnimatedPreserveAspectRatio: C$1, SVGAnimatedRect: C$1, SVGAnimatedString: C$1, SVGAnimatedTransformList: C$1, SVGAnimateElement: C$1, SVGAnimateMotionElement: C$1, SVGAnimateTransformElement: C$1, SVGAnimationElement: C$1, SVGCircleElement: C$1, SVGClipPathElement: C$1, SVGComponentTransferFunctionElement: C$1, SVGDefsElement: C$1, SVGDescElement: C$1, SVGDiscardElement: C$1, SVGElement: C$1, SVGEllipseElement: C$1, SVGFEBlendElement: C$1, SVGFEColorMatrixElement: C$1, SVGFEComponentTransferElement: C$1, SVGFECompositeElement: C$1, SVGFEConvolveMatrixElement: C$1, SVGFEDiffuseLightingElement: C$1, SVGFEDisplacementMapElement: C$1, SVGFEDistantLightElement: C$1, SVGFEDropShadowElement: C$1, SVGFEFloodElement: C$1, SVGFEFuncAElement: C$1, SVGFEFuncBElement: C$1, SVGFEFuncGElement: C$1, SVGFEFuncRElement: C$1, SVGFEGaussianBlurElement: C$1, SVGFEImageElement: C$1, SVGFEMergeElement: C$1, SVGFEMergeNodeElement: C$1, SVGFEMorphologyElement: C$1, SVGFEOffsetElement: C$1, SVGFEPointLightElement: C$1, SVGFESpecularLightingElement: C$1, SVGFESpotLightElement: C$1, SVGFETileElement: C$1, SVGFETurbulenceElement: C$1, SVGFilterElement: C$1, SVGForeignObjectElement: C$1, SVGGElement: C$1, SVGGeometryElement: C$1, SVGGradientElement: C$1, SVGGraphicsElement: C$1, SVGImageElement: C$1, SVGLength: C$1, SVGLengthList: C$1, SVGLinearGradientElement: C$1, SVGLineElement: C$1, SVGMarkerElement: C$1, SVGMaskElement: C$1, SVGMatrix: C$1, SVGMetadataElement: C$1, SVGMPathElement: C$1, SVGNumber: C$1, SVGNumberList: C$1, SVGPathElement: C$1, SVGPatternElement: C$1, SVGPoint: C$1, SVGPointList: C$1, SVGPolygonElement: C$1, SVGPolylineElement: C$1, SVGPreserveAspectRatio: C$1, SVGRadialGradientElement: C$1, SVGRect: C$1, SVGRectElement: C$1, SVGScriptElement: C$1, SVGSetElement: C$1, SVGStopElement: C$1, SVGStringList: C$1, SVGStyleElement: C$1, SVGSVGElement: C$1, SVGSwitchElement: C$1, SVGSymbolElement: C$1, SVGTextContentElement: C$1, SVGTextElement: C$1, SVGTextPathElement: C$1, SVGTextPositioningElement: C$1, SVGTitleElement: C$1, SVGTransform: C$1, SVGTransformList: C$1, SVGTSpanElement: C$1, SVGUnitTypes: C$1, SVGUseElement: C$1, SVGViewElement: C$1, TaskAttributionTiming: C$1, Text: C$1, TextEvent: C$1, TextMetrics: C$1, TextTrack: C$1, TextTrackCue: C$1, TextTrackCueList: C$1, TextTrackList: C$1, TimeRanges: C$1, toolbar: O, top: O, Touch: C$1, TouchEvent: C$1, TouchList: C$1, TrackEvent: C$1, TransitionEvent: C$1, TreeWalker: C$1, UIEvent: C$1, ValidityState: C$1, visualViewport: O, VisualViewport: C$1, VTTCue: C$1, WaveShaperNode: C$1, WebAssembly: O, WebGL2RenderingContext: C$1, WebGLActiveInfo: C$1, WebGLBuffer: C$1, WebGLContextEvent: C$1, WebGLFramebuffer: C$1, WebGLProgram: C$1, WebGLQuery: C$1, WebGLRenderbuffer: C$1, WebGLRenderingContext: C$1, WebGLSampler: C$1, WebGLShader: C$1, WebGLShaderPrecisionFormat: C$1, WebGLSync: C$1, WebGLTexture: C$1, WebGLTransformFeedback: C$1, WebGLUniformLocation: C$1, WebGLVertexArrayObject: C$1, WebSocket: C$1, WheelEvent: C$1, Window: C$1, Worker: C$1, WritableStream: C$1, XMLDocument: C$1, XMLHttpRequest: C$1, XMLHttpRequestEventTarget: C$1, XMLHttpRequestUpload: C$1, XMLSerializer: C$1, XPathEvaluator: C$1, XPathExpression: C$1, XPathResult: C$1, XSLTProcessor: C$1 }; for (const global of ['window', 'global', 'self', 'globalThis']) { knownGlobals[global] = knownGlobals; } function getGlobalAtPath(path) { let currentGlobal = knownGlobals; for (const pathSegment of path) { if (typeof pathSegment !== 'string') { return null; } currentGlobal = currentGlobal[pathSegment]; if (!currentGlobal) { return null; } } return currentGlobal[ValueProperties]; } class GlobalVariable extends Variable { constructor() { super(...arguments); // Ensure we use live-bindings for globals as we do not know if they have // been reassigned this.isReassigned = true; } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { switch (interaction.type) { // While there is no point in testing these cases as at the moment, they // are also covered via other means, we keep them for completeness case INTERACTION_ACCESSED: case INTERACTION_ASSIGNED: { if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) { super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } return; } case INTERACTION_CALLED: { const globalAtPath = getGlobalAtPath([this.name, ...path]); if (globalAtPath) { globalAtPath.deoptimizeArgumentsOnCall(interaction); } else { super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } return; } } } getLiteralValueAtPath(path, _recursionTracker, _origin) { const globalAtPath = getGlobalAtPath([this.name, ...path]); return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue; } hasEffectsOnInteractionAtPath(path, interaction, context) { switch (interaction.type) { case INTERACTION_ACCESSED: { if (path.length === 0) { // Technically, "undefined" is a global variable of sorts return this.name !== 'undefined' && !getGlobalAtPath([this.name]); } return !getGlobalAtPath([this.name, ...path].slice(0, -1)); } case INTERACTION_ASSIGNED: { return true; } case INTERACTION_CALLED: { const globalAtPath = getGlobalAtPath([this.name, ...path]); return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context); } } } } const tdzVariableKinds = { __proto__: null, class: true, const: true, let: true, var: true }; class Identifier extends NodeBase$2 { constructor() { super(...arguments); this.variable = null; this.isTDZAccess = null; } addExportedVariables(variables, exportNamesByVariable) { if (exportNamesByVariable.has(this.variable)) { variables.push(this.variable); } } bind() { if (!this.variable && is_reference(this, this.parent)) { this.variable = this.scope.findVariable(this.name); this.variable.addReference(this); } } declare(kind, init) { let variable; const { treeshake } = this.context.options; switch (kind) { case 'var': { variable = this.scope.addDeclaration(this, this.context, init, true); if (treeshake && treeshake.correctVarValueBeforeDeclaration) { // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here. variable.markInitializersForDeoptimization(); } break; } case 'function': { // in strict mode, functions are only hoisted within a scope but not across block scopes variable = this.scope.addDeclaration(this, this.context, init, false); break; } case 'let': case 'const': case 'class': { variable = this.scope.addDeclaration(this, this.context, init, false); break; } case 'parameter': { variable = this.scope.addParameterDeclaration(this); break; } /* istanbul ignore next */ default: { /* istanbul ignore next */ throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`); } } variable.kind = kind; return [(this.variable = variable)]; } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } deoptimizePath(path) { if (path.length === 0 && !this.scope.contains(this.name)) { this.disallowImportReassignment(); } // We keep conditional chaining because an unknown Node could have an // Identifier as property that might be deoptimized by default this.variable?.deoptimizePath(path); } getLiteralValueAtPath(path, recursionTracker, origin) { return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin); } getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) { const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin); return [expression, isPure || this.isPureFunction(path)]; } hasEffects(context) { if (!this.deoptimized) this.applyDeoptimizations(); if (this.isPossibleTDZ() && this.variable.kind !== 'var') { return true; } return (this.context.options.treeshake.unknownGlobalSideEffects && this.variable instanceof GlobalVariable && !this.isPureFunction(EMPTY_PATH) && this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context)); } hasEffectsOnInteractionAtPath(path, interaction, context) { switch (interaction.type) { case INTERACTION_ACCESSED: { return (this.variable !== null && !this.isPureFunction(path) && this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context)); } case INTERACTION_ASSIGNED: { return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context); } case INTERACTION_CALLED: { return (!this.isPureFunction(path) && this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context)); } } } include() { if (!this.deoptimized) this.applyDeoptimizations(); if (!this.included) { this.included = true; if (this.variable !== null) { this.context.includeVariableInModule(this.variable); } } } includeCallArguments(context, parameters) { this.variable.includeCallArguments(context, parameters); } isPossibleTDZ() { // return cached value to avoid issues with the next tree-shaking pass if (this.isTDZAccess !== null) return this.isTDZAccess; if (!(this.variable instanceof LocalVariable && this.variable.kind && this.variable.kind in tdzVariableKinds && // we ignore possible TDZs due to circular module dependencies as // otherwise we get many false positives this.variable.module === this.context.module)) { return (this.isTDZAccess = false); } let decl_id; if (this.variable.declarations && this.variable.declarations.length === 1 && (decl_id = this.variable.declarations[0]) && this.start < decl_id.start && closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) { // a variable accessed before its declaration // in the same function or at top level of module return (this.isTDZAccess = true); } if (!this.variable.initReached) { // Either a const/let TDZ violation or // var use before declaration was encountered. return (this.isTDZAccess = true); } return (this.isTDZAccess = false); } markDeclarationReached() { this.variable.initReached = true; } render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) { if (this.variable) { const name = this.variable.getName(getPropertyAccess, useOriginalName); if (name !== this.name) { code.overwrite(this.start, this.end, name, { contentOnly: true, storeName: true }); if (isShorthandProperty) { code.prependRight(this.start, `${this.name}: `); } } // In strict mode, any variable named "eval" must be the actual "eval" function if (name === 'eval' && renderedParentType === CallExpression$1 && isCalleeOfRenderedParent) { code.appendRight(this.start, '0, '); } } } applyDeoptimizations() { this.deoptimized = true; if (this.variable instanceof LocalVariable) { this.variable.consolidateInitializers(); this.context.requestTreeshakingPass(); } } disallowImportReassignment() { return this.context.error(logIllegalImportReassignment(this.name, this.context.module.id), this.start); } getVariableRespectingTDZ() { if (this.isPossibleTDZ()) { return UNKNOWN_EXPRESSION; } return this.variable; } isPureFunction(path) { let currentPureFunction = this.context.manualPureFunctions[this.name]; for (const segment of path) { if (currentPureFunction) { if (currentPureFunction[PureFunctionKey]) { return true; } currentPureFunction = currentPureFunction[segment]; } else { return false; } } return currentPureFunction?.[PureFunctionKey]; } } function closestParentFunctionOrProgram(node) { while (node && !/^Program|Function/.test(node.type)) { node = node.parent; } // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program return node; } function treeshakeNode(node, code, start, end) { code.remove(start, end); if (node.annotations) { for (const annotation of node.annotations) { if (annotation.start < start) { code.remove(annotation.start, annotation.end); } else { return; } } } } function removeAnnotations(node, code) { if (!node.annotations && node.parent.type === ExpressionStatement$1) { node = node.parent; } if (node.annotations) { for (const annotation of node.annotations) { code.remove(annotation.start, annotation.end); } } } const NO_SEMICOLON = { isNoStatement: true }; // This assumes there are only white-space and comments between start and the string we are looking for function findFirstOccurrenceOutsideComment(code, searchString, start = 0) { let searchPos, charCodeAfterSlash; searchPos = code.indexOf(searchString, start); while (true) { start = code.indexOf('/', start); if (start === -1 || start >= searchPos) return searchPos; charCodeAfterSlash = code.charCodeAt(++start); ++start; // With our assumption, '/' always starts a comment. Determine comment type: start = charCodeAfterSlash === 47 /*"/"*/ ? code.indexOf('\n', start) + 1 : code.indexOf('*/', start) + 2; if (start > searchPos) { searchPos = code.indexOf(searchString, start); } } } const NON_WHITESPACE = /\S/g; function findNonWhiteSpace(code, index) { NON_WHITESPACE.lastIndex = index; const result = NON_WHITESPACE.exec(code); return result.index; } // This assumes "code" only contains white-space and comments // Returns position of line-comment if applicable function findFirstLineBreakOutsideComment(code) { let lineBreakPos, charCodeAfterSlash, start = 0; lineBreakPos = code.indexOf('\n', start); while (true) { start = code.indexOf('/', start); if (start === -1 || start > lineBreakPos) return [lineBreakPos, lineBreakPos + 1]; // With our assumption, '/' always starts a comment. Determine comment type: charCodeAfterSlash = code.charCodeAt(start + 1); if (charCodeAfterSlash === 47 /*"/"*/) return [start, lineBreakPos + 1]; start = code.indexOf('*/', start + 3) + 2; if (start > lineBreakPos) { lineBreakPos = code.indexOf('\n', start); } } } function renderStatementList(statements, code, start, end, options) { let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart; let nextNode = statements[0]; let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries; if (nextNodeNeedsBoundaries) { nextNodeStart = start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1]; } for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) { currentNode = nextNode; currentNodeStart = nextNodeStart; currentNodeNeedsBoundaries = nextNodeNeedsBoundaries; nextNode = statements[nextIndex]; nextNodeNeedsBoundaries = nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries; if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) { nextNodeStart = currentNode.end + findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1]; if (currentNode.included) { currentNodeNeedsBoundaries ? currentNode.render(code, options, { end: nextNodeStart, start: currentNodeStart }) : currentNode.render(code, options); } else { treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart); } } else { currentNode.render(code, options); } } } // This assumes that the first character is not part of the first node function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) { const splitUpNodes = []; let node, nextNodeStart, contentEnd, char; let separator = start - 1; for (const nextNode of nodes) { if (node !== undefined) { separator = node.end + findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ','); } nextNodeStart = contentEnd = separator + 1 + findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1]; while (((char = code.original.charCodeAt(nextNodeStart)), char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/) nextNodeStart++; if (node !== undefined) { splitUpNodes.push({ contentEnd, end: nextNodeStart, node, separator, start }); } node = nextNode; start = nextNodeStart; } splitUpNodes.push({ contentEnd: end, end, node: node, separator: null, start }); return splitUpNodes; } // This assumes there are only white-space and comments between start and end function removeLineBreaks(code, start, end) { while (true) { const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end)); if (removeStart === -1) { break; } code.remove(start + removeStart, (start += removeEnd)); } } class BlockScope extends ChildScope { addDeclaration(identifier, context, init, isHoisted) { if (isHoisted) { const variable = this.parent.addDeclaration(identifier, context, init, isHoisted); // Necessary to make sure the init is deoptimized for conditional declarations. // We cannot call deoptimizePath here. variable.markInitializersForDeoptimization(); return variable; } else { return super.addDeclaration(identifier, context, init, false); } } } class ExpressionStatement extends NodeBase$2 { initialise() { if (this.directive && this.directive !== 'use strict' && this.parent.type === Program$1) { this.context.log(LOGLEVEL_WARN, // This is necessary, because either way (deleting or not) can lead to errors. logModuleLevelDirective(this.directive, this.context.module.id), this.start); } } render(code, options) { super.render(code, options); if (this.included) this.insertSemicolon(code); } shouldBeIncluded(context) { if (this.directive && this.directive !== 'use strict') return this.parent.type !== Program$1; return super.shouldBeIncluded(context); } applyDeoptimizations() { } } class BlockStatement extends NodeBase$2 { constructor() { super(...arguments); this.directlyIncluded = false; } addImplicitReturnExpressionToScope() { const lastStatement = this.body[this.body.length - 1]; if (!lastStatement || lastStatement.type !== ReturnStatement$1) { this.scope.addReturnExpression(UNKNOWN_EXPRESSION); } } createScope(parentScope) { this.scope = this.parent.preventChildBlockScope ? parentScope : new BlockScope(parentScope); } hasEffects(context) { if (this.deoptimizeBody) return true; for (const node of this.body) { if (context.brokenFlow) break; if (node.hasEffects(context)) return true; } return false; } include(context, includeChildrenRecursively) { if (!(this.deoptimizeBody && this.directlyIncluded)) { this.included = true; this.directlyIncluded = true; if (this.deoptimizeBody) includeChildrenRecursively = true; for (const node of this.body) { if (includeChildrenRecursively || node.shouldBeIncluded(context)) node.include(context, includeChildrenRecursively); } } } initialise() { const firstBodyStatement = this.body[0]; this.deoptimizeBody = firstBodyStatement instanceof ExpressionStatement && firstBodyStatement.directive === 'use asm'; } render(code, options) { if (this.body.length > 0) { renderStatementList(this.body, code, this.start + 1, this.end - 1, options); } else { super.render(code, options); } } } class RestElement extends NodeBase$2 { constructor() { super(...arguments); this.declarationInit = null; } addExportedVariables(variables, exportNamesByVariable) { this.argument.addExportedVariables(variables, exportNamesByVariable); } declare(kind, init) { this.declarationInit = init; return this.argument.declare(kind, UNKNOWN_EXPRESSION); } deoptimizePath(path) { path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH); } hasEffectsOnInteractionAtPath(path, interaction, context) { return (path.length > 0 || this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context)); } markDeclarationReached() { this.argument.markDeclarationReached(); } applyDeoptimizations() { this.deoptimized = true; if (this.declarationInit !== null) { this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]); this.context.requestTreeshakingPass(); } } } class FunctionBase extends NodeBase$2 { constructor() { super(...arguments); this.objectEntity = null; this.deoptimizedReturn = false; } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { if (interaction.type === INTERACTION_CALLED) { const { parameters } = this.scope; const { args } = interaction; let hasRest = false; for (let position = 0; position < args.length - 1; position++) { const parameter = this.params[position]; // Only the "this" argument arg[0] can be null const argument = args[position + 1]; if (hasRest || parameter instanceof RestElement) { hasRest = true; argument.deoptimizePath(UNKNOWN_PATH); } else if (parameter instanceof Identifier) { parameters[position][0].addEntityToBeDeoptimized(argument); this.addArgumentToBeDeoptimized(argument); } else if (parameter) { argument.deoptimizePath(UNKNOWN_PATH); } else { this.addArgumentToBeDeoptimized(argument); } } } else { this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } } deoptimizePath(path) { this.getObjectEntity().deoptimizePath(path); if (path.length === 1 && path[0] === UnknownKey) { // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track // which means the return expression and parameters need to be reassigned this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH); for (const parameterList of this.scope.parameters) { for (const parameter of parameterList) { parameter.deoptimizePath(UNKNOWN_PATH); } } } } getLiteralValueAtPath(path, recursionTracker, origin) { return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin); } getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) { if (path.length > 0) { return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin); } if (this.async) { if (!this.deoptimizedReturn) { this.deoptimizedReturn = true; this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH); this.context.requestTreeshakingPass(); } return UNKNOWN_RETURN_EXPRESSION; } return [this.scope.getReturnExpression(), false]; } hasEffectsOnInteractionAtPath(path, interaction, context) { if (path.length > 0 || interaction.type !== INTERACTION_CALLED) { return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context); } if (this.annotationNoSideEffects) { return false; } if (this.async) { const { propertyReadSideEffects } = this.context.options .treeshake; const returnExpression = this.scope.getReturnExpression(); if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) || (propertyReadSideEffects && (propertyReadSideEffects === 'always' || returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) { return true; } } for (const parameter of this.params) { if (parameter.hasEffects(context)) return true; } return false; } include(context, includeChildrenRecursively) { if (!this.deoptimized) this.applyDeoptimizations(); this.included = true; const { brokenFlow } = context; context.brokenFlow = false; this.body.include(context, includeChildrenRecursively); context.brokenFlow = brokenFlow; } includeCallArguments(context, parameters) { this.scope.includeCallArguments(context, parameters); } initialise() { this.scope.addParameterVariables(this.params.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement); if (this.body instanceof BlockStatement) { this.body.addImplicitReturnExpressionToScope(); } else { this.scope.addReturnExpression(this.body); } } parseNode(esTreeNode) { if (esTreeNode.body.type === BlockStatement$1) { this.body = new BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope); } super.parseNode(esTreeNode); } addArgumentToBeDeoptimized(_argument) { } applyDeoptimizations() { } } FunctionBase.prototype.preventChildBlockScope = true; class ArrowFunctionExpression extends FunctionBase { constructor() { super(...arguments); this.objectEntity = null; } createScope(parentScope) { this.scope = new ReturnValueScope(parentScope, this.context); } hasEffects() { if (!this.deoptimized) this.applyDeoptimizations(); return false; } hasEffectsOnInteractionAtPath(path, interaction, context) { if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) { return true; } if (this.annotationNoSideEffects) { return false; } if (interaction.type === INTERACTION_CALLED) { const { ignore, brokenFlow } = context; context.ignore = { breaks: false, continues: false, labels: new Set(), returnYield: true, this: false }; if (this.body.hasEffects(context)) return true; context.ignore = ignore; context.brokenFlow = brokenFlow; } return false; } include(context, includeChildrenRecursively) { super.include(context, includeChildrenRecursively); for (const parameter of this.params) { if (!(parameter instanceof Identifier)) { parameter.include(context, includeChildrenRecursively); } } } getObjectEntity() { if (this.objectEntity !== null) { return this.objectEntity; } return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE)); } } function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') { if (exportedVariables.length === 1 && exportNamesByVariable.get(exportedVariables[0]).length === 1) { const variable = exportedVariables[0]; return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName(getPropertyAccess)}${modifier})`; } else { const fields = []; for (const variable of exportedVariables) { for (const exportName of exportNamesByVariable.get(variable)) { fields.push([exportName, variable.getName(getPropertyAccess) + modifier]); } } return `exports(${getObject(fields, { lineBreakIndent: null })})`; } } function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) { code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`); code.appendLeft(expressionEnd, ')'); } function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) { const { _, getDirectReturnIifeLeft } = options.snippets; code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens })); code.appendLeft(expressionEnd, ')'); } function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) { const { _, getPropertyAccess } = options.snippets; code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`); if (needsParens) { code.prependRight(expressionStart, '('); code.appendLeft(expressionEnd, ')'); } } function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) { const { _ } = options.snippets; code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`); if (needsParens) { code.prependRight(expressionStart, '('); code.appendLeft(expressionEnd, ')'); } } class ObjectPattern extends NodeBase$2 { addExportedVariables(variables, exportNamesByVariable) { for (const property of this.properties) { if (property.type === Property$1) { property.value.addExportedVariables(variables, exportNamesByVariable); } else { property.argument.addExportedVariables(variables, exportNamesByVariable); } } } declare(kind, init) { const variables = []; for (const property of this.properties) { variables.push(...property.declare(kind, init)); } return variables; } deoptimizePath(path) { if (path.length === 0) { for (const property of this.properties) { property.deoptimizePath(path); } } } hasEffectsOnInteractionAtPath( // At the moment, this is only triggered for assignment left-hand sides, // where the path is empty _path, interaction, context) { for (const property of this.properties) { if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context)) return true; } return false; } markDeclarationReached() { for (const property of this.properties) { property.markDeclarationReached(); } } } class AssignmentExpression extends NodeBase$2 { hasEffects(context) { const { deoptimized, left, operator, right } = this; if (!deoptimized) this.applyDeoptimizations(); // MemberExpressions do not access the property before assignments if the // operator is '='. return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, operator !== '=')); } hasEffectsOnInteractionAtPath(path, interaction, context) { return this.right.hasEffectsOnInteractionAtPath(path, interaction, context); } include(context, includeChildrenRecursively) { const { deoptimized, left, right, operator } = this; if (!deoptimized) this.applyDeoptimizations(); this.included = true; if (includeChildrenRecursively || operator !== '=' || left.included || left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) { left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '='); } right.include(context, includeChildrenRecursively); } initialise() { this.left.setAssignedValue(this.right); } render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) { const { left, right, start, end, parent } = this; if (left.included) { left.render(code, options); right.render(code, options); } else { const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1); code.remove(start, inclusionStart); if (preventASI) { removeLineBreaks(code, inclusionStart, right.start); } right.render(code, options, { renderedParentType: renderedParentType || parent.type, renderedSurroundingElement: renderedSurroundingElement || parent.type }); } if (options.format === 'system') { if (left instanceof Identifier) { const variable = left.variable; const exportNames = options.exportNamesByVariable.get(variable); if (exportNames) { if (exportNames.length === 1) { renderSystemExportExpression(variable, start, end, code, options); } else { renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options); } return; } } else { const systemPatternExports = []; left.addExportedVariables(systemPatternExports, options.exportNamesByVariable); if (systemPatternExports.length > 0) { renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options); return; } } } if (left.included && left instanceof ObjectPattern && (renderedSurroundingElement === ExpressionStatement$1 || renderedSurroundingElement === ArrowFunctionExpression$1)) { code.appendRight(start, '('); code.prependLeft(end, ')'); } } applyDeoptimizations() { this.deoptimized = true; this.left.deoptimizePath(EMPTY_PATH); this.right.deoptimizePath(UNKNOWN_PATH); this.context.requestTreeshakingPass(); } } class AssignmentPattern extends NodeBase$2 { addExportedVariables(variables, exportNamesByVariable) { this.left.addExportedVariables(variables, exportNamesByVariable); } declare(kind, init) { return this.left.declare(kind, init); } deoptimizePath(path) { path.length === 0 && this.left.deoptimizePath(path); } hasEffectsOnInteractionAtPath(path, interaction, context) { return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context)); } markDeclarationReached() { this.left.markDeclarationReached(); } render(code, options, { isShorthandProperty } = BLANK) { this.left.render(code, options, { isShorthandProperty }); this.right.render(code, options); } applyDeoptimizations() { this.deoptimized = true; this.left.deoptimizePath(EMPTY_PATH); this.right.deoptimizePath(UNKNOWN_PATH); this.context.requestTreeshakingPass(); } } class ArgumentsVariable extends LocalVariable { constructor(context) { super('arguments', null, UNKNOWN_EXPRESSION, context); this.deoptimizedArguments = []; } addArgumentToBeDeoptimized(argument) { if (this.included) { argument.deoptimizePath(UNKNOWN_PATH); } else { this.deoptimizedArguments.push(argument); } } hasEffectsOnInteractionAtPath(path, { type }) { return type !== INTERACTION_ACCESSED || path.length > 1; } include() { super.include(); for (const argument of this.deoptimizedArguments) { argument.deoptimizePath(UNKNOWN_PATH); } this.deoptimizedArguments.length = 0; } } class ThisVariable extends ParameterVariable { constructor(context) { super('this', null, context); } hasEffectsOnInteractionAtPath(path, interaction, context) { return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context); } } class FunctionScope extends ReturnValueScope { constructor(parent, context) { super(parent, context); this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context))); this.variables.set('this', (this.thisVariable = new ThisVariable(context))); } findLexicalBoundary() { return this; } includeCallArguments(context, parameters) { super.includeCallArguments(context, parameters); if (this.argumentsVariable.included) { for (const argument of parameters) { if (!argument.included) { argument.include(context, false); } } } } } class FunctionNode extends FunctionBase { constructor() { super(...arguments); this.objectEntity = null; } createScope(parentScope) { this.scope = new FunctionScope(parentScope, this.context); this.constructedEntity = new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE); // This makes sure that all deoptimizations of "this" are applied to the // constructed entity. this.scope.thisVariable.addEntityToBeDeoptimized(this.constructedEntity); } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) { // args[0] is the "this" argument this.scope.thisVariable.addEntityToBeDeoptimized(interaction.args[0]); } } hasEffects(context) { if (!this.deoptimized) this.applyDeoptimizations(); if (this.annotationNoSideEffects) { return false; } return !!this.id?.hasEffects(context); } hasEffectsOnInteractionAtPath(path, interaction, context) { if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) return true; if (this.annotationNoSideEffects) { return false; } if (interaction.type === INTERACTION_CALLED) { const thisInit = context.replacedVariableInits.get(this.scope.thisVariable); context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION); const { brokenFlow, ignore, replacedVariableInits } = context; context.ignore = { breaks: false, continues: false, labels: new Set(), returnYield: true, this: interaction.withNew }; if (this.body.hasEffects(context)) return true; context.brokenFlow = brokenFlow; if (thisInit) { replacedVariableInits.set(this.scope.thisVariable, thisInit); } else { replacedVariableInits.delete(this.scope.thisVariable); } context.ignore = ignore; } return false; } include(context, includeChildrenRecursively) { super.include(context, includeChildrenRecursively); this.id?.include(); const hasArguments = this.scope.argumentsVariable.included; for (const parameter of this.params) { if (!(parameter instanceof Identifier) || hasArguments) { parameter.include(context, includeChildrenRecursively); } } } initialise() { super.initialise(); this.id?.declare('function', this); } addArgumentToBeDeoptimized(argument) { this.scope.argumentsVariable.addArgumentToBeDeoptimized(argument); } getObjectEntity() { if (this.objectEntity !== null) { return this.objectEntity; } return (this.objectEntity = new ObjectEntity([ { key: 'prototype', kind: 'init', property: new ObjectEntity([], OBJECT_PROTOTYPE) } ], OBJECT_PROTOTYPE)); } } class AwaitExpression extends NodeBase$2 { hasEffects() { if (!this.deoptimized) this.applyDeoptimizations(); return true; } include(context, includeChildrenRecursively) { if (!this.deoptimized) this.applyDeoptimizations(); if (!this.included) { this.included = true; checkTopLevelAwait: if (!this.context.usesTopLevelAwait) { let parent = this.parent; do { if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression) break checkTopLevelAwait; } while ((parent = parent.parent)); this.context.usesTopLevelAwait = true; } } this.argument.include(context, includeChildrenRecursively); } } const binaryOperators = { '!=': (left, right) => left != right, '!==': (left, right) => left !== right, '%': (left, right) => left % right, '&': (left, right) => left & right, '*': (left, right) => left * right, // At the moment, "**" will be transpiled to Math.pow '**': (left, right) => left ** right, '+': (left, right) => left + right, '-': (left, right) => left - right, '/': (left, right) => left / right, '<': (left, right) => left < right, '<<': (left, right) => left << right, '<=': (left, right) => left <= right, '==': (left, right) => left == right, '===': (left, right) => left === right, '>': (left, right) => left > right, '>=': (left, right) => left >= right, '>>': (left, right) => left >> right, '>>>': (left, right) => left >>> right, '^': (left, right) => left ^ right, '|': (left, right) => left | right // We use the fallback for cases where we return something unknown // in: () => UnknownValue, // instanceof: () => UnknownValue, }; class BinaryExpression extends NodeBase$2 { deoptimizeCache() { } getLiteralValueAtPath(path, recursionTracker, origin) { if (path.length > 0) return UnknownValue; const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin); if (typeof leftValue === 'symbol') return UnknownValue; const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin); if (typeof rightValue === 'symbol') return UnknownValue; const operatorFunction = binaryOperators[this.operator]; if (!operatorFunction) return UnknownValue; return operatorFunction(leftValue, rightValue); } hasEffects(context) { // support some implicit type coercion runtime errors if (this.operator === '+' && this.parent instanceof ExpressionStatement && this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') { return true; } return super.hasEffects(context); } hasEffectsOnInteractionAtPath(path, { type }) { return type !== INTERACTION_ACCESSED || path.length > 1; } render(code, options, { renderedSurroundingElement } = BLANK) { this.left.render(code, options, { renderedSurroundingElement }); this.right.render(code, options); } } class BreakStatement extends NodeBase$2 { hasEffects(context) { if (this.label) { if (!context.ignore.labels.has(this.label.name)) return true; context.includedLabels.add(this.label.name); } else { if (!context.ignore.breaks) return true; context.hasBreak = true; } context.brokenFlow = true; return false; } include(context) { this.included = true; if (this.label) { this.label.include(); context.includedLabels.add(this.label.name); } else { context.hasBreak = true; } context.brokenFlow = true; } } function renderCallArguments(code, options, node) { if (node.arguments.length > 0) { if (node.arguments[node.arguments.length - 1].included) { for (const argument of node.arguments) { argument.render(code, options); } } else { let lastIncludedIndex = node.arguments.length - 2; while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) { lastIncludedIndex--; } if (lastIncludedIndex >= 0) { for (let index = 0; index <= lastIncludedIndex; index++) { node.arguments[index].render(code, options); } code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1); } else { code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1); } } } } class Literal extends NodeBase$2 { deoptimizeArgumentsOnInteractionAtPath() { } getLiteralValueAtPath(path) { if (path.length > 0 || // unknown literals can also be null but do not start with an "n" (this.value === null && this.context.code.charCodeAt(this.start) !== 110) || typeof this.value === 'bigint' || // to support shims for regular expressions this.context.code.charCodeAt(this.start) === 47) { return UnknownValue; } return this.value; } getReturnExpressionWhenCalledAtPath(path) { if (path.length !== 1) return UNKNOWN_RETURN_EXPRESSION; return getMemberReturnExpressionWhenCalled(this.members, path[0]); } hasEffectsOnInteractionAtPath(path, interaction, context) { switch (interaction.type) { case INTERACTION_ACCESSED: { return path.length > (this.value === null ? 0 : 1); } case INTERACTION_ASSIGNED: { return true; } case INTERACTION_CALLED: { if (this.included && this.value instanceof RegExp && (this.value.global || this.value.sticky)) { return true; } return (path.length !== 1 || hasMemberEffectWhenCalled(this.members, path[0], interaction, context)); } } } initialise() { this.members = getLiteralMembersForValue(this.value); } parseNode(esTreeNode) { this.value = esTreeNode.value; this.regex = esTreeNode.regex; super.parseNode(esTreeNode); } render(code) { if (typeof this.value === 'string') { code.indentExclusionRanges.push([this.start + 1, this.end - 1]); } } } // To avoid infinite recursions const MAX_PATH_DEPTH = 7; function getResolvablePropertyKey(memberExpression) { return memberExpression.computed ? getResolvableComputedPropertyKey(memberExpression.property) : memberExpression.property.name; } function getResolvableComputedPropertyKey(propertyKey) { if (propertyKey instanceof Literal) { return String(propertyKey.value); } return null; } function getPathIfNotComputed(memberExpression) { const nextPathKey = memberExpression.propertyKey; const object = memberExpression.object; if (typeof nextPathKey === 'string') { if (object instanceof Identifier) { return [ { key: object.name, pos: object.start }, { key: nextPathKey, pos: memberExpression.property.start } ]; } if (object instanceof MemberExpression) { const parentPath = getPathIfNotComputed(object); return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]); } } return null; } function getStringFromPath(path) { let pathString = path[0].key; for (let index = 1; index < path.length; index++) { pathString += '.' + path[index].key; } return pathString; } class MemberExpression extends NodeBase$2 { constructor() { super(...arguments); this.variable = null; this.assignmentDeoptimized = false; this.bound = false; this.expressionsToBeDeoptimized = []; this.isUndefined = false; } bind() { this.bound = true; const path = getPathIfNotComputed(this); const baseVariable = path && this.scope.findVariable(path[0].key); if (baseVariable?.isNamespace) { const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.context); if (!resolvedVariable) { super.bind(); } else if (resolvedVariable === 'undefined') { this.isUndefined = true; } else { this.variable = resolvedVariable; this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable); } } else { super.bind(); } } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { if (this.variable) { this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } else if (!this.isUndefined) { if (path.length < MAX_PATH_DEPTH) { this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker); } else { deoptimizeInteraction(interaction); } } } deoptimizeCache() { const { expressionsToBeDeoptimized, object } = this; this.expressionsToBeDeoptimized = EMPTY_ARRAY; this.propertyKey = UnknownKey; object.deoptimizePath(UNKNOWN_PATH); for (const expression of expressionsToBeDeoptimized) { expression.deoptimizeCache(); } } deoptimizePath(path) { if (path.length === 0) this.disallowNamespaceReassignment(); if (this.variable) { this.variable.deoptimizePath(path); } else if (!this.isUndefined && path.length < MAX_PATH_DEPTH) { const propertyKey = this.getPropertyKey(); this.object.deoptimizePath([ propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey, ...path ]); } } getLiteralValueAtPath(path, recursionTracker, origin) { if (this.variable) { return this.variable.getLiteralValueAtPath(path, recursionTracker, origin); } if (this.isUndefined) { return undefined; } if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) { this.expressionsToBeDeoptimized.push(origin); return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin); } return UnknownValue; } getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) { if (this.variable) { return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin); } if (this.isUndefined) { return [UNDEFINED_EXPRESSION, false]; } if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) { this.expressionsToBeDeoptimized.push(origin); return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin); } return UNKNOWN_RETURN_EXPRESSION; } hasEffects(context) { if (!this.deoptimized) this.applyDeoptimizations(); return (this.property.hasEffects(context) || this.object.hasEffects(context) || this.hasAccessEffect(context)); } hasEffectsAsAssignmentTarget(context, checkAccess) { if (checkAccess && !this.deoptimized) this.applyDeoptimizations(); if (!this.assignmentDeoptimized) this.applyAssignmentDeoptimization(); return (this.property.hasEffects(context) || this.object.hasEffects(context) || (checkAccess && this.hasAccessEffect(context)) || this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context)); } hasEffectsOnInteractionAtPath(path, interaction, context) { if (this.variable) { return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context); } if (this.isUndefined) { return true; } if (path.length < MAX_PATH_DEPTH) { return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context); } return true; } include(context, includeChildrenRecursively) { if (!this.deoptimized) this.applyDeoptimizations(); this.includeProperties(context, includeChildrenRecursively); } includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) { if (!this.assignmentDeoptimized) this.applyAssignmentDeoptimization(); if (deoptimizeAccess) { this.include(context, includeChildrenRecursively); } else { this.includeProperties(context, includeChildrenRecursively); } } includeCallArguments(context, parameters) { if (this.variable) { this.variable.includeCallArguments(context, parameters); } else { super.includeCallArguments(context, parameters); } } initialise() { this.propertyKey = getResolvablePropertyKey(this); this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED }; } isSkippedAsOptional(origin) { return (!this.variable && !this.isUndefined && (this.object.isSkippedAsOptional?.(origin) || (this.optional && this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null))); } render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) { if (this.variable || this.isUndefined) { const { snippets: { getPropertyAccess } } = options; let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined'; if (renderedParentType && isCalleeOfRenderedParent) replacement = '0, ' + replacement; code.overwrite(this.start, this.end, replacement, { contentOnly: true, storeName: true }); } else { if (renderedParentType && isCalleeOfRenderedParent) { code.appendRight(this.start, '0, '); } this.object.render(code, options, { renderedSurroundingElement }); this.property.render(code, options); } } setAssignedValue(value) { this.assignmentInteraction = { args: [this.object, value], type: INTERACTION_ASSIGNED }; } applyDeoptimizations() { this.deoptimized = true; const { propertyReadSideEffects } = this.context.options .treeshake; if ( // Namespaces are not bound and should not be deoptimized this.bound && propertyReadSideEffects && !(this.variable || this.isUndefined)) { const propertyKey = this.getPropertyKey(); this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER); this.context.requestTreeshakingPass(); } } applyAssignmentDeoptimization() { this.assignmentDeoptimized = true; const { propertyReadSideEffects } = this.context.options .treeshake; if ( // Namespaces are not bound and should not be deoptimized this.bound && propertyReadSideEffects && !(this.variable || this.isUndefined)) { this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER); this.context.requestTreeshakingPass(); } } disallowNamespaceReassignment() { if (this.object instanceof Identifier) { const variable = this.scope.findVariable(this.object.name); if (variable.isNamespace) { if (this.variable) { this.context.includeVariableInModule(this.variable); } this.context.log(LOGLEVEL_WARN, logIllegalImportReassignment(this.object.name, this.context.module.id), this.start); } } } getPropertyKey() { if (this.propertyKey === null) { this.propertyKey = UnknownKey; const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this); return (this.propertyKey = value === SymbolToStringTag ? value : typeof value === 'symbol' ? UnknownKey : String(value)); } return this.propertyKey; } hasAccessEffect(context) { const { propertyReadSideEffects } = this.context.options .treeshake; return (!(this.variable || this.isUndefined) && propertyReadSideEffects && (propertyReadSideEffects === 'always' || this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context))); } includeProperties(context, includeChildrenRecursively) { if (!this.included) { this.included = true; if (this.variable) { this.context.includeVariableInModule(this.variable); } } this.object.include(context, includeChildrenRecursively); this.property.include(context, includeChildrenRecursively); } } function resolveNamespaceVariables(baseVariable, path, astContext) { if (path.length === 0) return baseVariable; if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable) return null; const exportName = path[0].key; const variable = baseVariable.context.traceExport(exportName); if (!variable) { if (path.length === 1) { const fileName = baseVariable.context.fileName; astContext.log(LOGLEVEL_WARN, logMissingExport(exportName, astContext.module.id, fileName), path[0].pos); return 'undefined'; } return null; } return resolveNamespaceVariables(variable, path.slice(1), astContext); } class CallExpressionBase extends NodeBase$2 { constructor() { super(...arguments); this.returnExpression = null; this.deoptimizableDependentExpressions = []; this.expressionsToBeDeoptimized = new Set(); } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { const { args } = interaction; const [returnExpression, isPure] = this.getReturnExpression(recursionTracker); if (isPure) return; const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION); if (deoptimizedExpressions.length === 0) return; if (returnExpression === UNKNOWN_EXPRESSION) { for (const expression of deoptimizedExpressions) { expression.deoptimizePath(UNKNOWN_PATH); } } else { recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => { for (const expression of deoptimizedExpressions) { this.expressionsToBeDeoptimized.add(expression); } returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); }, null); } } deoptimizeCache() { if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) { this.returnExpression = UNKNOWN_RETURN_EXPRESSION; const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this; this.expressionsToBeDeoptimized = EMPTY_SET; this.deoptimizableDependentExpressions = EMPTY_ARRAY; for (const expression of deoptimizableDependentExpressions) { expression.deoptimizeCache(); } for (const expression of expressionsToBeDeoptimized) { expression.deoptimizePath(UNKNOWN_PATH); } } } deoptimizePath(path) { if (path.length === 0 || this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) { return; } const [returnExpression] = this.getReturnExpression(); if (returnExpression !== UNKNOWN_EXPRESSION) { returnExpression.deoptimizePath(path); } } getLiteralValueAtPath(path, recursionTracker, origin) { const [returnExpression] = this.getReturnExpression(recursionTracker); if (returnExpression === UNKNOWN_EXPRESSION) { return UnknownValue; } return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => { this.deoptimizableDependentExpressions.push(origin); return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin); }, UnknownValue); } getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) { const returnExpression = this.getReturnExpression(recursionTracker); if (returnExpression[0] === UNKNOWN_EXPRESSION) { return returnExpression; } return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => { this.deoptimizableDependentExpressions.push(origin); const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin); return [expression, isPure || returnExpression[1]]; }, UNKNOWN_RETURN_EXPRESSION); } hasEffectsOnInteractionAtPath(path, interaction, context) { const { type } = interaction; if (type === INTERACTION_CALLED) { const { args, withNew } = interaction; if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) { return false; } } else if ((type === INTERACTION_ASSIGNED ? context.assigned : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) { return false; } const [returnExpression, isPure] = this.getReturnExpression(); return ((type === INTERACTION_ASSIGNED || !isPure) && returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context)); } } class CallExpression extends CallExpressionBase { bind() { super.bind(); if (this.callee instanceof Identifier) { const variable = this.scope.findVariable(this.callee.name); if (variable.isNamespace) { this.context.log(LOGLEVEL_WARN, logCannotCallNamespace(this.callee.name), this.start); } if (this.callee.name === 'eval') { this.context.log(LOGLEVEL_WARN, logEval(this.context.module.id), this.start); } } this.interaction = { args: [ this.callee instanceof MemberExpression && !this.callee.variable ? this.callee.object : null, ...this.arguments ], type: INTERACTION_CALLED, withNew: false }; } hasEffects(context) { try { for (const argument of this.arguments) { if (argument.hasEffects(context)) return true; } if (this.annotationPure) { return false; } return (this.callee.hasEffects(context) || this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context)); } finally { if (!this.deoptimized) this.applyDeoptimizations(); } } include(context, includeChildrenRecursively) { if (!this.deoptimized) this.applyDeoptimizations(); if (includeChildrenRecursively) { super.include(context, includeChildrenRecursively); if (includeChildrenRecursively === INCLUDE_PARAMETERS && this.callee instanceof Identifier && this.callee.variable) { this.callee.variable.markCalledFromTryStatement(); } } else { this.included = true; this.callee.include(context, false); } this.callee.includeCallArguments(context, this.arguments); } isSkippedAsOptional(origin) { return (this.callee.isSkippedAsOptional?.(origin) || (this.optional && this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null)); } render(code, options, { renderedSurroundingElement } = BLANK) { this.callee.render(code, options, { isCalleeOfRenderedParent: true, renderedSurroundingElement }); renderCallArguments(code, options, this); } applyDeoptimizations() { this.deoptimized = true; this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER); this.context.requestTreeshakingPass(); } getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) { if (this.returnExpression === null) { this.returnExpression = UNKNOWN_RETURN_EXPRESSION; return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this)); } return this.returnExpression; } } class CatchScope extends ParameterScope { addDeclaration(identifier, context, init, isHoisted) { const existingParameter = this.variables.get(identifier.name); if (existingParameter) { // While we still create a hoisted declaration, the initializer goes to // the parameter. Note that technically, the declaration now belongs to // two variables, which is not correct but should not cause issues. this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted); existingParameter.addDeclaration(identifier, init); return existingParameter; } return this.parent.addDeclaration(identifier, context, init, isHoisted); } } class CatchClause extends NodeBase$2 { createScope(parentScope) { this.scope = new CatchScope(parentScope, this.context); } parseNode(esTreeNode) { // Parameters need to be declared first as the logic is that initializers // of hoisted body variables are associated with parameters of the same // name instead of the variable const { param } = esTreeNode; if (param) { this.param = new (this.context.getNodeConstructor(param.type))(param, this, this.scope); this.param.declare('parameter', UNKNOWN_EXPRESSION); } super.parseNode(esTreeNode); } } class ChainExpression extends NodeBase$2 { // deoptimizations are not relevant as we are not caching values deoptimizeCache() { } getLiteralValueAtPath(path, recursionTracker, origin) { if (this.expression.isSkippedAsOptional(origin)) return undefined; return this.expression.getLiteralValueAtPath(path, recursionTracker, origin); } hasEffects(context) { if (this.expression.isSkippedAsOptional(this)) return false; return this.expression.hasEffects(context); } } class ClassBodyScope extends ChildScope { constructor(parent, classNode, context) { super(parent); this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context))); this.instanceScope = new ChildScope(this); this.instanceScope.variables.set('this', new ThisVariable(context)); } findLexicalBoundary() { return this; } } class ClassBody extends NodeBase$2 { createScope(parentScope) { this.scope = new ClassBodyScope(parentScope, this.parent, this.context); } include(context, includeChildrenRecursively) { this.included = true; this.context.includeVariableInModule(this.scope.thisVariable); for (const definition of this.body) { definition.include(context, includeChildrenRecursively); } } parseNode(esTreeNode) { const body = (this.body = []); for (const definition of esTreeNode.body) { body.push(new (this.context.getNodeConstructor(definition.type))(definition, this, definition.static ? this.scope : this.scope.instanceScope)); } super.parseNode(esTreeNode); } applyDeoptimizations() { } } class MethodBase extends NodeBase$2 { constructor() { super(...arguments); this.accessedValue = null; } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) { return this.value.deoptimizeArgumentsOnInteractionAtPath({ args: interaction.args, type: INTERACTION_CALLED, withNew: false }, EMPTY_PATH, recursionTracker); } if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) { return this.value.deoptimizeArgumentsOnInteractionAtPath({ args: interaction.args, type: INTERACTION_CALLED, withNew: false }, EMPTY_PATH, recursionTracker); } this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } // As getter properties directly receive their values from fixed function // expressions, there is no known situation where a getter is deoptimized. deoptimizeCache() { } deoptimizePath(path) { this.getAccessedValue()[0].deoptimizePath(path); } getLiteralValueAtPath(path, recursionTracker, origin) { return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin); } getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) { return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin); } hasEffects(context) { return this.key.hasEffects(context); } hasEffectsOnInteractionAtPath(path, interaction, context) { if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) { return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, { args: interaction.args, type: INTERACTION_CALLED, withNew: false }, context); } // setters are only called for empty paths if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) { return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, { args: interaction.args, type: INTERACTION_CALLED, withNew: false }, context); } return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context); } applyDeoptimizations() { } getAccessedValue() { if (this.accessedValue === null) { if (this.kind === 'get') { this.accessedValue = UNKNOWN_RETURN_EXPRESSION; return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this)); } else { return (this.accessedValue = [this.value, false]); } } return this.accessedValue; } } class MethodDefinition extends MethodBase { applyDeoptimizations() { } } class ObjectMember extends ExpressionEntity { constructor(object, key) { super(); this.object = object; this.key = key; } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker); } deoptimizePath(path) { this.object.deoptimizePath([this.key, ...path]); } getLiteralValueAtPath(path, recursionTracker, origin) { return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin); } getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) { return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin); } hasEffectsOnInteractionAtPath(path, interaction, context) { return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context); } } class ClassNode extends NodeBase$2 { constructor() { super(...arguments); this.objectEntity = null; } createScope(parentScope) { this.scope = new ChildScope(parentScope); } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } deoptimizeCache() { this.getObjectEntity().deoptimizeAllProperties(); } deoptimizePath(path) { this.getObjectEntity().deoptimizePath(path); } getLiteralValueAtPath(path, recursionTracker, origin) { return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin); } getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) { return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin); } hasEffects(context) { if (!this.deoptimized) this.applyDeoptimizations(); const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context); this.id?.markDeclarationReached(); return initEffect || super.hasEffects(context); } hasEffectsOnInteractionAtPath(path, interaction, context) { return interaction.type === INTERACTION_CALLED && path.length === 0 ? !interaction.withNew || (this.classConstructor === null ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context) : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) || false : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context); } include(context, includeChildrenRecursively) { if (!this.deoptimized) this.applyDeoptimizations(); this.included = true; this.superClass?.include(context, includeChildrenRecursively); this.body.include(context, includeChildrenRecursively); if (this.id) { this.id.markDeclarationReached(); this.id.include(); } } initialise() { this.id?.declare('class', this); for (const method of this.body.body) { if (method instanceof MethodDefinition && method.kind === 'constructor') { this.classConstructor = method; return; } } this.classConstructor = null; } applyDeoptimizations() { this.deoptimized = true; for (const definition of this.body.body) { if (!(definition.static || (definition instanceof MethodDefinition && definition.kind === 'constructor'))) { // Calls to methods are not tracked, ensure that the return value is deoptimized definition.deoptimizePath(UNKNOWN_PATH); } } this.context.requestTreeshakingPass(); } getObjectEntity() { if (this.objectEntity !== null) { return this.objectEntity; } const staticProperties = []; const dynamicMethods = []; for (const definition of this.body.body) { const properties = definition.static ? staticProperties : dynamicMethods; const definitionKind = definition.kind; // Note that class fields do not end up on the prototype if (properties === dynamicMethods && !definitionKind) continue; const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init'; let key; if (definition.computed) { const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this); if (typeof keyValue === 'symbol') { properties.push({ key: UnknownKey, kind, property: definition }); continue; } else { key = String(keyValue); } } else { key = definition.key instanceof Identifier ? definition.key.name : String(definition.key.value); } properties.push({ key, kind, property: definition }); } staticProperties.unshift({ key: 'prototype', kind: 'init', property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE) }); return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE)); } } class ClassDeclaration extends ClassNode { initialise() { super.initialise(); if (this.id !== null) { this.id.variable.isId = true; } } parseNode(esTreeNode) { if (esTreeNode.id !== null) { this.id = new Identifier(esTreeNode.id, this, this.scope.parent); } super.parseNode(esTreeNode); } render(code, options) { const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options; if (this.id) { const { variable, name } = this.id; if (format === 'system' && exportNamesByVariable.has(variable)) { code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`); } const renderedVariable = variable.getName(getPropertyAccess); if (renderedVariable !== name) { this.superClass?.render(code, options); this.body.render(code, { ...options, useOriginalName: (_variable) => _variable === variable }); code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`); code.prependLeft(this.end, ';'); return; } } super.render(code, options); } applyDeoptimizations() { super.applyDeoptimizations(); const { id, scope } = this; if (id) { const { name, variable } = id; for (const accessedVariable of scope.accessedOutsideVariables.values()) { if (accessedVariable !== variable) { accessedVariable.forbidName(name); } } } } } class ClassExpression extends ClassNode { render(code, options, { renderedSurroundingElement } = BLANK) { super.render(code, options); if (renderedSurroundingElement === ExpressionStatement$1) { code.appendRight(this.start, '('); code.prependLeft(this.end, ')'); } } } class MultiExpression extends ExpressionEntity { constructor(expressions) { super(); this.expressions = expressions; this.included = false; } deoptimizePath(path) { for (const expression of this.expressions) { expression.deoptimizePath(path); } } getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) { return [ new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])), false ]; } hasEffectsOnInteractionAtPath(path, interaction, context) { for (const expression of this.expressions) { if (expression.hasEffectsOnInteractionAtPath(path, interaction, context)) return true; } return false; } } class ConditionalExpression extends NodeBase$2 { constructor() { super(...arguments); this.expressionsToBeDeoptimized = []; this.isBranchResolutionAnalysed = false; this.usedBranch = null; } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } deoptimizeCache() { if (this.usedBranch !== null) { const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent; this.usedBranch = null; unusedBranch.deoptimizePath(UNKNOWN_PATH); const { expressionsToBeDeoptimized } = this; this.expressionsToBeDeoptimized = EMPTY_ARRAY; for (const expression of expressionsToBeDeoptimized) { expression.deoptimizeCache(); } } } deoptimizePath(path) { const usedBranch = this.getUsedBranch(); if (usedBranch) { usedBranch.deoptimizePath(path); } else { this.consequent.deoptimizePath(path); this.alternate.deoptimizePath(path); } } getLiteralValueAtPath(path, recursionTracker, origin) { const usedBranch = this.getUsedBranch(); if (!usedBranch) return UnknownValue; this.expressionsToBeDeoptimized.push(origin); return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin); } getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) { const usedBranch = this.getUsedBranch(); if (!usedBranch) return [ new MultiExpression([ this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0], this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0] ]), false ]; this.expressionsToBeDeoptimized.push(origin); return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin); } hasEffects(context) { if (this.test.hasEffects(context)) return true; const usedBranch = this.getUsedBranch(); if (!usedBranch) { return this.consequent.hasEffects(context) || this.alternate.hasEffects(context); } return usedBranch.hasEffects(context); } hasEffectsOnInteractionAtPath(path, interaction, context) { const usedBranch = this.getUsedBranch(); if (!usedBranch) { return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) || this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context)); } return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context); } include(context, includeChildrenRecursively) { this.included = true; const usedBranch = this.getUsedBranch(); if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) { this.test.include(context, includeChildrenRecursively); this.consequent.include(context, includeChildrenRecursively); this.alternate.include(context, includeChildrenRecursively); } else { usedBranch.include(context, includeChildrenRecursively); } } includeCallArguments(context, parameters) { const usedBranch = this.getUsedBranch(); if (usedBranch) { usedBranch.includeCallArguments(context, parameters); } else { this.consequent.includeCallArguments(context, parameters); this.alternate.includeCallArguments(context, parameters); } } render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) { const usedBranch = this.getUsedBranch(); if (this.test.included) { this.test.render(code, options, { renderedSurroundingElement }); this.consequent.render(code, options); this.alternate.render(code, options); } else { const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end); const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end) : colonPos) + 1); if (preventASI) { removeLineBreaks(code, inclusionStart, usedBranch.start); } code.remove(this.start, inclusionStart); if (this.consequent.included) { code.remove(colonPos, this.end); } removeAnnotations(this, code); usedBranch.render(code, options, { isCalleeOfRenderedParent, preventASI: true, renderedParentType: renderedParentType || this.parent.type, renderedSurroundingElement: renderedSurroundingElement || this.parent.type }); } } getUsedBranch() { if (this.isBranchResolutionAnalysed) { return this.usedBranch; } this.isBranchResolutionAnalysed = true; const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this); return typeof testValue === 'symbol' ? null : (this.usedBranch = testValue ? this.consequent : this.alternate); } } class ContinueStatement extends NodeBase$2 { hasEffects(context) { if (this.label) { if (!context.ignore.labels.has(this.label.name)) return true; context.includedLabels.add(this.label.name); } else { if (!context.ignore.continues) return true; context.hasContinue = true; } context.brokenFlow = true; return false; } include(context) { this.included = true; if (this.label) { this.label.include(); context.includedLabels.add(this.label.name); } else { context.hasContinue = true; } context.brokenFlow = true; } } function hasLoopBodyEffects(context, body) { const { brokenFlow, hasBreak, hasContinue, ignore } = context; const { breaks, continues } = ignore; ignore.breaks = true; ignore.continues = true; context.hasBreak = false; context.hasContinue = false; if (body.hasEffects(context)) return true; ignore.breaks = breaks; ignore.continues = continues; context.hasBreak = hasBreak; context.hasContinue = hasContinue; context.brokenFlow = brokenFlow; return false; } function includeLoopBody(context, body, includeChildrenRecursively) { const { brokenFlow, hasBreak, hasContinue } = context; context.hasBreak = false; context.hasContinue = false; body.include(context, includeChildrenRecursively, { asSingleStatement: true }); context.hasBreak = hasBreak; context.hasContinue = hasContinue; context.brokenFlow = brokenFlow; } class DoWhileStatement extends NodeBase$2 { hasEffects(context) { if (this.test.hasEffects(context)) return true; return hasLoopBodyEffects(context, this.body); } include(context, includeChildrenRecursively) { this.included = true; this.test.include(context, includeChildrenRecursively); includeLoopBody(context, this.body, includeChildrenRecursively); } } class EmptyStatement extends NodeBase$2 { hasEffects() { return false; } } class ExportAllDeclaration extends NodeBase$2 { hasEffects() { return false; } initialise() { this.context.addExport(this); } render(code, _options, nodeRenderOptions) { code.remove(nodeRenderOptions.start, nodeRenderOptions.end); } applyDeoptimizations() { } } ExportAllDeclaration.prototype.needsBoundaries = true; class FunctionDeclaration extends FunctionNode { initialise() { super.initialise(); if (this.id !== null) { this.id.variable.isId = true; } } parseNode(esTreeNode) { if (esTreeNode.id !== null) { this.id = new Identifier(esTreeNode.id, this, this.scope.parent); } super.parseNode(esTreeNode); } } // The header ends at the first non-white-space after "default" function getDeclarationStart(code, start) { return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7); } function getFunctionIdInsertPosition(code, start) { const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length; code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd)); const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*'); if (generatorStarPos === -1) { return declarationEnd; } return declarationEnd + generatorStarPos + 1; } class ExportDefaultDeclaration extends NodeBase$2 { include(context, includeChildrenRecursively) { super.include(context, includeChildrenRecursively); if (includeChildrenRecursively) { this.context.includeVariableInModule(this.variable); } } initialise() { const declaration = this.declaration; this.declarationName = (declaration.id && declaration.id.name) || this.declaration.name; this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context); this.context.addExport(this); } render(code, options, nodeRenderOptions) { const { start, end } = nodeRenderOptions; const declarationStart = getDeclarationStart(code.original, this.start); if (this.declaration instanceof FunctionDeclaration) { this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null ? getFunctionIdInsertPosition(code.original, declarationStart) : null, options); } else if (this.declaration instanceof ClassDeclaration) { this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length : null, options); } else if (this.variable.getOriginalVariable() !== this.variable) { // Remove altogether to prevent re-declaring the same variable treeshakeNode(this, code, start, end); return; } else if (this.variable.included) { this.renderVariableDeclaration(code, declarationStart, options); } else { code.remove(this.start, declarationStart); this.declaration.render(code, options, { renderedSurroundingElement: ExpressionStatement$1 }); if (code.original[this.end - 1] !== ';') { code.appendLeft(this.end, ';'); } return; } this.declaration.render(code, options); } applyDeoptimizations() { } renderNamedDeclaration(code, declarationStart, idInsertPosition, options) { const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options; const name = this.variable.getName(getPropertyAccess); // Remove `export default` code.remove(this.start, declarationStart); if (idInsertPosition !== null) { code.appendLeft(idInsertPosition, ` ${name}`); } if (format === 'system' && this.declaration instanceof ClassDeclaration && exportNamesByVariable.has(this.variable)) { code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`); } } renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) { const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/ const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable); if (systemExportNames) { code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports('${systemExportNames[0]}', `); code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';')); } else { code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `); if (!hasTrailingSemicolon) { code.appendLeft(this.end, ';'); } } } } ExportDefaultDeclaration.prototype.needsBoundaries = true; class ExportNamedDeclaration extends NodeBase$2 { bind() { // Do not bind specifiers this.declaration?.bind(); } hasEffects(context) { return !!this.declaration?.hasEffects(context); } initialise() { this.context.addExport(this); } render(code, options, nodeRenderOptions) { const { start, end } = nodeRenderOptions; if (this.declaration === null) { code.remove(start, end); } else { code.remove(this.start, this.declaration.start); this.declaration.render(code, options, { end, start }); } } applyDeoptimizations() { } } ExportNamedDeclaration.prototype.needsBoundaries = true; class ExportSpecifier extends NodeBase$2 { applyDeoptimizations() { } } class ForInStatement extends NodeBase$2 { createScope(parentScope) { this.scope = new BlockScope(parentScope); } hasEffects(context) { const { body, deoptimized, left, right } = this; if (!deoptimized) this.applyDeoptimizations(); if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context)) return true; return hasLoopBodyEffects(context, body); } include(context, includeChildrenRecursively) { const { body, deoptimized, left, right } = this; if (!deoptimized) this.applyDeoptimizations(); this.included = true; left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false); right.include(context, includeChildrenRecursively); includeLoopBody(context, body, includeChildrenRecursively); } initialise() { this.left.setAssignedValue(UNKNOWN_EXPRESSION); } render(code, options) { this.left.render(code, options, NO_SEMICOLON); this.right.render(code, options, NO_SEMICOLON); // handle no space between "in" and the right side if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) { code.prependLeft(this.right.start, ' '); } this.body.render(code, options); } applyDeoptimizations() { this.deoptimized = true; this.left.deoptimizePath(EMPTY_PATH); this.context.requestTreeshakingPass(); } } class ForOfStatement extends NodeBase$2 { createScope(parentScope) { this.scope = new BlockScope(parentScope); } hasEffects() { if (!this.deoptimized) this.applyDeoptimizations(); // Placeholder until proper Symbol.Iterator support return true; } include(context, includeChildrenRecursively) { const { body, deoptimized, left, right } = this; if (!deoptimized) this.applyDeoptimizations(); this.included = true; left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false); right.include(context, includeChildrenRecursively); includeLoopBody(context, body, includeChildrenRecursively); } initialise() { this.left.setAssignedValue(UNKNOWN_EXPRESSION); } render(code, options) { this.left.render(code, options, NO_SEMICOLON); this.right.render(code, options, NO_SEMICOLON); // handle no space between "of" and the right side if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) { code.prependLeft(this.right.start, ' '); } this.body.render(code, options); } applyDeoptimizations() { this.deoptimized = true; this.left.deoptimizePath(EMPTY_PATH); this.right.deoptimizePath(UNKNOWN_PATH); this.context.requestTreeshakingPass(); } } class ForStatement extends NodeBase$2 { createScope(parentScope) { this.scope = new BlockScope(parentScope); } hasEffects(context) { if (this.init?.hasEffects(context) || this.test?.hasEffects(context) || this.update?.hasEffects(context)) { return true; } return hasLoopBodyEffects(context, this.body); } include(context, includeChildrenRecursively) { this.included = true; this.init?.include(context, includeChildrenRecursively, { asSingleStatement: true }); this.test?.include(context, includeChildrenRecursively); this.update?.include(context, includeChildrenRecursively); includeLoopBody(context, this.body, includeChildrenRecursively); } render(code, options) { this.init?.render(code, options, NO_SEMICOLON); this.test?.render(code, options, NO_SEMICOLON); this.update?.render(code, options, NO_SEMICOLON); this.body.render(code, options); } } class FunctionExpression extends FunctionNode { render(code, options, { renderedSurroundingElement } = BLANK) { super.render(code, options); if (renderedSurroundingElement === ExpressionStatement$1) { code.appendRight(this.start, '('); code.prependLeft(this.end, ')'); } } } class TrackingScope extends BlockScope { constructor() { super(...arguments); this.hoistedDeclarations = []; } addDeclaration(identifier, context, init, isHoisted) { this.hoistedDeclarations.push(identifier); return super.addDeclaration(identifier, context, init, isHoisted); } } const unset = Symbol('unset'); class IfStatement extends NodeBase$2 { constructor() { super(...arguments); this.testValue = unset; } deoptimizeCache() { this.testValue = UnknownValue; } hasEffects(context) { if (this.test.hasEffects(context)) { return true; } const testValue = this.getTestValue(); if (typeof testValue === 'symbol') { const { brokenFlow } = context; if (this.consequent.hasEffects(context)) return true; // eslint-disable-next-line unicorn/consistent-destructuring const consequentBrokenFlow = context.brokenFlow; context.brokenFlow = brokenFlow; if (this.alternate === null) return false; if (this.alternate.hasEffects(context)) return true; // eslint-disable-next-line unicorn/consistent-destructuring context.brokenFlow = context.brokenFlow && consequentBrokenFlow; return false; } return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context); } include(context, includeChildrenRecursively) { this.included = true; if (includeChildrenRecursively) { this.includeRecursively(includeChildrenRecursively, context); } else { const testValue = this.getTestValue(); if (typeof testValue === 'symbol') { this.includeUnknownTest(context); } else { this.includeKnownTest(context, testValue); } } } parseNode(esTreeNode) { this.consequentScope = new TrackingScope(this.scope); this.consequent = new (this.context.getNodeConstructor(esTreeNode.consequent.type))(esTreeNode.consequent, this, this.consequentScope); if (esTreeNode.alternate) { this.alternateScope = new TrackingScope(this.scope); this.alternate = new (this.context.getNodeConstructor(esTreeNode.alternate.type))(esTreeNode.alternate, this, this.alternateScope); } super.parseNode(esTreeNode); } render(code, options) { const { snippets: { getPropertyAccess } } = options; // Note that unknown test values are always included const testValue = this.getTestValue(); const hoistedDeclarations = []; const includesIfElse = this.test.included; const noTreeshake = !this.context.options.treeshake; if (includesIfElse) { this.test.render(code, options); } else { code.remove(this.start, this.consequent.start); } if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) { this.consequent.render(code, options); } else { code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : ''); hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations); } if (this.alternate) { if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) { if (includesIfElse) { if (code.original.charCodeAt(this.alternate.start - 1) === 101) { code.prependLeft(this.alternate.start, ' '); } } else { code.remove(this.consequent.end, this.alternate.start); } this.alternate.render(code, options); } else { if (includesIfElse && this.shouldKeepAlternateBranch()) { code.overwrite(this.alternate.start, this.end, ';'); } else { code.remove(this.consequent.end, this.end); } hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations); } } this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess); } applyDeoptimizations() { } getTestValue() { if (this.testValue === unset) { return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)); } return this.testValue; } includeKnownTest(context, testValue) { if (this.test.shouldBeIncluded(context)) { this.test.include(context, false); } if (testValue && this.consequent.shouldBeIncluded(context)) { this.consequent.include(context, false, { asSingleStatement: true }); } if (!testValue && this.alternate?.shouldBeIncluded(context)) { this.alternate.include(context, false, { asSingleStatement: true }); } } includeRecursively(includeChildrenRecursively, context) { this.test.include(context, includeChildrenRecursively); this.consequent.include(context, includeChildrenRecursively); this.alternate?.include(context, includeChildrenRecursively); } includeUnknownTest(context) { this.test.include(context, false); const { brokenFlow } = context; let consequentBrokenFlow = false; if (this.consequent.shouldBeIncluded(context)) { this.consequent.include(context, false, { asSingleStatement: true }); // eslint-disable-next-line unicorn/consistent-destructuring consequentBrokenFlow = context.brokenFlow; context.brokenFlow = brokenFlow; } if (this.alternate?.shouldBeIncluded(context)) { this.alternate.include(context, false, { asSingleStatement: true }); // eslint-disable-next-line unicorn/consistent-destructuring context.brokenFlow = context.brokenFlow && consequentBrokenFlow; } } renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) { const hoistedVariables = [ ...new Set(hoistedDeclarations.map(identifier => { const variable = identifier.variable; return variable.included ? variable.getName(getPropertyAccess) : ''; })) ] .filter(Boolean) .join(', '); if (hoistedVariables) { const parentType = this.parent.type; const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1; code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `); if (needsBraces) { code.appendLeft(this.end, ` }`); } } } shouldKeepAlternateBranch() { let currentParent = this.parent; do { if (currentParent instanceof IfStatement && currentParent.alternate) { return true; } if (currentParent instanceof BlockStatement) { return false; } currentParent = currentParent.parent; } while (currentParent); return false; } } class ImportAttribute extends NodeBase$2 { } class ImportDeclaration extends NodeBase$2 { // Do not bind specifiers or assertions bind() { } hasEffects() { return false; } initialise() { this.context.addImport(this); } render(code, _options, nodeRenderOptions) { code.remove(nodeRenderOptions.start, nodeRenderOptions.end); } applyDeoptimizations() { } } ImportDeclaration.prototype.needsBoundaries = true; class ImportDefaultSpecifier extends NodeBase$2 { applyDeoptimizations() { } } const INTEROP_DEFAULT_VARIABLE = '_interopDefault'; const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat'; const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace'; const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat'; const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault'; const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly'; const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces'; const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript'; const defaultInteropHelpersByInteropType = { auto: INTEROP_DEFAULT_VARIABLE, compat: INTEROP_DEFAULT_COMPAT_VARIABLE, default: null, defaultOnly: null, esModule: null }; const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' || (externalLiveBindings && (interopType === 'auto' || interopType === 'compat')); const namespaceInteropHelpersByInteropType = { auto: INTEROP_NAMESPACE_VARIABLE, compat: INTEROP_NAMESPACE_COMPAT_VARIABLE, default: INTEROP_NAMESPACE_DEFAULT_VARIABLE, defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, esModule: null }; const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings); const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, namespaceToStringTag) => { const usedHelpers = new Set(additionalHelpers); for (const variable of HELPER_NAMES) { if (accessedGlobals.has(variable)) { usedHelpers.add(variable); } } return HELPER_NAMES.map(variable => usedHelpers.has(variable) ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) : '').join(''); }; const HELPER_GENERATORS = { [DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) { return `var${_}${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof${_}document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`; }, [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) { const { _, getDirectReturnFunction, n } = snippets; const [left, right] = getDirectReturnFunction(['e'], { functionReturn: true, lineBreakIndent: null, name: INTEROP_DEFAULT_COMPAT_VARIABLE }); return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` + `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`); }, [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) { const { _, getDirectReturnFunction, n } = snippets; const [left, right] = getDirectReturnFunction(['e'], { functionReturn: true, lineBreakIndent: null, name: INTEROP_DEFAULT_VARIABLE }); return (`${left}e${_}&&${_}e.__esModule${_}?${_}` + `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`); }, [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) { const { _, getDirectReturnFunction, n } = snippets; if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) { const [left, right] = getDirectReturnFunction(['e'], { functionReturn: true, lineBreakIndent: null, name: INTEROP_NAMESPACE_COMPAT_VARIABLE }); return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`; } return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` + `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` + createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) + `}${n}${n}`); }, [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, namespaceToStringTag) { const { getDirectReturnFunction, getObject, n } = snippets; const [left, right] = getDirectReturnFunction(['e'], { functionReturn: true, lineBreakIndent: null, name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE }); return `${left}${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, getObject([ ['__proto__', 'null'], ['default', 'e'] ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`; }, [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) { const { _, n } = snippets; return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` + createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) + `}${n}${n}`); }, [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) { const { _, getDirectReturnFunction, n } = snippets; if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) { const [left, right] = getDirectReturnFunction(['e'], { functionReturn: true, lineBreakIndent: null, name: INTEROP_NAMESPACE_VARIABLE }); return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`; } return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` + `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` + createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) + `}${n}${n}`); }, [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) { const { _, cnst, n } = snippets; const useForEach = cnst === 'var' && liveBindings; return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` + `${t}${loopOverNamespaces(`{${n}` + `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` + (liveBindings ? useForEach ? copyOwnPropertyLiveBinding : copyPropertyLiveBinding : copyPropertyStatic)(t, t + t + t + t, snippets) + `${t}${t}${t}}${n}` + `${t}${t}}`, useForEach, t, snippets)}${n}` + `${t}return ${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, 'n', snippets))};${n}` + `}${n}${n}`); } }; const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`; const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`; const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`; const createNamespaceObject = (t, index, snippets, liveBindings, freeze, namespaceToStringTag) => { const { _, cnst, getObject, getPropertyAccess, n, s } = snippets; const copyProperty = `{${n}` + (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) + `${index}${t}}`; return (`${index}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}` : ''});${n}` + `${index}if${_}(e)${_}{${n}` + `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` + `${index}}${n}` + `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` + `${index}return ${getFrozen(freeze, 'n')}${s}${n}`); }; const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable ? `for${_}(${cnst} k in e)${_}${body}` : `Object.keys(e).forEach(${getFunctionIntro(['k'], { isAsync: false, name: null })}${body})${s}`; const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => { if (useForEach) { const [left, right] = getDirectReturnFunction(['e'], { functionReturn: false, lineBreakIndent: { base: t, t }, name: null }); return (`m.forEach(${left}` + `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], { isAsync: false, name: null })}${body})${right});`); } return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` + `${t}${t}${cnst} e${_}=${_}m[i];${n}` + `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`); }; const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => { const { _, n } = snippets; return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` + copyOwnPropertyLiveBinding(t, index + t, snippets) + `${index}}${n}`); }; const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => { const [left, right] = getDirectReturnFunction([], { functionReturn: true, lineBreakIndent: null, name: null }); return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` + `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` + `${index}${t}enumerable:${_}true,${n}` + `${index}${t}get:${_}${left}e[k]${right}${n}` + `${index}});${n}`); }; const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => { const [left, right] = getDirectReturnFunction([], { functionReturn: true, lineBreakIndent: null, name: null }); return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` + `${index}if${_}(d)${_}{${n}` + `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` + `${index}${t}${t}enumerable:${_}true,${n}` + `${index}${t}${t}get:${_}${left}e[k]${right}${n}` + `${index}${t}});${n}` + `${index}}${n}`); }; const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`; const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment; const getWithToStringTag = (namespaceToStringTag, fragment, { _, getObject }) => namespaceToStringTag ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})` : fragment; const HELPER_NAMES = Object.keys(HELPER_GENERATORS); function getToStringTagValue(getObject) { return getObject([['value', "'Module'"]], { lineBreakIndent: null }); } function isReassignedExportsMember(variable, exportNamesByVariable) { return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned); } class VariableDeclarator extends NodeBase$2 { declareDeclarator(kind) { this.id.declare(kind, this.init || UNDEFINED_EXPRESSION); } deoptimizePath(path) { this.id.deoptimizePath(path); } hasEffects(context) { if (!this.deoptimized) this.applyDeoptimizations(); const initEffect = this.init?.hasEffects(context); this.id.markDeclarationReached(); return initEffect || this.id.hasEffects(context); } include(context, includeChildrenRecursively) { const { deoptimized, id, init } = this; if (!deoptimized) this.applyDeoptimizations(); this.included = true; init?.include(context, includeChildrenRecursively); id.markDeclarationReached(); if (includeChildrenRecursively || id.shouldBeIncluded(context)) { id.include(context, includeChildrenRecursively); } } render(code, options) { const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options; const { end, id, init, start } = this; const renderId = id.included; if (renderId) { id.render(code, options); } else { const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end); code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1)); } if (init) { if (id instanceof Identifier && init instanceof ClassExpression && !init.id) { const renderedVariable = id.variable.getName(getPropertyAccess); if (renderedVariable !== id.name) { code.appendLeft(init.start + 5, ` ${id.name}`); } } init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 }); } else if (id instanceof Identifier && isReassignedExportsMember(id.variable, exportNamesByVariable)) { code.appendLeft(end, `${_}=${_}void 0`); } } applyDeoptimizations() { this.deoptimized = true; const { id, init } = this; if (init && id instanceof Identifier && init instanceof ClassExpression && !init.id) { const { name, variable } = id; for (const accessedVariable of init.scope.accessedOutsideVariables.values()) { if (accessedVariable !== variable) { accessedVariable.forbidName(name); } } } } } // TODO once ImportExpression follows official ESTree specs with "null" as // default, keys.ts should be updated class ImportExpression extends NodeBase$2 { constructor() { super(...arguments); this.inlineNamespace = null; this.assertions = null; this.mechanism = null; this.namespaceExportName = undefined; this.resolution = null; this.resolutionString = null; } // Do not bind assertions bind() { this.source.bind(); } /** * Get imported variables for deterministic usage, valid cases are: * * - `const { foo } = await import('bar')`. * - `(await import('bar')).foo` * - `import('bar').then(({ foo }) => {})` * * Returns empty array if it's side-effect only import. * Returns undefined if it's not fully deterministic. */ getDeterministicImportedNames() { const parent1 = this.parent; // Side-effect only: import('bar') if (parent1 instanceof ExpressionStatement) { return EMPTY_ARRAY; } if (parent1 instanceof AwaitExpression) { const parent2 = parent1.parent; // Side-effect only: await import('bar') if (parent2 instanceof ExpressionStatement) { return EMPTY_ARRAY; } // Case 1: const { foo } = await import('bar') if (parent2 instanceof VariableDeclarator) { const declaration = parent2.id; return declaration instanceof ObjectPattern ? getDeterministicObjectDestructure(declaration) : undefined; } // Case 2: (await import('bar')).foo if (parent2 instanceof MemberExpression) { const id = parent2.property; if (!parent2.computed && id instanceof Identifier) { return [id.name]; } } return; } // Case 3: import('bar').then(({ foo }) => {}) if (parent1 instanceof MemberExpression) { const callExpression = parent1.parent; const property = parent1.property; if (!(callExpression instanceof CallExpression) || !(property instanceof Identifier)) { return; } const memberName = property.name; // side-effect only, when only chaining .catch or .finally if (callExpression.parent instanceof ExpressionStatement && ['catch', 'finally'].includes(memberName)) { return EMPTY_ARRAY; } if (memberName !== 'then') return; // Side-effect only: import('bar').then() if (callExpression.arguments.length === 0) { return EMPTY_ARRAY; } const argument = callExpression.arguments[0]; if (callExpression.arguments.length !== 1 || !(argument instanceof ArrowFunctionExpression || argument instanceof FunctionExpression)) { return; } // Side-effect only: import('bar').then(() => {}) if (argument.params.length === 0) { return EMPTY_ARRAY; } const declaration = argument.params[0]; if (argument.params.length === 1 && declaration instanceof ObjectPattern) { return getDeterministicObjectDestructure(declaration); } return; } } hasEffects() { return true; } include(context, includeChildrenRecursively) { if (!this.included) { this.included = true; this.context.includeDynamicImport(this); this.scope.addAccessedDynamicImport(this); } this.source.include(context, includeChildrenRecursively); } initialise() { this.context.addDynamicImport(this); } parseNode(esTreeNode) { // Keep the source AST to be used by renderDynamicImport super.parseNode(esTreeNode, ['source']); } render(code, options) { const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess } } = options; if (this.inlineNamespace) { const [left, right] = getDirectReturnFunction([], { functionReturn: true, lineBreakIndent: null, name: null }); code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`); return; } if (this.mechanism) { code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left); code.overwrite(this.end - 1, this.end, this.mechanism.right); } if (this.resolutionString) { code.overwrite(this.source.start, this.source.end, this.resolutionString); if (this.namespaceExportName) { const [left, right] = getDirectReturnFunction(['n'], { functionReturn: true, lineBreakIndent: null, name: null }); code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`); } } else { this.source.render(code, options); } if (this.assertions !== true) { if (this.arguments) { code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true }); } if (this.assertions) { code.appendLeft(this.end - 1, `,${_}${getObject([['assert', this.assertions]], { lineBreakIndent: null })}`); } } } setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, assertions) { const { format } = options; this.inlineNamespace = null; this.resolution = resolution; this.resolutionString = resolutionString; this.namespaceExportName = namespaceExportName; this.assertions = assertions; const accessedGlobals = [...(accessedImportGlobals[format] || [])]; let helper; ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver)); if (helper) { accessedGlobals.push(helper); } if (accessedGlobals.length > 0) { this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope); } } setInternalResolution(inlineNamespace) { this.inlineNamespace = inlineNamespace; } applyDeoptimizations() { } getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportFunction, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) { const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [ { customResolution: typeof this.resolution === 'string' ? this.resolution : null, format, moduleId: this.context.module.id, targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null } ]); if (mechanism) { return { helper: null, mechanism }; } const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string'; switch (format) { case 'cjs': { if (dynamicImportInCjs && (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) { return { helper: null, mechanism: null }; } const helper = getInteropHelper(resolution, exportMode, interop); let left = `require(`; let right = `)`; if (helper) { left = `/*#__PURE__*/${helper}(${left}`; right += ')'; } const [functionLeft, functionRight] = getDirectReturnFunction([], { functionReturn: true, lineBreakIndent: null, name: null }); left = `Promise.resolve().then(${functionLeft}${left}`; right += `${functionRight})`; if (!arrowFunctions && hasDynamicTarget) { left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, { needsArrowReturnParens: false, needsWrappedFunction: true }); right = ')'; } return { helper, mechanism: { left, right } }; } case 'amd': { const resolve = compact ? 'c' : 'resolve'; const reject = compact ? 'e' : 'reject'; const helper = getInteropHelper(resolution, exportMode, interop); const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], { functionReturn: false, lineBreakIndent: null, name: null }); const resolveNamespace = helper ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}` : resolve; const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], { functionReturn: false, lineBreakIndent: null, name: null }); let left = `new Promise(${handlerLeft}require([`; let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`; if (!arrowFunctions && hasDynamicTarget) { left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, { needsArrowReturnParens: false, needsWrappedFunction: true }); right = ')'; } return { helper, mechanism: { left, right } }; } case 'system': { return { helper: null, mechanism: { left: 'module.import(', right: ')' } }; } case 'es': { if (dynamicImportFunction) { return { helper: null, mechanism: { left: `${dynamicImportFunction}(`, right: ')' } }; } } } return { helper: null, mechanism: null }; } } function getInteropHelper(resolution, exportMode, interop) { return exportMode === 'external' ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)] : exportMode === 'default' ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE : null; } const accessedImportGlobals = { amd: ['require'], cjs: ['require'], system: ['module'] }; function getDeterministicObjectDestructure(objectPattern) { const variables = []; for (const property of objectPattern.properties) { if (property.type === 'RestElement' || property.computed || property.key.type !== 'Identifier') return; variables.push(property.key.name); } return variables; } class ImportNamespaceSpecifier extends NodeBase$2 { applyDeoptimizations() { } } class ImportSpecifier extends NodeBase$2 { applyDeoptimizations() { } } class LabeledStatement extends NodeBase$2 { hasEffects(context) { const brokenFlow = context.brokenFlow; context.ignore.labels.add(this.label.name); if (this.body.hasEffects(context)) return true; context.ignore.labels.delete(this.label.name); if (context.includedLabels.has(this.label.name)) { context.includedLabels.delete(this.label.name); context.brokenFlow = brokenFlow; } return false; } include(context, includeChildrenRecursively) { this.included = true; const brokenFlow = context.brokenFlow; this.body.include(context, includeChildrenRecursively); if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) { this.label.include(); context.includedLabels.delete(this.label.name); context.brokenFlow = brokenFlow; } } render(code, options) { if (this.label.included) { this.label.render(code, options); } else { code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1)); } this.body.render(code, options); } } class LogicalExpression extends NodeBase$2 { constructor() { super(...arguments); // We collect deoptimization information if usedBranch !== null this.expressionsToBeDeoptimized = []; this.isBranchResolutionAnalysed = false; this.usedBranch = null; } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } deoptimizeCache() { if (this.usedBranch) { const unusedBranch = this.usedBranch === this.left ? this.right : this.left; this.usedBranch = null; unusedBranch.deoptimizePath(UNKNOWN_PATH); const { context, expressionsToBeDeoptimized } = this; this.expressionsToBeDeoptimized = EMPTY_ARRAY; for (const expression of expressionsToBeDeoptimized) { expression.deoptimizeCache(); } // Request another pass because we need to ensure "include" runs again if // it is rendered context.requestTreeshakingPass(); } } deoptimizePath(path) { const usedBranch = this.getUsedBranch(); if (usedBranch) { usedBranch.deoptimizePath(path); } else { this.left.deoptimizePath(path); this.right.deoptimizePath(path); } } getLiteralValueAtPath(path, recursionTracker, origin) { const usedBranch = this.getUsedBranch(); if (!usedBranch) return UnknownValue; this.expressionsToBeDeoptimized.push(origin); return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin); } getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) { const usedBranch = this.getUsedBranch(); if (!usedBranch) return [ new MultiExpression([ this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0], this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0] ]), false ]; this.expressionsToBeDeoptimized.push(origin); return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin); } hasEffects(context) { if (this.left.hasEffects(context)) { return true; } if (this.getUsedBranch() !== this.left) { return this.right.hasEffects(context); } return false; } hasEffectsOnInteractionAtPath(path, interaction, context) { const usedBranch = this.getUsedBranch(); if (!usedBranch) { return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) || this.right.hasEffectsOnInteractionAtPath(path, interaction, context)); } return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context); } include(context, includeChildrenRecursively) { this.included = true; const usedBranch = this.getUsedBranch(); if (includeChildrenRecursively || (usedBranch === this.right && this.left.shouldBeIncluded(context)) || !usedBranch) { this.left.include(context, includeChildrenRecursively); this.right.include(context, includeChildrenRecursively); } else { usedBranch.include(context, includeChildrenRecursively); } } render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) { if (!this.left.included || !this.right.included) { const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end); if (this.right.included) { const removePos = findNonWhiteSpace(code.original, operatorPos + 2); code.remove(this.start, removePos); if (preventASI) { removeLineBreaks(code, removePos, this.right.start); } } else { code.remove(operatorPos, this.end); } removeAnnotations(this, code); this.getUsedBranch().render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType: renderedParentType || this.parent.type, renderedSurroundingElement: renderedSurroundingElement || this.parent.type }); } else { this.left.render(code, options, { preventASI, renderedSurroundingElement }); this.right.render(code, options); } } getUsedBranch() { if (!this.isBranchResolutionAnalysed) { this.isBranchResolutionAnalysed = true; const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this); if (typeof leftValue === 'symbol') { return null; } else { this.usedBranch = (this.operator === '||' && leftValue) || (this.operator === '&&' && !leftValue) || (this.operator === '??' && leftValue != null) ? this.left : this.right; } } return this.usedBranch; } } const FILE_PREFIX = 'ROLLUP_FILE_URL_'; const IMPORT = 'import'; class MetaProperty extends NodeBase$2 { constructor() { super(...arguments); this.metaProperty = null; this.preliminaryChunkId = null; this.referenceId = null; } getReferencedFileName(outputPluginDriver) { const { meta: { name }, metaProperty } = this; if (name === IMPORT && metaProperty?.startsWith(FILE_PREFIX)) { return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length)); } return null; } hasEffects() { return false; } hasEffectsOnInteractionAtPath(path, { type }) { return path.length > 1 || type !== INTERACTION_ACCESSED; } include() { if (!this.included) { this.included = true; if (this.meta.name === IMPORT) { this.context.addImportMeta(this); const parent = this.parent; const metaProperty = (this.metaProperty = parent instanceof MemberExpression && typeof parent.propertyKey === 'string' ? parent.propertyKey : null); if (metaProperty?.startsWith(FILE_PREFIX)) { this.referenceId = metaProperty.slice(FILE_PREFIX.length); } } } } render(code, renderOptions) { const { format, pluginDriver, snippets } = renderOptions; const { context: { module }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this; const { id: moduleId } = module; if (name !== IMPORT) return; const chunkId = preliminaryChunkId; if (referenceId) { const fileName = pluginDriver.getFileName(referenceId); const relativePath = normalize$1(relative$2(dirname$1(chunkId), fileName)); const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [ { chunkId, fileName, format, moduleId, referenceId, relativePath } ]) || relativeUrlMechanisms$1[format](relativePath); code.overwrite(parent.start, parent.end, replacement, { contentOnly: true }); return; } let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [ metaProperty, { chunkId, format, moduleId } ]); if (!replacement) { replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets }); renderOptions.accessedDocumentCurrentScript || (renderOptions.accessedDocumentCurrentScript = formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined'); } if (typeof replacement === 'string') { if (parent instanceof MemberExpression) { code.overwrite(parent.start, parent.end, replacement, { contentOnly: true }); } else { code.overwrite(start, end, replacement, { contentOnly: true }); } } } setResolution(format, accessedGlobalsByScope, preliminaryChunkId) { this.preliminaryChunkId = preliminaryChunkId; const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) ? accessedFileUrlGlobals : accessedMetaUrlGlobals)[format]; if (accessedGlobals.length > 0) { this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope); } } } const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd']; const accessedMetaUrlGlobals = { amd: ['document', 'module', 'URL'], cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT], es: [], iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT], system: ['module'], umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT] }; const accessedFileUrlGlobals = { amd: ['document', 'require', 'URL'], cjs: ['document', 'require', 'URL'], es: [], iife: ['document', 'URL'], system: ['module', 'URL'], umd: ['document', 'require', 'URL'] }; const getResolveUrl$1 = (path, URL = 'URL') => `new ${URL}(${path}).href`; const getRelativeUrlFromDocument$1 = (relativePath, umd = false) => getResolveUrl$1(`'${escapeId$1(relativePath)}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`); const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => { const urlMechanism = getUrl(chunkId); return property === null ? `({ url: ${urlMechanism} })` : property === 'url' ? urlMechanism : 'undefined'; }; const getFileUrlFromFullPath$1 = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`; const getFileUrlFromRelativePath$1 = (path) => getFileUrlFromFullPath$1(`__dirname + '/${path}'`); const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(${DOCUMENT_CURRENT_SCRIPT} && ${DOCUMENT_CURRENT_SCRIPT}.src || new URL('${escapeId$1(chunkId)}', document.baseURI).href)`; const relativeUrlMechanisms$1 = { amd: relativePath => { if (relativePath[0] !== '.') relativePath = './' + relativePath; return getResolveUrl$1(`require.toUrl('${relativePath}'), document.baseURI`); }, cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath$1(relativePath)} : ${getRelativeUrlFromDocument$1(relativePath)})`, es: relativePath => getResolveUrl$1(`'${relativePath}', import.meta.url`), iife: relativePath => getRelativeUrlFromDocument$1(relativePath), system: relativePath => getResolveUrl$1(`'${relativePath}', module.meta.url`), umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath$1(relativePath)} : ${getRelativeUrlFromDocument$1(relativePath, true)})` }; const importMetaMechanisms = { amd: getGenericImportMetaMechanism(() => getResolveUrl$1(`module.uri, document.baseURI`)), cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath$1('__filename')} : ${getUrlFromDocument(chunkId)})`), iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)), system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`, umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath$1('__filename')} : ${getUrlFromDocument(chunkId, true)})`) }; class NewExpression extends NodeBase$2 { hasEffects(context) { try { for (const argument of this.arguments) { if (argument.hasEffects(context)) return true; } if (this.annotationPure) { return false; } return (this.callee.hasEffects(context) || this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context)); } finally { if (!this.deoptimized) this.applyDeoptimizations(); } } hasEffectsOnInteractionAtPath(path, { type }) { return path.length > 0 || type !== INTERACTION_ACCESSED; } include(context, includeChildrenRecursively) { if (!this.deoptimized) this.applyDeoptimizations(); if (includeChildrenRecursively) { super.include(context, includeChildrenRecursively); } else { this.included = true; this.callee.include(context, false); } this.callee.includeCallArguments(context, this.arguments); } initialise() { this.interaction = { args: [null, ...this.arguments], type: INTERACTION_CALLED, withNew: true }; } render(code, options) { this.callee.render(code, options); renderCallArguments(code, options, this); } applyDeoptimizations() { this.deoptimized = true; this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER); this.context.requestTreeshakingPass(); } } class ObjectExpression extends NodeBase$2 { constructor() { super(...arguments); this.objectEntity = null; } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } deoptimizeCache() { this.getObjectEntity().deoptimizeAllProperties(); } deoptimizePath(path) { this.getObjectEntity().deoptimizePath(path); } getLiteralValueAtPath(path, recursionTracker, origin) { return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin); } getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) { return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin); } hasEffectsOnInteractionAtPath(path, interaction, context) { return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context); } render(code, options, { renderedSurroundingElement } = BLANK) { super.render(code, options); if (renderedSurroundingElement === ExpressionStatement$1 || renderedSurroundingElement === ArrowFunctionExpression$1) { code.appendRight(this.start, '('); code.prependLeft(this.end, ')'); } } applyDeoptimizations() { } getObjectEntity() { if (this.objectEntity !== null) { return this.objectEntity; } let prototype = OBJECT_PROTOTYPE; const properties = []; for (const property of this.properties) { if (property instanceof SpreadElement) { properties.push({ key: UnknownKey, kind: 'init', property }); continue; } let key; if (property.computed) { const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this); if (typeof keyValue === 'symbol') { properties.push({ key: UnknownKey, kind: property.kind, property }); continue; } else { key = String(keyValue); } } else { key = property.key instanceof Identifier ? property.key.name : String(property.key.value); if (key === '__proto__' && property.kind === 'init') { prototype = property.value instanceof Literal && property.value.value === null ? null : property.value; continue; } } properties.push({ key, kind: property.kind, property }); } return (this.objectEntity = new ObjectEntity(properties, prototype)); } } class PrivateIdentifier extends NodeBase$2 { } class Program extends NodeBase$2 { constructor() { super(...arguments); this.hasCachedEffect = null; this.hasLoggedEffect = false; } hasCachedEffects() { if (!this.included) { return false; } return this.hasCachedEffect === null ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext())) : this.hasCachedEffect; } hasEffects(context) { for (const node of this.body) { if (node.hasEffects(context)) { if (this.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) { this.hasLoggedEffect = true; const { code, log, module } = this.context; log(LOGLEVEL_INFO, logFirstSideEffect(code, module.id, locate(code, node.start, { offsetLine: 1 })), node.start); } return (this.hasCachedEffect = true); } } return false; } include(context, includeChildrenRecursively) { this.included = true; for (const node of this.body) { if (includeChildrenRecursively || node.shouldBeIncluded(context)) { node.include(context, includeChildrenRecursively); } } } render(code, options) { let start = this.start; if (code.original.startsWith('#!')) { start = Math.min(code.original.indexOf('\n') + 1, this.end); code.remove(0, start); } if (this.body.length > 0) { // Keep all consecutive lines that start with a comment while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) { const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start)); if (firstLineBreak[0] === -1) { break; } start += firstLineBreak[1]; } renderStatementList(this.body, code, start, this.end, options); } else { super.render(code, options); } } applyDeoptimizations() { } } class Property extends MethodBase { constructor() { super(...arguments); this.declarationInit = null; } declare(kind, init) { this.declarationInit = init; return this.value.declare(kind, UNKNOWN_EXPRESSION); } hasEffects(context) { if (!this.deoptimized) this.applyDeoptimizations(); const propertyReadSideEffects = this.context.options.treeshake .propertyReadSideEffects; return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') || this.key.hasEffects(context) || this.value.hasEffects(context)); } markDeclarationReached() { this.value.markDeclarationReached(); } render(code, options) { if (!this.shorthand) { this.key.render(code, options); } this.value.render(code, options, { isShorthandProperty: this.shorthand }); } applyDeoptimizations() { this.deoptimized = true; if (this.declarationInit !== null) { this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]); this.context.requestTreeshakingPass(); } } } class PropertyDefinition extends NodeBase$2 { deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } deoptimizePath(path) { this.value?.deoptimizePath(path); } getLiteralValueAtPath(path, recursionTracker, origin) { return this.value ? this.value.getLiteralValueAtPath(path, recursionTracker, origin) : UnknownValue; } getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) { return this.value ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) : UNKNOWN_RETURN_EXPRESSION; } hasEffects(context) { return this.key.hasEffects(context) || (this.static && !!this.value?.hasEffects(context)); } hasEffectsOnInteractionAtPath(path, interaction, context) { return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context); } applyDeoptimizations() { } } class ReturnStatement extends NodeBase$2 { hasEffects(context) { if (!context.ignore.returnYield || this.argument?.hasEffects(context)) return true; context.brokenFlow = true; return false; } include(context, includeChildrenRecursively) { this.included = true; this.argument?.include(context, includeChildrenRecursively); context.brokenFlow = true; } initialise() { this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION); } render(code, options) { if (this.argument) { this.argument.render(code, options, { preventASI: true }); if (this.argument.start === this.start + 6 /* 'return'.length */) { code.prependLeft(this.start + 6, ' '); } } } } class SequenceExpression extends NodeBase$2 { deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } deoptimizePath(path) { this.expressions[this.expressions.length - 1].deoptimizePath(path); } getLiteralValueAtPath(path, recursionTracker, origin) { return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin); } hasEffects(context) { for (const expression of this.expressions) { if (expression.hasEffects(context)) return true; } return false; } hasEffectsOnInteractionAtPath(path, interaction, context) { return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context); } include(context, includeChildrenRecursively) { this.included = true; const lastExpression = this.expressions[this.expressions.length - 1]; for (const expression of this.expressions) { if (includeChildrenRecursively || (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) || expression.shouldBeIncluded(context)) expression.include(context, includeChildrenRecursively); } } render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) { let includedNodes = 0; let lastSeparatorPos = null; const lastNode = this.expressions[this.expressions.length - 1]; for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) { if (!node.included) { treeshakeNode(node, code, start, end); continue; } includedNodes++; lastSeparatorPos = separator; if (includedNodes === 1 && preventASI) { removeLineBreaks(code, start, node.start); } if (includedNodes === 1) { const parentType = renderedParentType || this.parent.type; node.render(code, options, { isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode, renderedParentType: parentType, renderedSurroundingElement: parentType }); } else { node.render(code, options); } } if (lastSeparatorPos) { code.remove(lastSeparatorPos, this.end); } } } class StaticBlock extends NodeBase$2 { createScope(parentScope) { this.scope = new BlockScope(parentScope); } hasEffects(context) { for (const node of this.body) { if (node.hasEffects(context)) return true; } return false; } include(context, includeChildrenRecursively) { this.included = true; for (const node of this.body) { if (includeChildrenRecursively || node.shouldBeIncluded(context)) node.include(context, includeChildrenRecursively); } } render(code, options) { if (this.body.length > 0) { const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1; renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options); } else { super.render(code, options); } } } class Super extends NodeBase$2 { bind() { this.variable = this.scope.findVariable('this'); } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } deoptimizePath(path) { this.variable.deoptimizePath(path); } include() { if (!this.included) { this.included = true; this.context.includeVariableInModule(this.variable); } } } class SwitchCase extends NodeBase$2 { hasEffects(context) { if (this.test?.hasEffects(context)) return true; for (const node of this.consequent) { if (context.brokenFlow) break; if (node.hasEffects(context)) return true; } return false; } include(context, includeChildrenRecursively) { this.included = true; this.test?.include(context, includeChildrenRecursively); for (const node of this.consequent) { if (includeChildrenRecursively || node.shouldBeIncluded(context)) node.include(context, includeChildrenRecursively); } } render(code, options, nodeRenderOptions) { if (this.consequent.length > 0) { this.test && this.test.render(code, options); const testEnd = this.test ? this.test.end : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7; const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1; renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options); } else { super.render(code, options); } } } SwitchCase.prototype.needsBoundaries = true; class SwitchStatement extends NodeBase$2 { createScope(parentScope) { this.parentScope = parentScope; this.scope = new BlockScope(parentScope); } hasEffects(context) { if (this.discriminant.hasEffects(context)) return true; const { brokenFlow, hasBreak, ignore } = context; const { breaks } = ignore; ignore.breaks = true; context.hasBreak = false; let onlyHasBrokenFlow = true; for (const switchCase of this.cases) { if (switchCase.hasEffects(context)) return true; // eslint-disable-next-line unicorn/consistent-destructuring onlyHasBrokenFlow && (onlyHasBrokenFlow = context.brokenFlow && !context.hasBreak); context.hasBreak = false; context.brokenFlow = brokenFlow; } if (this.defaultCase !== null) { context.brokenFlow = onlyHasBrokenFlow; } ignore.breaks = breaks; context.hasBreak = hasBreak; return false; } include(context, includeChildrenRecursively) { this.included = true; this.discriminant.include(context, includeChildrenRecursively); const { brokenFlow, hasBreak } = context; context.hasBreak = false; let onlyHasBrokenFlow = true; let isCaseIncluded = includeChildrenRecursively || (this.defaultCase !== null && this.defaultCase < this.cases.length - 1); for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) { const switchCase = this.cases[caseIndex]; if (switchCase.included) { isCaseIncluded = true; } if (!isCaseIncluded) { const hasEffectsContext = createHasEffectsContext(); hasEffectsContext.ignore.breaks = true; isCaseIncluded = switchCase.hasEffects(hasEffectsContext); } if (isCaseIncluded) { switchCase.include(context, includeChildrenRecursively); // eslint-disable-next-line unicorn/consistent-destructuring onlyHasBrokenFlow && (onlyHasBrokenFlow = context.brokenFlow && !context.hasBreak); context.hasBreak = false; context.brokenFlow = brokenFlow; } else { onlyHasBrokenFlow = brokenFlow; } } if (isCaseIncluded && this.defaultCase !== null) { context.brokenFlow = onlyHasBrokenFlow; } context.hasBreak = hasBreak; } initialise() { for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) { if (this.cases[caseIndex].test === null) { this.defaultCase = caseIndex; return; } } this.defaultCase = null; } parseNode(esTreeNode) { this.discriminant = new (this.context.getNodeConstructor(esTreeNode.discriminant.type))(esTreeNode.discriminant, this, this.parentScope); super.parseNode(esTreeNode); } render(code, options) { this.discriminant.render(code, options); if (this.cases.length > 0) { renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options); } } } class TaggedTemplateExpression extends CallExpressionBase { bind() { super.bind(); if (this.tag.type === Identifier$1) { const name = this.tag.name; const variable = this.scope.findVariable(name); if (variable.isNamespace) { this.context.log(LOGLEVEL_WARN, logCannotCallNamespace(name), this.start); } } } hasEffects(context) { try { for (const argument of this.quasi.expressions) { if (argument.hasEffects(context)) return true; } return (this.tag.hasEffects(context) || this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context)); } finally { if (!this.deoptimized) this.applyDeoptimizations(); } } include(context, includeChildrenRecursively) { if (!this.deoptimized) this.applyDeoptimizations(); if (includeChildrenRecursively) { super.include(context, includeChildrenRecursively); } else { this.included = true; this.tag.include(context, includeChildrenRecursively); this.quasi.include(context, includeChildrenRecursively); } this.tag.includeCallArguments(context, this.args); const [returnExpression] = this.getReturnExpression(); if (!returnExpression.included) { returnExpression.include(context, false); } } initialise() { this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions]; this.interaction = { args: [ this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null, ...this.args ], type: INTERACTION_CALLED, withNew: false }; } render(code, options) { this.tag.render(code, options, { isCalleeOfRenderedParent: true }); this.quasi.render(code, options); } applyDeoptimizations() { this.deoptimized = true; this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER); this.context.requestTreeshakingPass(); } getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) { if (this.returnExpression === null) { this.returnExpression = UNKNOWN_RETURN_EXPRESSION; return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this)); } return this.returnExpression; } } class TemplateElement extends NodeBase$2 { // Do not try to bind value bind() { } hasEffects() { return false; } include() { this.included = true; } parseNode(esTreeNode) { this.value = esTreeNode.value; super.parseNode(esTreeNode); } render() { } } class TemplateLiteral extends NodeBase$2 { deoptimizeArgumentsOnInteractionAtPath() { } getLiteralValueAtPath(path) { if (path.length > 0 || this.quasis.length !== 1) { return UnknownValue; } return this.quasis[0].value.cooked; } getReturnExpressionWhenCalledAtPath(path) { if (path.length !== 1) { return UNKNOWN_RETURN_EXPRESSION; } return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]); } hasEffectsOnInteractionAtPath(path, interaction, context) { if (interaction.type === INTERACTION_ACCESSED) { return path.length > 1; } if (interaction.type === INTERACTION_CALLED && path.length === 1) { return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context); } return true; } render(code, options) { code.indentExclusionRanges.push([this.start, this.end]); super.render(code, options); } } class UndefinedVariable extends Variable { constructor() { super('undefined'); } getLiteralValueAtPath() { return undefined; } } class ExportDefaultVariable extends LocalVariable { constructor(name, exportDefaultDeclaration, context) { super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context); this.hasId = false; this.originalId = null; this.originalVariable = null; const declaration = exportDefaultDeclaration.declaration; if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) && declaration.id) { this.hasId = true; this.originalId = declaration.id; } else if (declaration instanceof Identifier) { this.originalId = declaration; } } addReference(identifier) { if (!this.hasId) { this.name = identifier.name; } } forbidName(name) { const original = this.getOriginalVariable(); if (original === this) { super.forbidName(name); } else { original.forbidName(name); } } getAssignedVariableName() { return (this.originalId && this.originalId.name) || null; } getBaseVariableName() { const original = this.getOriginalVariable(); return original === this ? super.getBaseVariableName() : original.getBaseVariableName(); } getDirectOriginalVariable() { return this.originalId && (this.hasId || !(this.originalId.isPossibleTDZ() || this.originalId.variable.isReassigned || this.originalId.variable instanceof UndefinedVariable || // this avoids a circular dependency 'syntheticNamespace' in this.originalId.variable)) ? this.originalId.variable : null; } getName(getPropertyAccess) { const original = this.getOriginalVariable(); return original === this ? super.getName(getPropertyAccess) : original.getName(getPropertyAccess); } getOriginalVariable() { if (this.originalVariable) return this.originalVariable; // eslint-disable-next-line @typescript-eslint/no-this-alias let original = this; let currentVariable; const checkedVariables = new Set(); do { checkedVariables.add(original); currentVariable = original; original = currentVariable.getDirectOriginalVariable(); } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original)); return (this.originalVariable = original || currentVariable); } } class ModuleScope extends ChildScope { constructor(parent, context) { super(parent); this.context = context; this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context)); } addExportDefaultDeclaration(name, exportDefaultDeclaration, context) { const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context); this.variables.set('default', variable); return variable; } addNamespaceMemberAccess() { } deconflict(format, exportNamesByVariable, accessedGlobalsByScope) { // all module level variables are already deconflicted when deconflicting the chunk for (const scope of this.children) scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope); } findLexicalBoundary() { return this; } findVariable(name) { const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name); if (knownVariable) { return knownVariable; } const variable = this.context.traceVariable(name) || this.parent.findVariable(name); if (variable instanceof GlobalVariable) { this.accessedOutsideVariables.set(name, variable); } return variable; } } class ThisExpression extends NodeBase$2 { bind() { this.variable = this.scope.findVariable('this'); } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker); } deoptimizePath(path) { this.variable.deoptimizePath(path); } hasEffectsOnInteractionAtPath(path, interaction, context) { if (path.length === 0) { return interaction.type !== INTERACTION_ACCESSED; } return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context); } include() { if (!this.included) { this.included = true; this.context.includeVariableInModule(this.variable); } } initialise() { this.alias = this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null; if (this.alias === 'undefined') { this.context.log(LOGLEVEL_WARN, logThisIsUndefined(), this.start); } } render(code) { if (this.alias !== null) { code.overwrite(this.start, this.end, this.alias, { contentOnly: false, storeName: true }); } } } class ThrowStatement extends NodeBase$2 { hasEffects() { return true; } include(context, includeChildrenRecursively) { this.included = true; this.argument.include(context, includeChildrenRecursively); context.brokenFlow = true; } render(code, options) { this.argument.render(code, options, { preventASI: true }); if (this.argument.start === this.start + 5 /* 'throw'.length */) { code.prependLeft(this.start + 5, ' '); } } } class TryStatement extends NodeBase$2 { constructor() { super(...arguments); this.directlyIncluded = false; this.includedLabelsAfterBlock = null; } hasEffects(context) { return ((this.context.options.treeshake.tryCatchDeoptimization ? this.block.body.length > 0 : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context)); } include(context, includeChildrenRecursively) { const tryCatchDeoptimization = this.context.options.treeshake ?.tryCatchDeoptimization; const { brokenFlow, includedLabels } = context; if (!this.directlyIncluded || !tryCatchDeoptimization) { this.included = true; this.directlyIncluded = true; this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively); if (includedLabels.size > 0) { this.includedLabelsAfterBlock = [...includedLabels]; } context.brokenFlow = brokenFlow; } else if (this.includedLabelsAfterBlock) { for (const label of this.includedLabelsAfterBlock) { includedLabels.add(label); } } if (this.handler !== null) { this.handler.include(context, includeChildrenRecursively); context.brokenFlow = brokenFlow; } this.finalizer?.include(context, includeChildrenRecursively); } } const unaryOperators = { '!': value => !value, '+': value => +value, '-': value => -value, delete: () => UnknownValue, typeof: value => typeof value, void: () => undefined, '~': value => ~value }; class UnaryExpression extends NodeBase$2 { getLiteralValueAtPath(path, recursionTracker, origin) { if (path.length > 0) return UnknownValue; const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin); if (typeof argumentValue === 'symbol') return UnknownValue; return unaryOperators[this.operator](argumentValue); } hasEffects(context) { if (!this.deoptimized) this.applyDeoptimizations(); if (this.operator === 'typeof' && this.argument instanceof Identifier) return false; return (this.argument.hasEffects(context) || (this.operator === 'delete' && this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context))); } hasEffectsOnInteractionAtPath(path, { type }) { return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1); } applyDeoptimizations() { this.deoptimized = true; if (this.operator === 'delete') { this.argument.deoptimizePath(EMPTY_PATH); this.context.requestTreeshakingPass(); } } } class UnknownNode extends NodeBase$2 { hasEffects() { return true; } include(context) { super.include(context, true); } } class UpdateExpression extends NodeBase$2 { hasEffects(context) { if (!this.deoptimized) this.applyDeoptimizations(); return this.argument.hasEffectsAsAssignmentTarget(context, true); } hasEffectsOnInteractionAtPath(path, { type }) { return path.length > 1 || type !== INTERACTION_ACCESSED; } include(context, includeChildrenRecursively) { if (!this.deoptimized) this.applyDeoptimizations(); this.included = true; this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true); } initialise() { this.argument.setAssignedValue(UNKNOWN_EXPRESSION); } render(code, options) { const { exportNamesByVariable, format, snippets: { _ } } = options; this.argument.render(code, options); if (format === 'system') { const variable = this.argument.variable; const exportNames = exportNamesByVariable.get(variable); if (exportNames) { if (this.prefix) { if (exportNames.length === 1) { renderSystemExportExpression(variable, this.start, this.end, code, options); } else { renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options); } } else { const operator = this.operator[0]; renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`); } } } } applyDeoptimizations() { this.deoptimized = true; this.argument.deoptimizePath(EMPTY_PATH); if (this.argument instanceof Identifier) { const variable = this.scope.findVariable(this.argument.name); variable.isReassigned = true; } this.context.requestTreeshakingPass(); } } function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) { for (const declarator of declarations) { if (!declarator.id.included) return false; if (declarator.id.type === Identifier$1) { if (exportNamesByVariable.has(declarator.id.variable)) return false; } else { const exportedVariables = []; declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable); if (exportedVariables.length > 0) return false; } } return true; } class VariableDeclaration extends NodeBase$2 { deoptimizePath() { for (const declarator of this.declarations) { declarator.deoptimizePath(EMPTY_PATH); } } hasEffectsOnInteractionAtPath() { return false; } include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) { this.included = true; for (const declarator of this.declarations) { if (includeChildrenRecursively || declarator.shouldBeIncluded(context)) declarator.include(context, includeChildrenRecursively); const { id, init } = declarator; if (asSingleStatement) { id.include(context, includeChildrenRecursively); } if (init && id.included && !init.included && (id instanceof ObjectPattern || id instanceof ArrayPattern)) { init.include(context, includeChildrenRecursively); } } } initialise() { for (const declarator of this.declarations) { declarator.declareDeclarator(this.kind); } } render(code, options, nodeRenderOptions = BLANK) { if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) { for (const declarator of this.declarations) { declarator.render(code, options); } if (!nodeRenderOptions.isNoStatement && code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) { code.appendLeft(this.end, ';'); } } else { this.renderReplacedDeclarations(code, options); } } applyDeoptimizations() { } renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) { if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) { code.remove(this.end - 1, this.end); } separatorString += ';'; if (lastSeparatorPos === null) { code.appendLeft(renderedContentEnd, separatorString); } else { if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ && (code.original.charCodeAt(this.end) === 10 /*"\n"*/ || code.original.charCodeAt(this.end) === 13) /*"\r"*/) { actualContentEnd--; if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) { actualContentEnd--; } } if (actualContentEnd === lastSeparatorPos + 1) { code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString); } else { code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString); code.remove(actualContentEnd, renderedContentEnd); } } if (systemPatternExports.length > 0) { code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`); } } renderReplacedDeclarations(code, options) { const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0)); let actualContentEnd, renderedContentEnd; renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length); let lastSeparatorPos = renderedContentEnd - 1; code.remove(this.start, lastSeparatorPos); let isInDeclaration = false; let hasRenderedContent = false; let separatorString = '', leadingString, nextSeparatorString; const aggregatedSystemExports = []; const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports); for (const { node, start, separator, contentEnd, end } of separatedNodes) { if (!node.included) { code.remove(start, end); continue; } node.render(code, options); leadingString = ''; nextSeparatorString = ''; if (!node.id.included || (node.id instanceof Identifier && isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) { if (hasRenderedContent) { separatorString += ';'; } isInDeclaration = false; } else { if (singleSystemExport && singleSystemExport === node.id.variable) { const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end); renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options); } if (isInDeclaration) { separatorString += ','; } else { if (hasRenderedContent) { separatorString += ';'; } leadingString += `${this.kind} `; isInDeclaration = true; } } if (renderedContentEnd === lastSeparatorPos + 1) { code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString); } else { code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString); code.appendLeft(renderedContentEnd, leadingString); } actualContentEnd = contentEnd; renderedContentEnd = end; hasRenderedContent = true; lastSeparatorPos = separator; separatorString = nextSeparatorString; } this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options); } } function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) { let singleSystemExport = null; if (options.format === 'system') { for (const { node } of separatedNodes) { if (node.id instanceof Identifier && node.init && aggregatedSystemExports.length === 0 && options.exportNamesByVariable.get(node.id.variable)?.length === 1) { singleSystemExport = node.id.variable; aggregatedSystemExports.push(singleSystemExport); } else { node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable); } } if (aggregatedSystemExports.length > 1) { singleSystemExport = null; } else if (singleSystemExport) { aggregatedSystemExports.length = 0; } } return singleSystemExport; } class WhileStatement extends NodeBase$2 { hasEffects(context) { if (this.test.hasEffects(context)) return true; return hasLoopBodyEffects(context, this.body); } include(context, includeChildrenRecursively) { this.included = true; this.test.include(context, includeChildrenRecursively); includeLoopBody(context, this.body, includeChildrenRecursively); } } class YieldExpression extends NodeBase$2 { hasEffects(context) { if (!this.deoptimized) this.applyDeoptimizations(); return !(context.ignore.returnYield && !this.argument?.hasEffects(context)); } render(code, options) { if (this.argument) { this.argument.render(code, options, { preventASI: true }); if (this.argument.start === this.start + 5 /* 'yield'.length */) { code.prependLeft(this.start + 5, ' '); } } } } const nodeConstructors = { ArrayExpression, ArrayPattern, ArrowFunctionExpression, AssignmentExpression, AssignmentPattern, AwaitExpression, BinaryExpression, BlockStatement, BreakStatement, CallExpression, CatchClause, ChainExpression, ClassBody, ClassDeclaration, ClassExpression, ConditionalExpression, ContinueStatement, DoWhileStatement, EmptyStatement, ExportAllDeclaration, ExportDefaultDeclaration, ExportNamedDeclaration, ExportSpecifier, ExpressionStatement, ForInStatement, ForOfStatement, ForStatement, FunctionDeclaration, FunctionExpression, Identifier, IfStatement, ImportAttribute, ImportDeclaration, ImportDefaultSpecifier, ImportExpression, ImportNamespaceSpecifier, ImportSpecifier, LabeledStatement, Literal, LogicalExpression, MemberExpression, MetaProperty, MethodDefinition, NewExpression, ObjectExpression, ObjectPattern, PrivateIdentifier, Program, Property, PropertyDefinition, RestElement, ReturnStatement, SequenceExpression, SpreadElement, StaticBlock, Super, SwitchCase, SwitchStatement, TaggedTemplateExpression, TemplateElement, TemplateLiteral, ThisExpression, ThrowStatement, TryStatement, UnaryExpression, UnknownNode, UpdateExpression, VariableDeclaration, VariableDeclarator, WhileStatement, YieldExpression }; const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim'; class ExportShimVariable extends Variable { constructor(module) { super(MISSING_EXPORT_SHIM_VARIABLE); this.module = module; } include() { super.include(); this.module.needsExportShim = true; } } class NamespaceVariable extends Variable { constructor(context) { super(context.getModuleName()); this.memberVariables = null; this.mergedNamespaces = []; this.referencedEarly = false; this.references = []; this.context = context; this.module = context.module; } addReference(identifier) { this.references.push(identifier); this.name = identifier.name; } deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) { if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) { const key = path[0]; if (typeof key === 'string') { this.getMemberVariables()[key]?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker); } else { deoptimizeInteraction(interaction); } } } deoptimizePath(path) { if (path.length > 1) { const key = path[0]; if (typeof key === 'string') { this.getMemberVariables()[key]?.deoptimizePath(path.slice(1)); } } } getLiteralValueAtPath(path) { if (path[0] === SymbolToStringTag) { return 'Module'; } return UnknownValue; } getMemberVariables() { if (this.memberVariables) { return this.memberVariables; } const memberVariables = Object.create(null); const sortedExports = [...this.context.getExports(), ...this.context.getReexports()].sort(); for (const name of sortedExports) { if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) { const exportedVariable = this.context.traceExport(name); if (exportedVariable) { memberVariables[name] = exportedVariable; } } } return (this.memberVariables = memberVariables); } hasEffectsOnInteractionAtPath(path, interaction, context) { const { type } = interaction; if (path.length === 0) { // This can only be a call anyway return true; } if (path.length === 1 && type !== INTERACTION_CALLED) { return type === INTERACTION_ASSIGNED; } const key = path[0]; if (typeof key !== 'string') { return true; } const memberVariable = this.getMemberVariables()[key]; return (!memberVariable || memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context)); } include() { this.included = true; this.context.includeAllExports(); } prepare(accessedGlobalsByScope) { if (this.mergedNamespaces.length > 0) { this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope); } } renderBlock(options) { const { exportNamesByVariable, format, freeze, indent: t, namespaceToStringTag, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options; const memberVariables = this.getMemberVariables(); const members = Object.entries(memberVariables) .filter(([_, variable]) => variable.included) .map(([name, variable]) => { if (this.referencedEarly || variable.isReassigned || variable === this) { return [ null, `get ${name}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}` ]; } return [name, variable.getName(getPropertyAccess)]; }); members.unshift([null, `__proto__:${_}null`]); let output = getObject(members, { lineBreakIndent: { base: '', t } }); if (this.mergedNamespaces.length > 0) { const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess)); output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`; } else { // The helper to merge namespaces will also take care of freezing and toStringTag if (namespaceToStringTag) { output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`; } if (freeze) { output = `/*#__PURE__*/Object.freeze(${output})`; } } const name = this.getName(getPropertyAccess); output = `${cnst} ${name}${_}=${_}${output};`; if (format === 'system' && exportNamesByVariable.has(this)) { output += `${n}${getSystemExportStatement([this], options)};`; } return output; } renderFirst() { return this.referencedEarly; } setMergedNamespaces(mergedNamespaces) { this.mergedNamespaces = mergedNamespaces; const moduleExecIndex = this.context.getModuleExecIndex(); for (const identifier of this.references) { if (identifier.context.getModuleExecIndex() <= moduleExecIndex) { this.referencedEarly = true; break; } } } } NamespaceVariable.prototype.isNamespace = true; class SyntheticNamedExportVariable extends Variable { constructor(context, name, syntheticNamespace) { super(name); this.baseVariable = null; this.context = context; this.module = context.module; this.syntheticNamespace = syntheticNamespace; } getBaseVariable() { if (this.baseVariable) return this.baseVariable; let baseVariable = this.syntheticNamespace; while (baseVariable instanceof ExportDefaultVariable || baseVariable instanceof SyntheticNamedExportVariable) { if (baseVariable instanceof ExportDefaultVariable) { const original = baseVariable.getOriginalVariable(); if (original === baseVariable) break; baseVariable = original; } if (baseVariable instanceof SyntheticNamedExportVariable) { baseVariable = baseVariable.syntheticNamespace; } } return (this.baseVariable = baseVariable); } getBaseVariableName() { return this.syntheticNamespace.getBaseVariableName(); } getName(getPropertyAccess) { return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`; } include() { this.included = true; this.context.includeVariableInModule(this.syntheticNamespace); } setRenderNames(baseName, name) { super.setRenderNames(baseName, name); } } var BuildPhase; (function (BuildPhase) { BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE"; BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE"; BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE"; })(BuildPhase || (BuildPhase = {})); const sourceMapCache = new WeakMap(); /** * This clears the decoded array and falls back to the encoded string form. * Sourcemap mappings arrays can be very large and holding on to them for longer * than is necessary leads to poor heap utilization. */ function resetCacheToEncoded(cache) { if (cache.encodedMappings === undefined && cache.decodedMappings) { cache.encodedMappings = encode$3(cache.decodedMappings); } cache.decodedMappings = undefined; } function resetSourcemapCache(map, sourcemapChain) { if (map) { const cache = sourceMapCache.get(map); if (cache) { resetCacheToEncoded(cache); } } if (!sourcemapChain) { return; } for (const map of sourcemapChain) { if (map.missing) continue; resetSourcemapCache(map); } } function decodedSourcemap(map) { if (!map) return null; if (typeof map === 'string') { map = JSON.parse(map); } if (!map.mappings) { return { mappings: [], names: [], sources: [], version: 3 }; } const originalMappings = map.mappings; const isAlreadyDecoded = Array.isArray(originalMappings); const cache = { decodedMappings: isAlreadyDecoded ? originalMappings : undefined, encodedMappings: isAlreadyDecoded ? undefined : originalMappings }; const decodedMap = { ...map, // By moving mappings behind an accessor, we can avoid unneeded computation for cases // where the mappings field is never actually accessed. This appears to greatly reduce // the overhead of sourcemap decoding in terms of both compute time and memory usage. get mappings() { if (cache.decodedMappings) { return cache.decodedMappings; } // If decodedMappings doesn't exist then encodedMappings should. // The only scenario where cache.encodedMappings should be undefined is if the map // this was constructed from was already decoded, or if mappings was set to a new // decoded string. In either case, this line shouldn't get hit. cache.decodedMappings = cache.encodedMappings ? decode$1(cache.encodedMappings) : []; cache.encodedMappings = undefined; return cache.decodedMappings; } }; sourceMapCache.set(decodedMap, cache); return decodedMap; } function getId(m) { return m.id; } function getOriginalLocation(sourcemapChain, location) { const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !sourcemap.missing); traceSourcemap: while (filteredSourcemapChain.length > 0) { const sourcemap = filteredSourcemapChain.pop(); const line = sourcemap.mappings[location.line - 1]; if (line) { const filteredLine = line.filter((segment) => segment.length > 1); const lastSegment = filteredLine[filteredLine.length - 1]; for (const segment of filteredLine) { if (segment[0] >= location.column || segment === lastSegment) { location = { column: segment[3], line: segment[2] + 1 }; continue traceSourcemap; } } } throw new Error("Can't resolve original location of error."); } return location; } function getAssertionsFromImportExpression(node) { const assertProperty = node.arguments?.[0]?.properties.find((property) => getPropertyKey(property) === 'assert')?.value; if (!assertProperty) { return EMPTY_OBJECT; } const assertFields = assertProperty.properties .map(property => { const key = getPropertyKey(property); if (typeof key === 'string' && typeof property.value.value === 'string') { return [key, property.value.value]; } return null; }) .filter((property) => !!property); if (assertFields.length > 0) { return Object.fromEntries(assertFields); } return EMPTY_OBJECT; } const getPropertyKey = (property) => { const key = property.key; return key && (key.name || key.value); }; function getAssertionsFromImportExportDeclaration(assertions) { return assertions?.length ? Object.fromEntries(assertions.map(assertion => [getPropertyKey(assertion), assertion.value.value])) : EMPTY_OBJECT; } function doAssertionsDiffer(assertionA, assertionB) { const keysA = Object.keys(assertionA); return (keysA.length !== Object.keys(assertionB).length || keysA.some(key => assertionA[key] !== assertionB[key])); } let timers = new Map(); function getPersistedLabel(label, level) { switch (level) { case 1: { return `# ${label}`; } case 2: { return `## ${label}`; } case 3: { return label; } default: { return `${' '.repeat(level - 4)}- ${label}`; } } } function timeStartImpl(label, level = 3) { label = getPersistedLabel(label, level); const startMemory = process$1.memoryUsage().heapUsed; const startTime = performance$1.now(); const timer = timers.get(label); if (timer === undefined) { timers.set(label, { memory: 0, startMemory, startTime, time: 0, totalMemory: 0 }); } else { timer.startMemory = startMemory; timer.startTime = startTime; } } function timeEndImpl(label, level = 3) { label = getPersistedLabel(label, level); const timer = timers.get(label); if (timer !== undefined) { const currentMemory = process$1.memoryUsage().heapUsed; timer.memory += currentMemory - timer.startMemory; timer.time += performance$1.now() - timer.startTime; timer.totalMemory = Math.max(timer.totalMemory, currentMemory); } } function getTimings() { const newTimings = {}; for (const [label, { memory, time, totalMemory }] of timers) { newTimings[label] = [time, memory, totalMemory]; } return newTimings; } let timeStart = doNothing; let timeEnd = doNothing; const TIMED_PLUGIN_HOOKS = [ 'augmentChunkHash', 'buildEnd', 'buildStart', 'generateBundle', 'load', 'moduleParsed', 'options', 'outputOptions', 'renderChunk', 'renderDynamicImport', 'renderStart', 'resolveDynamicImport', 'resolveFileUrl', 'resolveId', 'resolveImportMeta', 'shouldTransformCachedModule', 'transform', 'writeBundle' ]; function getPluginWithTimers(plugin, index) { if (plugin._hasTimer) return plugin; plugin._hasTimer = true; for (const hook of TIMED_PLUGIN_HOOKS) { if (hook in plugin) { let timerLabel = `plugin ${index}`; if (plugin.name) { timerLabel += ` (${plugin.name})`; } timerLabel += ` - ${hook}`; const handler = function (...parameters) { timeStart(timerLabel, 4); const result = hookFunction.apply(this, parameters); timeEnd(timerLabel, 4); return result; }; let hookFunction; if (typeof plugin[hook].handler === 'function') { hookFunction = plugin[hook].handler; plugin[hook].handler = handler; } else { hookFunction = plugin[hook]; plugin[hook] = handler; } } } return plugin; } function initialiseTimers(inputOptions) { if (inputOptions.perf) { timers = new Map(); timeStart = timeStartImpl; timeEnd = timeEndImpl; inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers); } else { timeStart = doNothing; timeEnd = doNothing; } } function markModuleAndImpureDependenciesAsExecuted(baseModule) { baseModule.isExecuted = true; const modules = [baseModule]; const visitedModules = new Set(); for (const module of modules) { for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) { if (!(dependency instanceof ExternalModule) && !dependency.isExecuted && (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) && !visitedModules.has(dependency.id)) { dependency.isExecuted = true; visitedModules.add(dependency.id); modules.push(dependency); } } } } const MISSING_EXPORT_SHIM_DESCRIPTION = { identifier: null, localName: MISSING_EXPORT_SHIM_VARIABLE }; function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) { const searchedModules = searchedNamesAndModules.get(name); if (searchedModules) { if (searchedModules.has(target)) { return isExportAllSearch ? [null] : error$4(logCircularReexport(name, target.id)); } searchedModules.add(target); } else { searchedNamesAndModules.set(name, new Set([target])); } return target.getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules }); } function getAndExtendSideEffectModules(variable, module) { const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet)); let currentVariable = variable; const referencedVariables = new Set([currentVariable]); while (true) { const importingModule = currentVariable.module; currentVariable = currentVariable instanceof ExportDefaultVariable ? currentVariable.getDirectOriginalVariable() : currentVariable instanceof SyntheticNamedExportVariable ? currentVariable.syntheticNamespace : null; if (!currentVariable || referencedVariables.has(currentVariable)) { break; } referencedVariables.add(currentVariable); sideEffectModules.add(importingModule); const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable); if (originalSideEffects) { for (const module of originalSideEffects) { sideEffectModules.add(module); } } } return sideEffectModules; } class Module { constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, assertions) { this.graph = graph; this.id = id; this.options = options; this.alternativeReexportModules = new Map(); this.chunkFileNames = new Set(); this.chunkNames = []; this.cycles = new Set(); this.dependencies = new Set(); this.dynamicDependencies = new Set(); this.dynamicImporters = []; this.dynamicImports = []; this.execIndex = Infinity; this.implicitlyLoadedAfter = new Set(); this.implicitlyLoadedBefore = new Set(); this.importDescriptions = new Map(); this.importMetas = []; this.importedFromNotTreeshaken = false; this.importers = []; this.includedDynamicImporters = []; this.includedImports = new Set(); this.isExecuted = false; this.isUserDefinedEntryPoint = false; this.needsExportShim = false; this.sideEffectDependenciesByVariable = new Map(); this.sourcesWithAssertions = new Map(); this.allExportNames = null; this.ast = null; this.exportAllModules = []; this.exportAllSources = new Set(); this.exportNamesByVariable = null; this.exportShimVariable = new ExportShimVariable(this); this.exports = new Map(); this.namespaceReexportsByName = new Map(); this.reexportDescriptions = new Map(); this.relevantDependencies = null; this.syntheticExports = new Map(); this.syntheticNamespace = null; this.transformDependencies = []; this.transitiveReexports = null; this.excludeFromSourcemap = /\0/.test(id); this.context = options.moduleContext(id); this.preserveSignature = this.options.preserveEntrySignatures; // eslint-disable-next-line @typescript-eslint/no-this-alias const module = this; const { dynamicImports, dynamicImporters, exportAllSources, exports, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAssertions } = this; this.info = { assertions, ast: null, code: null, get dynamicallyImportedIdResolutions() { return dynamicImports .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument]) .filter(Boolean); }, get dynamicallyImportedIds() { // We cannot use this.dynamicDependencies because this is needed before // dynamicDependencies are populated return dynamicImports.map(({ id }) => id).filter((id) => id != null); }, get dynamicImporters() { return dynamicImporters.sort(); }, get exportedBindings() { const exportBindings = { '.': [...exports.keys()] }; for (const [name, { source }] of reexportDescriptions) { (exportBindings[source] ?? (exportBindings[source] = [])).push(name); } for (const source of exportAllSources) { (exportBindings[source] ?? (exportBindings[source] = [])).push('*'); } return exportBindings; }, get exports() { return [ ...exports.keys(), ...reexportDescriptions.keys(), ...[...exportAllSources].map(() => '*') ]; }, get hasDefaultExport() { // This information is only valid after parsing if (!module.ast) { return null; } return module.exports.has('default') || reexportDescriptions.has('default'); }, get hasModuleSideEffects() { warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', URL_THIS_GETMODULEINFO, true, options); return this.moduleSideEffects; }, id, get implicitlyLoadedAfterOneOf() { // eslint-disable-next-line unicorn/prefer-spread return Array.from(implicitlyLoadedAfter, getId).sort(); }, get implicitlyLoadedBefore() { // eslint-disable-next-line unicorn/prefer-spread return Array.from(implicitlyLoadedBefore, getId).sort(); }, get importedIdResolutions() { // eslint-disable-next-line unicorn/prefer-spread return Array.from(sourcesWithAssertions.keys(), source => module.resolvedIds[source]).filter(Boolean); }, get importedIds() { // We cannot use this.dependencies because this is needed before // dependencies are populated // eslint-disable-next-line unicorn/prefer-spread return Array.from(sourcesWithAssertions.keys(), source => module.resolvedIds[source]?.id).filter(Boolean); }, get importers() { return importers.sort(); }, isEntry, isExternal: false, get isIncluded() { if (graph.phase !== BuildPhase.GENERATE) { return null; } return module.isIncluded(); }, meta: { ...meta }, moduleSideEffects, syntheticNamedExports }; // Hide the deprecated key so that it only warns when accessed explicitly // eslint-disable-next-line unicorn/consistent-destructuring Object.defineProperty(this.info, 'hasModuleSideEffects', { enumerable: false }); } basename() { const base = basename$1(this.id); const extension = extname(this.id); return makeLegal(extension ? base.slice(0, -extension.length) : base); } bindReferences() { this.ast.bind(); } error(properties, pos) { this.addLocationToLogProps(properties, pos); return error$4(properties); } // sum up the length of all ast nodes that are included estimateSize() { let size = 0; for (const node of this.ast.body) { if (node.included) { size += node.end - node.start; } } return size; } getAllExportNames() { if (this.allExportNames) { return this.allExportNames; } this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]); for (const module of this.exportAllModules) { if (module instanceof ExternalModule) { this.allExportNames.add(`*${module.id}`); continue; } for (const name of module.getAllExportNames()) { if (name !== 'default') this.allExportNames.add(name); } } // We do not count the synthetic namespace as a regular export to hide it // from entry signatures and namespace objects if (typeof this.info.syntheticNamedExports === 'string') { this.allExportNames.delete(this.info.syntheticNamedExports); } return this.allExportNames; } getDependenciesToBeIncluded() { if (this.relevantDependencies) return this.relevantDependencies; this.relevantDependencies = new Set(); const necessaryDependencies = new Set(); const alwaysCheckedDependencies = new Set(); const dependencyVariables = new Set(this.includedImports); if (this.info.isEntry || this.includedDynamicImporters.length > 0 || this.namespace.included || this.implicitlyLoadedAfter.size > 0) { for (const exportName of [...this.getReexports(), ...this.getExports()]) { const [exportedVariable] = this.getVariableForExportName(exportName); if (exportedVariable?.included) { dependencyVariables.add(exportedVariable); } } } for (let variable of dependencyVariables) { const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable); if (sideEffectDependencies) { for (const module of sideEffectDependencies) { alwaysCheckedDependencies.add(module); } } if (variable instanceof SyntheticNamedExportVariable) { variable = variable.getBaseVariable(); } else if (variable instanceof ExportDefaultVariable) { variable = variable.getOriginalVariable(); } necessaryDependencies.add(variable.module); } if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') { for (const dependency of this.dependencies) { this.relevantDependencies.add(dependency); } } else { this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies); } for (const dependency of necessaryDependencies) { this.relevantDependencies.add(dependency); } return this.relevantDependencies; } getExportNamesByVariable() { if (this.exportNamesByVariable) { return this.exportNamesByVariable; } const exportNamesByVariable = new Map(); for (const exportName of this.getAllExportNames()) { let [tracedVariable] = this.getVariableForExportName(exportName); if (tracedVariable instanceof ExportDefaultVariable) { tracedVariable = tracedVariable.getOriginalVariable(); } if (!tracedVariable || !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) { continue; } const existingExportNames = exportNamesByVariable.get(tracedVariable); if (existingExportNames) { existingExportNames.push(exportName); } else { exportNamesByVariable.set(tracedVariable, [exportName]); } } return (this.exportNamesByVariable = exportNamesByVariable); } getExports() { return [...this.exports.keys()]; } getReexports() { if (this.transitiveReexports) { return this.transitiveReexports; } // to avoid infinite recursion when using circular `export * from X` this.transitiveReexports = []; const reexports = new Set(this.reexportDescriptions.keys()); for (const module of this.exportAllModules) { if (module instanceof ExternalModule) { reexports.add(`*${module.id}`); } else { for (const name of [...module.getReexports(), ...module.getExports()]) { if (name !== 'default') reexports.add(name); } } } return (this.transitiveReexports = [...reexports]); } getRenderedExports() { // only direct exports are counted here, not reexports at all const renderedExports = []; const removedExports = []; for (const exportName of this.exports.keys()) { const [variable] = this.getVariableForExportName(exportName); (variable && variable.included ? renderedExports : removedExports).push(exportName); } return { removedExports, renderedExports }; } getSyntheticNamespace() { if (this.syntheticNamespace === null) { this.syntheticNamespace = undefined; [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string' ? this.info.syntheticNamedExports : 'default', { onlyExplicit: true }); } if (!this.syntheticNamespace) { return error$4(logSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports)); } return this.syntheticNamespace; } getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) { if (name[0] === '*') { if (name.length === 1) { // export * from './other' return [this.namespace]; } // export * from 'external' const module = this.graph.modulesById.get(name.slice(1)); return module.getVariableForExportName('*'); } // export { foo } from './other' const reexportDeclaration = this.reexportDescriptions.get(name); if (reexportDeclaration) { const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules); if (!variable) { return this.error(logMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start); } if (importerForSideEffects) { setAlternativeExporterIfCyclic(variable, importerForSideEffects, this); if (this.info.moduleSideEffects) { getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this); } } return [variable]; } const exportDeclaration = this.exports.get(name); if (exportDeclaration) { if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) { return [this.exportShimVariable]; } const name = exportDeclaration.localName; const variable = this.traceVariable(name, { importerForSideEffects, searchedNamesAndModules }); if (importerForSideEffects) { setAlternativeExporterIfCyclic(variable, importerForSideEffects, this); getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this); } return [variable]; } if (onlyExplicit) { return [null]; } if (name !== 'default') { const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ?? this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules); this.namespaceReexportsByName.set(name, foundNamespaceReexport); if (foundNamespaceReexport[0]) { return foundNamespaceReexport; } } if (this.info.syntheticNamedExports) { return [ getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace())) ]; } // we don't want to create shims when we are just // probing export * modules for exports if (!isExportAllSearch && this.options.shimMissingExports) { this.shimMissingExport(name); return [this.exportShimVariable]; } return [null]; } hasEffects() { return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects(); } include() { const context = createInclusionContext(); if (this.ast.shouldBeIncluded(context)) this.ast.include(context, false); } includeAllExports(includeNamespaceMembers) { if (!this.isExecuted) { markModuleAndImpureDependenciesAsExecuted(this); this.graph.needsTreeshakingPass = true; } for (const exportName of this.exports.keys()) { if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) { const variable = this.getVariableForExportName(exportName)[0]; variable.deoptimizePath(UNKNOWN_PATH); if (!variable.included) { this.includeVariable(variable); } } } for (const name of this.getReexports()) { const [variable] = this.getVariableForExportName(name); if (variable) { variable.deoptimizePath(UNKNOWN_PATH); if (!variable.included) { this.includeVariable(variable); } if (variable instanceof ExternalVariable) { variable.module.reexported = true; } } } if (includeNamespaceMembers) { this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces()); } } includeAllInBundle() { this.ast.include(createInclusionContext(), true); this.includeAllExports(false); } includeExportsByNames(names) { if (!this.isExecuted) { markModuleAndImpureDependenciesAsExecuted(this); this.graph.needsTreeshakingPass = true; } let includeNamespaceMembers = false; for (const name of names) { const variable = this.getVariableForExportName(name)[0]; if (variable) { variable.deoptimizePath(UNKNOWN_PATH); if (!variable.included) { this.includeVariable(variable); } } if (!this.exports.has(name) && !this.reexportDescriptions.has(name)) { includeNamespaceMembers = true; } } if (includeNamespaceMembers) { this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces()); } } isIncluded() { // Modules where this.ast is missing have been loaded via this.load and are // not yet fully processed, hence they cannot be included. return (this.ast && (this.ast.included || this.namespace.included || this.importedFromNotTreeshaken || this.exportShimVariable.included)); } linkImports() { this.addModulesToImportDescriptions(this.importDescriptions); this.addModulesToImportDescriptions(this.reexportDescriptions); const externalExportAllModules = []; for (const source of this.exportAllSources) { const module = this.graph.modulesById.get(this.resolvedIds[source].id); if (module instanceof ExternalModule) { externalExportAllModules.push(module); continue; } this.exportAllModules.push(module); } this.exportAllModules.push(...externalExportAllModules); } log(level, properties, pos) { this.addLocationToLogProps(properties, pos); this.options.onLog(level, properties); } render(options) { const source = this.magicString.clone(); this.ast.render(source, options); source.trim(); const { usesTopLevelAwait } = this.astContext; if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') { return error$4(logInvalidFormatForTopLevelAwait(this.id, options.format)); } return { source, usesTopLevelAwait }; } setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) { timeStart('generate ast', 3); this.info.code = code; this.originalCode = originalCode; // We need to call decodedSourcemap on the input in case they were hydrated from json in the cache and don't // have the lazy evaluation cache configured. Right now this isn't enforced by the type system because the // RollupCache stores `ExistingDecodedSourcemap` instead of `ExistingRawSourcemap` this.originalSourcemap = decodedSourcemap(originalSourcemap); this.sourcemapChain = sourcemapChain.map(mapOrMissing => mapOrMissing.missing ? mapOrMissing : decodedSourcemap(mapOrMissing)); // If coming from cache and this value is already fully decoded, we want to re-encode here to save memory. resetSourcemapCache(this.originalSourcemap, this.sourcemapChain); if (transformFiles) { this.transformFiles = transformFiles; } this.transformDependencies = transformDependencies; this.customTransformCache = customTransformCache; this.updateOptions(moduleOptions); const moduleAst = ast ?? this.tryParse(); timeEnd('generate ast', 3); timeStart('analyze ast', 3); this.resolvedIds = resolvedIds ?? Object.create(null); // By default, `id` is the file name. Custom resolvers and loaders // can change that, but it makes sense to use it for the source file name const fileName = this.id; this.magicString = new MagicString$3(code, { filename: (this.excludeFromSourcemap ? null : fileName), indentExclusionRanges: [] }); this.astContext = { addDynamicImport: this.addDynamicImport.bind(this), addExport: this.addExport.bind(this), addImport: this.addImport.bind(this), addImportMeta: this.addImportMeta.bind(this), code, deoptimizationTracker: this.graph.deoptimizationTracker, error: this.error.bind(this), fileName, getExports: this.getExports.bind(this), getModuleExecIndex: () => this.execIndex, getModuleName: this.basename.bind(this), getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode, getReexports: this.getReexports.bind(this), importDescriptions: this.importDescriptions, includeAllExports: () => this.includeAllExports(true), includeDynamicImport: this.includeDynamicImport.bind(this), includeVariableInModule: this.includeVariableInModule.bind(this), log: this.log.bind(this), magicString: this.magicString, manualPureFunctions: this.graph.pureFunctions, module: this, moduleContext: this.context, options: this.options, requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true), traceExport: (name) => this.getVariableForExportName(name)[0], traceVariable: this.traceVariable.bind(this), usesTopLevelAwait: false }; this.scope = new ModuleScope(this.graph.scope, this.astContext); this.namespace = new NamespaceVariable(this.astContext); this.ast = new Program(moduleAst, { context: this.astContext, type: 'Module' }, this.scope); // Assign AST directly if has existing one as there's no way to drop it from memory. // If cache is enabled, also assign directly as otherwise it takes more CPU and memory to re-compute. if (ast || this.options.cache !== false) { this.info.ast = moduleAst; } else { // Make lazy and apply LRU cache to not hog the memory Object.defineProperty(this.info, 'ast', { get: () => { if (this.graph.astLru.has(fileName)) { return this.graph.astLru.get(fileName); } else { const parsedAst = this.tryParse(); this.graph.astLru.set(fileName, parsedAst); return parsedAst; } } }); } timeEnd('analyze ast', 3); } toJSON() { return { assertions: this.info.assertions, ast: this.info.ast, code: this.info.code, customTransformCache: this.customTransformCache, // eslint-disable-next-line unicorn/prefer-spread dependencies: Array.from(this.dependencies, getId), id: this.id, meta: this.info.meta, moduleSideEffects: this.info.moduleSideEffects, originalCode: this.originalCode, originalSourcemap: this.originalSourcemap, resolvedIds: this.resolvedIds, sourcemapChain: this.sourcemapChain, syntheticNamedExports: this.info.syntheticNamedExports, transformDependencies: this.transformDependencies, transformFiles: this.transformFiles }; } traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) { const localVariable = this.scope.variables.get(name); if (localVariable) { return localVariable; } const importDescription = this.importDescriptions.get(name); if (importDescription) { const otherModule = importDescription.module; if (otherModule instanceof Module && importDescription.name === '*') { return otherModule.namespace; } const [declaration] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules); if (!declaration) { return this.error(logMissingExport(importDescription.name, this.id, otherModule.id), importDescription.start); } return declaration; } return null; } updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) { if (moduleSideEffects != null) { this.info.moduleSideEffects = moduleSideEffects; } if (syntheticNamedExports != null) { this.info.syntheticNamedExports = syntheticNamedExports; } if (meta != null) { Object.assign(this.info.meta, meta); } } addDynamicImport(node) { let argument = node.source; if (argument instanceof TemplateLiteral) { if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) { argument = argument.quasis[0].value.cooked; } } else if (argument instanceof Literal && typeof argument.value === 'string') { argument = argument.value; } this.dynamicImports.push({ argument, id: null, node, resolution: null }); } addExport(node) { if (node instanceof ExportDefaultDeclaration) { // export default foo; this.exports.set('default', { identifier: node.variable.getAssignedVariableName(), localName: 'default' }); } else if (node instanceof ExportAllDeclaration) { const source = node.source.value; this.addSource(source, node); if (node.exported) { // export * as name from './other' const name = node.exported.name; this.reexportDescriptions.set(name, { localName: '*', module: null, source, start: node.start }); } else { // export * from './other' this.exportAllSources.add(source); } } else if (node.source instanceof Literal) { // export { name } from './other' const source = node.source.value; this.addSource(source, node); for (const { exported, local, start } of node.specifiers) { const name = exported instanceof Literal ? exported.value : exported.name; this.reexportDescriptions.set(name, { localName: local instanceof Literal ? local.value : local.name, module: null, source, start }); } } else if (node.declaration) { const declaration = node.declaration; if (declaration instanceof VariableDeclaration) { // export var { foo, bar } = ... // export var foo = 1, bar = 2; for (const declarator of declaration.declarations) { for (const localName of extractAssignedNames$1(declarator.id)) { this.exports.set(localName, { identifier: null, localName }); } } } else { // export function foo () {} const localName = declaration.id.name; this.exports.set(localName, { identifier: null, localName }); } } else { // export { foo, bar, baz } for (const { local, exported } of node.specifiers) { // except for reexports, local must be an Identifier const localName = local.name; const exportedName = exported instanceof Identifier ? exported.name : exported.value; this.exports.set(exportedName, { identifier: null, localName }); } } } addImport(node) { const source = node.source.value; this.addSource(source, node); for (const specifier of node.specifiers) { const name = specifier instanceof ImportDefaultSpecifier ? 'default' : specifier instanceof ImportNamespaceSpecifier ? '*' : specifier.imported instanceof Identifier ? specifier.imported.name : specifier.imported.value; this.importDescriptions.set(specifier.local.name, { module: null, name, source, start: specifier.start }); } } addImportMeta(node) { this.importMetas.push(node); } addLocationToLogProps(properties, pos) { properties.id = this.id; properties.pos = pos; let code = this.info.code; const location = locate(code, pos, { offsetLine: 1 }); if (location) { let { column, line } = location; try { ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line })); code = this.originalCode; } catch (error_) { this.options.onLog(LOGLEVEL_WARN, logInvalidSourcemapForError(error_, this.id, column, line, pos)); } augmentCodeLocation(properties, { column, line }, code, this.id); } } addModulesToImportDescriptions(importDescription) { for (const specifier of importDescription.values()) { const { id } = this.resolvedIds[specifier.source]; specifier.module = this.graph.modulesById.get(id); } } addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) { const handledDependencies = new Set(); const addSideEffectDependencies = (possibleDependencies) => { for (const dependency of possibleDependencies) { if (handledDependencies.has(dependency)) { continue; } handledDependencies.add(dependency); if (necessaryDependencies.has(dependency)) { relevantDependencies.add(dependency); continue; } if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) { continue; } if (dependency instanceof ExternalModule || dependency.hasEffects()) { relevantDependencies.add(dependency); continue; } addSideEffectDependencies(dependency.dependencies); } }; addSideEffectDependencies(this.dependencies); addSideEffectDependencies(alwaysCheckedDependencies); } addSource(source, declaration) { const parsedAssertions = getAssertionsFromImportExportDeclaration(declaration.assertions); const existingAssertions = this.sourcesWithAssertions.get(source); if (existingAssertions) { if (doAssertionsDiffer(existingAssertions, parsedAssertions)) { this.log(LOGLEVEL_WARN, logInconsistentImportAssertions(existingAssertions, parsedAssertions, source, this.id), declaration.start); } } else { this.sourcesWithAssertions.set(source, parsedAssertions); } } getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) { let foundSyntheticDeclaration = null; const foundInternalDeclarations = new Map(); const foundExternalDeclarations = new Set(); for (const module of this.exportAllModules) { // Synthetic namespaces should not hide "regular" exports of the same name if (module.info.syntheticNamedExports === name) { continue; } const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true, // We are creating a copy to handle the case where the same binding is // imported through different namespace reexports gracefully copyNameToModulesMap(searchedNamesAndModules)); if (module instanceof ExternalModule || indirectExternal) { foundExternalDeclarations.add(variable); } else if (variable instanceof SyntheticNamedExportVariable) { if (!foundSyntheticDeclaration) { foundSyntheticDeclaration = variable; } } else if (variable) { foundInternalDeclarations.set(variable, module); } } if (foundInternalDeclarations.size > 0) { const foundDeclarationList = [...foundInternalDeclarations]; const usedDeclaration = foundDeclarationList[0][0]; if (foundDeclarationList.length === 1) { return [usedDeclaration]; } this.options.onLog(LOGLEVEL_WARN, logNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id))); // TODO we are pretending it was not found while it should behave like "undefined" return [null]; } if (foundExternalDeclarations.size > 0) { const foundDeclarationList = [...foundExternalDeclarations]; const usedDeclaration = foundDeclarationList[0]; if (foundDeclarationList.length > 1) { this.options.onLog(LOGLEVEL_WARN, logAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id))); } return [usedDeclaration, true]; } if (foundSyntheticDeclaration) { return [foundSyntheticDeclaration]; } return [null]; } includeAndGetAdditionalMergedNamespaces() { const externalNamespaces = new Set(); const syntheticNamespaces = new Set(); for (const module of [this, ...this.exportAllModules]) { if (module instanceof ExternalModule) { const [externalVariable] = module.getVariableForExportName('*'); externalVariable.include(); this.includedImports.add(externalVariable); externalNamespaces.add(externalVariable); } else if (module.info.syntheticNamedExports) { const syntheticNamespace = module.getSyntheticNamespace(); syntheticNamespace.include(); this.includedImports.add(syntheticNamespace); syntheticNamespaces.add(syntheticNamespace); } } return [...syntheticNamespaces, ...externalNamespaces]; } includeDynamicImport(node) { const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution; if (resolution instanceof Module) { resolution.includedDynamicImporters.push(this); const importedNames = this.options.treeshake ? node.getDeterministicImportedNames() : undefined; if (importedNames) { resolution.includeExportsByNames(importedNames); } else { resolution.includeAllExports(true); } } } includeVariable(variable) { const variableModule = variable.module; if (variable.included) { if (variableModule instanceof Module && variableModule !== this) { getAndExtendSideEffectModules(variable, this); } } else { variable.include(); this.graph.needsTreeshakingPass = true; if (variableModule instanceof Module) { if (!variableModule.isExecuted) { markModuleAndImpureDependenciesAsExecuted(variableModule); } if (variableModule !== this) { const sideEffectModules = getAndExtendSideEffectModules(variable, this); for (const module of sideEffectModules) { if (!module.isExecuted) { markModuleAndImpureDependenciesAsExecuted(module); } } } } } } includeVariableInModule(variable) { this.includeVariable(variable); const variableModule = variable.module; if (variableModule && variableModule !== this) { this.includedImports.add(variable); } } shimMissingExport(name) { this.options.onLog(LOGLEVEL_WARN, logShimmedExport(this.id, name)); this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION); } tryParse() { try { return this.graph.contextParse(this.info.code); } catch (error_) { return this.error(logParseError(error_, this.id), error_.pos); } } } // if there is a cyclic import in the reexport chain, we should not // import from the original module but from the cyclic module to not // mess up execution order. function setAlternativeExporterIfCyclic(variable, importer, reexporter) { if (variable.module instanceof Module && variable.module !== reexporter) { const exporterCycles = variable.module.cycles; if (exporterCycles.size > 0) { const importerCycles = reexporter.cycles; for (const cycleSymbol of importerCycles) { if (exporterCycles.has(cycleSymbol)) { importer.alternativeReexportModules.set(variable, reexporter); break; } } } } } const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules && // eslint-disable-next-line unicorn/prefer-spread new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)])); function removeJsExtension(name) { return name.endsWith('.js') ? name.slice(0, -3) : name; } function getCompleteAmdId(options, chunkId) { if (options.autoId) { return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`; } return options.id ?? ''; } function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, mechanism = 'return ') { const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets; if (!namedExportsMode) { return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`; } let exportBlock = ''; for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) { if (reexports && namedExportsMode) { for (const specifier of reexports) { if (specifier.reexported !== '*') { const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess); if (exportBlock) exportBlock += n; if (specifier.imported !== '*' && specifier.needsLiveBinding) { const [left, right] = getDirectReturnFunction([], { functionReturn: true, lineBreakIndent: null, name: null }); exportBlock += `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` + `${t}enumerable:${_}true,${n}` + `${t}get:${_}${left}${importName}${right}${n}});`; } else { exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`; } } } } } for (const { exported, local } of exports) { const lhs = `exports${getPropertyAccess(exported)}`; const rhs = local; if (lhs !== rhs) { if (exportBlock) exportBlock += n; exportBlock += `${lhs}${_}=${_}${rhs};`; } } for (const { name, reexports } of dependencies) { if (reexports && namedExportsMode) { for (const specifier of reexports) { if (specifier.reexported === '*') { if (exportBlock) exportBlock += n; const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!Object.prototype.hasOwnProperty.call(exports,${_}k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`; exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], { isAsync: false, name: null })}${copyPropertyIfNecessary});`; } } } } if (exportBlock) { return `${n}${n}${exportBlock}`; } return ''; } function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) { if (exports.length > 0) { return exports[0].local; } else { for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) { if (reexports) { return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess); } } } } function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) { if (imported === 'default') { if (!isChunk) { const moduleInterop = interop(moduleId); const variableName = defaultInteropHelpersByInteropType[moduleInterop] ? defaultVariableName : moduleVariableName; return isDefaultAProperty(moduleInterop, externalLiveBindings) ? `${variableName}${getPropertyAccess('default')}` : variableName; } return depNamedExportsMode ? `${moduleVariableName}${getPropertyAccess('default')}` : moduleVariableName; } if (imported === '*') { return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)]) ? namespaceVariableName : moduleVariableName; } return `${moduleVariableName}${getPropertyAccess(imported)}`; } function getEsModuleValue(getObject) { return getObject([['value', 'true']], { lineBreakIndent: null }); } function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) { if (hasNamedExports) { if (addEsModule) { if (addNamespaceToStringTag) { return `Object.defineProperties(exports,${_}${getObject([ ['__esModule', getEsModuleValue(getObject)], [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`] ], { lineBreakIndent: null })});`; } return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`; } if (addNamespaceToStringTag) { return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`; } } return ''; } const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => { if (needsLiveBinding) { const [left, right] = getDirectReturnFunction([], { functionReturn: true, lineBreakIndent: null, name: null }); return (`Object.defineProperty(exports,${_}k,${_}{${n}` + `${t}${t}enumerable:${_}true,${n}` + `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`); } return `exports[k]${_}=${_}${name}[k]`; }; function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, indent, snippets) { const { _, cnst, n } = snippets; const neededInteropHelpers = new Set(); const interopStatements = []; const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => { neededInteropHelpers.add(helper); interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`); }; for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) { if (isChunk) { for (const { imported, reexported } of [ ...(imports || []), ...(reexports || []) ]) { if (imported === '*' && reexported !== '*') { if (!namedExportsMode) { addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name); } break; } } } else { const moduleInterop = interop(importPath); let hasDefault = false; let hasNamespace = false; for (const { imported, reexported } of [ ...(imports || []), ...(reexports || []) ]) { let helper; let variableName; if (imported === 'default') { if (!hasDefault) { hasDefault = true; if (defaultVariableName !== namespaceVariableName) { variableName = defaultVariableName; helper = defaultInteropHelpersByInteropType[moduleInterop]; } } } else if (imported === '*' && reexported !== '*' && !hasNamespace) { hasNamespace = true; helper = namespaceInteropHelpersByInteropType[moduleInterop]; variableName = namespaceVariableName; } if (helper) { addInteropStatement(variableName, helper, name); } } } } return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`; } function addJsExtension(name) { return name.endsWith('.js') ? name : name + '.js'; } // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted. // The assumption is that this makes sense for all relative ids: // https://requirejs.org/docs/api.html#jsfiles function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) { if (id[0] !== '.') { return id; } return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id); } const require$$0$3 = [ "assert", "async_hooks", "buffer", "child_process", "cluster", "console", "constants", "crypto", "dgram", "diagnostics_channel", "dns", "domain", "events", "fs", "http", "http2", "https", "inspector", "module", "net", "os", "path", "perf_hooks", "process", "punycode", "querystring", "readline", "repl", "stream", "string_decoder", "timers", "tls", "trace_events", "tty", "url", "util", "v8", "vm", "wasi", "worker_threads", "zlib" ]; var _static = require$$0$3; const builtinModules = /*@__PURE__*/getDefaultExportFromCjs$3(_static); const nodeBuiltins = new Set([ ...builtinModules, // TODO // remove once builtin-modules includes PR: https://github.com/sindresorhus/builtin-modules/pull/17 'assert/strict', 'dns/promises', 'fs/promises', 'path/posix', 'path/win32', 'readline/promises', 'stream/consumers', 'stream/promises', 'stream/web', 'timers/promises', 'util/types' ]); function warnOnBuiltins(log, dependencies) { const externalBuiltins = dependencies .map(({ importPath }) => importPath) .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:')); if (externalBuiltins.length === 0) return; log(LOGLEVEL_WARN, logMissingNodeBuiltins(externalBuiltins)); } function amd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, log, outro, snippets }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) { warnOnBuiltins(log, dependencies); const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`); const parameters = dependencies.map(m => m.name); const { n, getNonArrowFunctionIntro, _ } = snippets; if (namedExportsMode && hasExports) { parameters.unshift(`exports`); deps.unshift(`'exports'`); } if (accessedGlobals.has('require')) { parameters.unshift('require'); deps.unshift(`'require'`); } if (accessedGlobals.has('module')) { parameters.unshift('module'); deps.unshift(`'module'`); } const completeAmdId = getCompleteAmdId(amd, id); const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) + (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``); const useStrict = strict ? `${_}'use strict';` : ''; magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`); const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings); let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && namespaceToStringTag, snippets); if (namespaceMarkers) { namespaceMarkers = n + n + namespaceMarkers; } magicString .append(`${exportBlock}${namespaceMarkers}${outro}`) .indent(t) // factory function should be wrapped by parentheses to avoid lazy parsing, // cf. https://v8.dev/blog/preparser#pife .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, { isAsync: false, name: null })}{${useStrict}${n}${n}`) .append(`${n}${n}}));`); } function cjs$2(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) { const { _, n } = snippets; const useStrict = strict ? `'use strict';${n}${n}` : ''; let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && namespaceToStringTag, snippets); if (namespaceMarkers) { namespaceMarkers += n + n; } const importBlock = getImportBlock$1(dependencies, snippets, compact); const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets); magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`); const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`); magicString.append(`${exportBlock}${outro}`); } function getImportBlock$1(dependencies, { _, cnst, n }, compact) { let importBlock = ''; let definingVariable = false; for (const { importPath, name, reexports, imports } of dependencies) { if (!reexports && !imports) { if (importBlock) { importBlock += compact && !definingVariable ? ',' : `;${n}`; } definingVariable = false; importBlock += `require('${importPath}')`; } else { importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `; definingVariable = true; importBlock += `${name}${_}=${_}require('${importPath}')`; } } if (importBlock) { return `${importBlock};${n}${n}`; } return ''; } function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, namespaceToStringTag }) { const { n } = snippets; const importBlock = getImportBlock(dependencies, snippets); if (importBlock.length > 0) intro += importBlock.join(n) + n + n; intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag); if (intro) magicString.prepend(intro); const exportBlock = getExportBlock(exports, snippets); if (exportBlock.length > 0) magicString.append(n + n + exportBlock.join(n).trim()); if (outro) magicString.append(outro); magicString.trim(); } function getImportBlock(dependencies, { _ }) { const importBlock = []; for (const { importPath, reexports, imports, name, assertions } of dependencies) { const assertion = assertions ? `${_}assert${_}${assertions}` : ''; const pathWithAssertion = `'${importPath}'${assertion};`; if (!reexports && !imports) { importBlock.push(`import${_}${pathWithAssertion}`); continue; } if (imports) { let defaultImport = null; let starImport = null; const importedNames = []; for (const specifier of imports) { if (specifier.imported === 'default') { defaultImport = specifier; } else if (specifier.imported === '*') { starImport = specifier; } else { importedNames.push(specifier); } } if (starImport) { importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`); } if (defaultImport && importedNames.length === 0) { importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`); } else if (importedNames.length > 0) { importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames .map(specifier => specifier.imported === specifier.local ? specifier.imported : `${specifier.imported} as ${specifier.local}`) .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`); } } if (reexports) { let starExport = null; const namespaceReexports = []; const namedReexports = []; for (const specifier of reexports) { if (specifier.reexported === '*') { starExport = specifier; } else if (specifier.imported === '*') { namespaceReexports.push(specifier); } else { namedReexports.push(specifier); } } if (starExport) { importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`); } if (namespaceReexports.length > 0) { if (!imports || !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) { importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`); } for (const specifier of namespaceReexports) { importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`); } } if (namedReexports.length > 0) { importBlock.push(`export${_}{${_}${namedReexports .map(specifier => specifier.imported === specifier.reexported ? specifier.imported : `${specifier.imported} as ${specifier.reexported}`) .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`); } } } return importBlock; } function getExportBlock(exports, { _, cnst }) { const exportBlock = []; const exportDeclaration = []; for (const specifier of exports) { if (specifier.expression) { exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`); } exportDeclaration.push(specifier.exported === specifier.local ? specifier.local : `${specifier.local} as ${specifier.exported}`); } if (exportDeclaration.length > 0) { exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`); } return exportBlock; } const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join(''); function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact) { const parts = name.split('.'); parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0]; parts.pop(); let propertyPath = root; return (parts .map(part => { propertyPath += getPropertyAccess(part); return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`; }) .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n')); } function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) { const parts = deepName.split('.'); parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0]; const last = parts.pop(); let propertyPath = root; let deepAssignment = [ ...parts.map(part => { propertyPath += getPropertyAccess(part); return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`; }), `${propertyPath}${getPropertyAccess(last)}` ].join(`,${_}`) + `${_}=${_}${assignment}`; if (parts.length > 0) { deepAssignment = `(${deepAssignment})`; } return deepAssignment; } function trimEmptyImports(dependencies) { let index = dependencies.length; while (index--) { const { imports, reexports } = dependencies[index]; if (imports || reexports) { return dependencies.slice(0, index + 1); } } return []; } function iife(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, namedExportsMode, log, outro, snippets }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) { const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets; const isNamespaced = name && name.includes('.'); const useVariableAssignment = !extend && !isNamespaced; if (name && useVariableAssignment && !isLegal(name)) { return error$4(logIllegalIdentifierAsName(name)); } warnOnBuiltins(log, dependencies); const external = trimEmptyImports(dependencies); const deps = external.map(dep => dep.globalName || 'null'); const parameters = external.map(m => m.name); if (hasExports && !name) { log(LOGLEVEL_WARN, logMissingNameOptionForIifeExport()); } if (namedExportsMode && hasExports) { if (extend) { deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`); parameters.unshift('exports'); } else { deps.unshift('{}'); parameters.unshift('exports'); } } const useStrict = strict ? `${t}'use strict';${n}` : ''; const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets); magicString.prepend(`${intro}${interopBlock}`); let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, { isAsync: false, name: null })}{${n}${useStrict}${n}`; if (hasExports) { if (name && !(extend && namedExportsMode)) { wrapperIntro = (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) + `${_}=${_}${wrapperIntro}`; } if (isNamespaced) { wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact) + wrapperIntro; } } let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`; if (hasExports && !extend && namedExportsMode) { wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`; } const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings); let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), namespaceToStringTag, snippets); if (namespaceMarkers) { namespaceMarkers = n + n + namespaceMarkers; } magicString .append(`${exportBlock}${namespaceMarkers}${outro}`) .indent(t) .prepend(wrapperIntro) .append(wrapperOutro); } function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) { const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets; const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets); const registeredName = name ? `'${name}',${_}` : ''; const wrapperParameters = accessedGlobals.has('module') ? ['exports', 'module'] : hasExports ? ['exports'] : []; // factory function should be wrapped by parentheses to avoid lazy parsing, // cf. https://v8.dev/blog/preparser#pife let wrapperStart = `System.register(${registeredName}[` + dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) + `],${_}(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}${t}${strict ? "'use strict';" : ''}` + getStarExcludesBlock(starExcludes, t, snippets) + getImportBindingsBlock(importBindings, t, snippets) + `${n}${t}return${_}{${setters.length > 0 ? `${n}${t}${t}setters:${_}[${setters .map(setter => setter ? `${getFunctionIntro(['module'], { isAsync: false, name: null })}{${n}${t}${t}${t}${setter}${n}${t}${t}}` : systemNullSetters ? `null` : `${getFunctionIntro([], { isAsync: false, name: null })}{}`) .join(`,${_}`)}],` : ''}${n}`; wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], { isAsync: usesTopLevelAwait, name: null })}{${n}${n}`; const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`; magicString .prepend(intro + getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) + getHoistedExportsBlock(exports, t, snippets)) .append(`${outro}${n}${n}` + getSyntheticExportsBlock(exports, t, snippets) + getMissingExportsBlock(exports, t, snippets)) .indent(`${t}${t}${t}`) .append(wrapperEnd) .prepend(wrapperStart); } function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) { const importBindings = []; const setters = []; let starExcludes = null; for (const { imports, reexports } of dependencies) { const setter = []; if (imports) { for (const specifier of imports) { importBindings.push(specifier.local); if (specifier.imported === '*') { setter.push(`${specifier.local}${_}=${_}module;`); } else { setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`); } } } if (reexports) { const reexportedNames = []; let hasStarReexport = false; for (const { imported, reexported } of reexports) { if (reexported === '*') { hasStarReexport = true; } else { reexportedNames.push([ reexported, imported === '*' ? 'module' : `module${getPropertyAccess(imported)}` ]); } } if (reexportedNames.length > 1 || hasStarReexport) { const exportMapping = getObject(reexportedNames, { lineBreakIndent: null }); if (hasStarReexport) { if (!starExcludes) { starExcludes = getStarExcludes({ dependencies, exports }); } setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);'); } else { setter.push(`exports(${exportMapping});`); } } else { const [key, value] = reexportedNames[0]; setter.push(`exports('${key}',${_}${value});`); } } setters.push(setter.join(`${n}${t}${t}${t}`)); } return { importBindings, setters, starExcludes }; } const getStarExcludes = ({ dependencies, exports }) => { const starExcludes = new Set(exports.map(expt => expt.exported)); starExcludes.add('default'); for (const { reexports } of dependencies) { if (reexports) { for (const reexport of reexports) { if (reexport.reexported !== '*') starExcludes.add(reexport.reexported); } } } return starExcludes; }; const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => starExcludes ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(property => [property, '1']), { lineBreakIndent: { base: t, t } })};` : ''; const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : ''); const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets); function getExportsBlock(exports, t, { _, n }) { if (exports.length === 0) { return ''; } if (exports.length === 1) { return `exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`; } return (`exports({${n}` + exports.map(({ name, value }) => `${t}${name}:${_}${value}`).join(`,${n}`) + `${n}});${n}${n}`); } const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports .filter(expt => expt.expression) .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets); const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE) .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets); function globalProperty(name, globalVariable, getPropertyAccess) { if (!name) return 'null'; return `${globalVariable}${keypath(name, getPropertyAccess)}`; } function safeAccess(name, globalVariable, { _, getPropertyAccess }) { let propertyPath = globalVariable; return name .split('.') .map(part => (propertyPath += getPropertyAccess(part))) .join(`${_}&&${_}`); } function umd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, namedExportsMode, log, outro, snippets }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) { const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets; const factoryVariable = compact ? 'f' : 'factory'; const globalVariable = compact ? 'g' : 'global'; if (hasExports && !name) { return error$4(logMissingNameOptionForUmdExport()); } warnOnBuiltins(log, dependencies); const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`); const cjsDeps = dependencies.map(m => `require('${m.importPath}')`); const trimmedImports = trimEmptyImports(dependencies); const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess)); const factoryParameters = trimmedImports.map(m => m.name); if (namedExportsMode && (hasExports || noConflict)) { amdDeps.unshift(`'exports'`); cjsDeps.unshift(`exports`); globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets)); factoryParameters.unshift('exports'); } const completeAmdId = getCompleteAmdId(amd, id); const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) + (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``); const define = amd.define; const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``; const useStrict = strict ? `${_}'use strict';${n}` : ``; let iifeExport; if (noConflict) { const noConflictExportsVariable = compact ? 'e' : 'exports'; let factory; if (!namedExportsMode && hasExports) { factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets)};`; } else { const module = globalDeps.shift(); factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` + `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`; } iifeExport = `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` + `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` + `${t}${t}${factory}${n}` + `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], { isAsync: false, name: null })}{${_}` + `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` + `${t}})()`; } else { iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`; if (!namedExportsMode && hasExports) { iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets); } } const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0; const wrapperParameters = [factoryVariable]; if (iifeNeedsGlobal) { wrapperParameters.unshift(globalVariable); } const globalArgument = iifeNeedsGlobal ? `this,${_}` : ''; const iifeStart = iifeNeedsGlobal ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}` : ''; const iifeEnd = iifeNeedsGlobal ? ')' : ''; const cjsIntro = iifeNeedsGlobal ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` + `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}` : ''; const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` + cjsIntro + `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` + `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` + // factory function should be wrapped by parentheses to avoid lazy parsing, // cf. https://v8.dev/blog/preparser#pife `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, { isAsync: false, name: null })}{${useStrict}${n}`; const wrapperOutro = n + n + '}));'; magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`); const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings); let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), namespaceToStringTag, snippets); if (namespaceMarkers) { namespaceMarkers = n + n + namespaceMarkers; } magicString .append(`${exportBlock}${namespaceMarkers}${outro}`) .trim() .indent(t) .append(wrapperOutro) .prepend(wrapperIntro); } const finalisers = { amd, cjs: cjs$2, es, iife, system, umd }; const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out); const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out); async function createAddons(options, outputPluginDriver, chunk) { try { let [banner, footer, intro, outro] = await Promise.all([ outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator), outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator), outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator), outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator) ]); if (intro) intro += '\n\n'; if (outro) outro = `\n\n${outro}`; if (banner) banner += '\n'; if (footer) footer = '\n' + footer; return { banner, footer, intro, outro }; } catch (error_) { return error$4(logAddonNotGenerated(error_.message, error_.hook, error_.plugin)); } } const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = { amd: deconflictImportsOther, cjs: deconflictImportsOther, es: deconflictImportsEsmOrSystem, iife: deconflictImportsOther, system: deconflictImportsEsmOrSystem, umd: deconflictImportsOther }; function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) { const reversedModules = [...modules].reverse(); for (const module of reversedModules) { module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope); } deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces); DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports); for (const module of reversedModules) { module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope); } } function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) { // This is needed for namespace reexports for (const dependency of dependenciesToBeDeconflicted.dependencies) { if (preserveModules || dependency instanceof ExternalChunk) { dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null); } } for (const variable of imports) { const module = variable.module; const name = variable.name; if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) { variable.setRenderNames(null, (module instanceof ExternalModule ? externalChunkByModule.get(module) : chunkByModule.get(module)).variableName); } else if (module instanceof ExternalModule && name === 'default') { variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included) ? module.suggestedVariableName + '__default' : module.suggestedVariableName, usedNames, variable.forbiddenNames)); } else { variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames)); } } for (const variable of syntheticExports) { variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames)); } } function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) { for (const chunk of dependencies) { chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null); } for (const chunk of deconflictedNamespace) { chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null); } for (const externalModule of deconflictedDefault) { externalModule.defaultVariableName = deconflictedNamespace.has(externalModule) && canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings) ? externalModule.namespaceVariableName : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null); } for (const variable of imports) { const module = variable.module; if (module instanceof ExternalModule) { const chunk = externalChunkByModule.get(module); const name = variable.name; if (name === 'default') { const moduleInterop = interop(module.id); const variableName = defaultInteropHelpersByInteropType[moduleInterop] ? chunk.defaultVariableName : chunk.variableName; if (isDefaultAProperty(moduleInterop, externalLiveBindings)) { variable.setRenderNames(variableName, 'default'); } else { variable.setRenderNames(null, variableName); } } else if (name === '*') { variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)] ? chunk.namespaceVariableName : chunk.variableName); } else { // if the second parameter is `null`, it uses its "name" for the property name variable.setRenderNames(chunk.variableName, null); } } else { const chunk = chunkByModule.get(module); if (preserveModules && variable.isNamespace) { variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName); } else if (chunk.exportMode === 'default') { variable.setRenderNames(null, chunk.variableName); } else { variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable)); } } } } function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) { for (const module of modules) { for (const variable of module.scope.variables.values()) { if (variable.included && // this will only happen for exports in some formats !(variable.renderBaseName || (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) { variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames)); } } if (includedNamespaces.has(module)) { const namespace = module.namespace; namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames)); } } } function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) { let nameIndex = 0; for (const variable of exports) { let [exportName] = variable.name; if (exportsByName.has(exportName)) { do { exportName = toBase64(++nameIndex); // skip past leading number identifiers if (exportName.charCodeAt(0) === 49 /* '1' */) { nameIndex += 9 * 64 ** (exportName.length - 1); exportName = toBase64(nameIndex); } } while (RESERVED_NAMES$1.has(exportName) || exportsByName.has(exportName)); } exportsByName.set(exportName, variable); exportNamesByVariable.set(variable, [exportName]); } } function assignExportsToNames(exports, exportsByName, exportNamesByVariable) { for (const variable of exports) { let nameIndex = 0; let exportName = variable.name; while (exportsByName.has(exportName)) { exportName = variable.name + '$' + ++nameIndex; } exportsByName.set(exportName, variable); exportNamesByVariable.set(variable, [exportName]); } } function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, log) { const exportKeys = chunk.getExportNames(); if (exportMode === 'default') { if (exportKeys.length !== 1 || exportKeys[0] !== 'default') { return error$4(logIncompatibleExportOptionValue('default', exportKeys, facadeModuleId)); } } else if (exportMode === 'none' && exportKeys.length > 0) { return error$4(logIncompatibleExportOptionValue('none', exportKeys, facadeModuleId)); } if (exportMode === 'auto') { if (exportKeys.length === 0) { exportMode = 'none'; } else if (exportKeys.length === 1 && exportKeys[0] === 'default') { exportMode = 'default'; } else { if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) { log(LOGLEVEL_WARN, logMixedExport(facadeModuleId, name)); } exportMode = 'named'; } } return exportMode; } function guessIndentString(code) { const lines = code.split('\n'); const tabbed = lines.filter(line => /^\t+/.test(line)); const spaced = lines.filter(line => /^ {2,}/.test(line)); if (tabbed.length === 0 && spaced.length === 0) { return null; } // More lines tabbed than spaced? Assume tabs, and // default to tabs in the case of a tie (or nothing // to go on) if (tabbed.length >= spaced.length) { return '\t'; } // Otherwise, we need to guess the multiple const min = spaced.reduce((previous, current) => { const numberSpaces = /^ +/.exec(current)[0].length; return Math.min(numberSpaces, previous); }, Infinity); return ' '.repeat(min); } function getIndentString(modules, options) { if (options.indent !== true) return options.indent; for (const module of modules) { const indent = guessIndentString(module.originalCode); if (indent !== null) return indent; } return '\t'; } function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) { const staticDependencyBlocks = []; const handledDependencies = new Set(); for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) { const module = orderedModules[modulePos]; if (!handledDependencies.has(module)) { const staticDependencies = []; addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule); staticDependencyBlocks.unshift(staticDependencies); } } const dependencies = new Set(); for (const block of staticDependencyBlocks) { for (const dependency of block) { dependencies.add(dependency); } } return dependencies; } function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) { const dependencies = module.getDependenciesToBeIncluded(); for (const dependency of dependencies) { if (dependency instanceof ExternalModule) { staticDependencies.push(externalChunkByModule.get(dependency)); continue; } const dependencyChunk = chunkByModule.get(dependency); if (dependencyChunk !== chunk) { staticDependencies.push(dependencyChunk); continue; } if (!handledModules.has(dependency)) { handledModules.add(dependency); addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule); } } } // Four random characters from the private use area to minimize risk of // conflicts const hashPlaceholderLeft = '!~{'; const hashPlaceholderRight = '}~'; const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length; // This is the size of a sha256 const maxHashSize = 64; const defaultHashSize = 8; const getHashPlaceholderGenerator = () => { let nextIndex = 0; return (optionName, hashSize = defaultHashSize) => { if (hashSize > maxHashSize) { return error$4(logFailedValidation(`Hashes cannot be longer than ${maxHashSize} characters, received ${hashSize}. Check the "${optionName}" option.`)); } const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`; if (placeholder.length > hashSize) { return error$4(logFailedValidation(`To generate hashes for this number of chunks (currently ${nextIndex}), you need a minimum hash size of ${placeholder.length}, received ${hashSize}. Check the "${optionName}" option.`)); } return placeholder; }; }; const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${maxHashSize - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g'); const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder); const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match)); const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => { const containedPlaceholders = new Set(); const transformedCode = code.replace(REPLACER_REGEX, placeholder => { if (placeholders.has(placeholder)) { containedPlaceholders.add(placeholder); return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`; } return placeholder; }); return { containedPlaceholders, transformedCode }; }; const lowercaseBundleKeys = Symbol('bundleKeys'); const FILE_PLACEHOLDER = { type: 'placeholder' }; const getOutputBundle = (outputBundleBase) => { const reservedLowercaseBundleKeys = new Set(); return new Proxy(outputBundleBase, { deleteProperty(target, key) { if (typeof key === 'string') { reservedLowercaseBundleKeys.delete(key.toLowerCase()); } return Reflect.deleteProperty(target, key); }, get(target, key) { if (key === lowercaseBundleKeys) { return reservedLowercaseBundleKeys; } return Reflect.get(target, key); }, set(target, key, value) { if (typeof key === 'string') { reservedLowercaseBundleKeys.add(key.toLowerCase()); } return Reflect.set(target, key, value); } }); }; const removeUnreferencedAssets = (outputBundle) => { const unreferencedAssets = new Set(); const bundleEntries = Object.values(outputBundle); for (const asset of bundleEntries) { asset.type === 'asset' && asset.needsCodeReference && unreferencedAssets.add(asset.fileName); } for (const chunk of bundleEntries) { if (chunk.type === 'chunk') { for (const referencedFile of chunk.referencedFiles) { unreferencedAssets.has(referencedFile) && unreferencedAssets.delete(referencedFile); } } } for (const file of unreferencedAssets) { delete outputBundle[file]; } }; function renderNamePattern(pattern, patternName, replacements) { if (isPathFragment(pattern)) return error$4(logFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths. If you want your files to be stored in a subdirectory, write its name without a leading slash like this: subdirectory/pattern.`)); return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => { if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) { return error$4(logFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`)); } const replacement = replacements[type](size && Number.parseInt(size.slice(1))); if (isPathFragment(replacement)) return error$4(logFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`)); return replacement; }); } function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) { if (!reservedLowercaseBundleKeys.has(name.toLowerCase())) return name; const extension = extname(name); name = name.slice(0, Math.max(0, name.length - extension.length)); let uniqueName, uniqueIndex = 1; while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase())) ; return uniqueName; } const NON_ASSET_EXTENSIONS = new Set([ '.js', '.jsx', '.ts', '.tsx', '.mjs', '.mts', '.cjs', '.cts' ]); function getGlobalName(chunk, globals, hasExports, log) { const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id]; if (globalName) { return globalName; } if (hasExports) { log(LOGLEVEL_WARN, logMissingGlobalName(chunk.id, chunk.variableName)); return chunk.variableName; } } let Chunk$3 = class Chunk { constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) { this.orderedModules = orderedModules; this.inputOptions = inputOptions; this.outputOptions = outputOptions; this.unsetOptions = unsetOptions; this.pluginDriver = pluginDriver; this.modulesById = modulesById; this.chunkByModule = chunkByModule; this.externalChunkByModule = externalChunkByModule; this.facadeChunkByModule = facadeChunkByModule; this.includedNamespaces = includedNamespaces; this.manualChunkAlias = manualChunkAlias; this.getPlaceholder = getPlaceholder; this.bundle = bundle; this.inputBase = inputBase; this.snippets = snippets; this.entryModules = []; this.exportMode = 'named'; this.facadeModule = null; this.namespaceVariableName = ''; this.variableName = ''; this.accessedGlobalsByScope = new Map(); this.dependencies = new Set(); this.dynamicEntryModules = []; this.dynamicName = null; this.exportNamesByVariable = new Map(); this.exports = new Set(); this.exportsByName = new Map(); this.fileName = null; this.implicitEntryModules = []; this.implicitlyLoadedBefore = new Set(); this.imports = new Set(); this.includedDynamicImports = null; this.includedReexportsByModule = new Map(); // This may be updated in the constructor this.isEmpty = true; this.name = null; this.needsExportsShim = false; this.preRenderedChunkInfo = null; this.preliminaryFileName = null; this.preliminarySourcemapFileName = null; this.renderedChunkInfo = null; this.renderedDependencies = null; this.renderedModules = Object.create(null); this.sortedExportNames = null; this.strictFacade = false; this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity; const chunkModules = new Set(orderedModules); for (const module of orderedModules) { chunkByModule.set(module, this); if (module.namespace.included && !outputOptions.preserveModules) { includedNamespaces.add(module); } if (this.isEmpty && module.isIncluded()) { this.isEmpty = false; } if (module.info.isEntry || outputOptions.preserveModules) { this.entryModules.push(module); } for (const importer of module.includedDynamicImporters) { if (!chunkModules.has(importer)) { this.dynamicEntryModules.push(module); // Modules with synthetic exports need an artificial namespace for dynamic imports if (module.info.syntheticNamedExports) { includedNamespaces.add(module); this.exports.add(module.namespace); } } } if (module.implicitlyLoadedAfter.size > 0) { this.implicitEntryModules.push(module); } } this.suggestedVariableName = makeLegal(this.generateVariableName()); } static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) { const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets); chunk.assignFacadeName(facadeName, facadedModule); if (!facadeChunkByModule.has(facadedModule)) { facadeChunkByModule.set(facadedModule, chunk); } for (const dependency of facadedModule.getDependenciesToBeIncluded()) { chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : externalChunkByModule.get(dependency)); } if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) && facadedModule.info.moduleSideEffects && facadedModule.hasEffects()) { chunk.dependencies.add(chunkByModule.get(facadedModule)); } chunk.ensureReexportsAreAvailableForModule(facadedModule); chunk.facadeModule = facadedModule; chunk.strictFacade = true; return chunk; } canModuleBeFacade(module, exposedVariables) { const moduleExportNamesByVariable = module.getExportNamesByVariable(); // All exports of this chunk need to be exposed by the candidate module for (const exposedVariable of this.exports) { if (!moduleExportNamesByVariable.has(exposedVariable)) { return false; } } // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules for (const exposedVariable of exposedVariables) { if (!(exposedVariable.module === module || moduleExportNamesByVariable.has(exposedVariable) || (exposedVariable instanceof SyntheticNamedExportVariable && moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) { return false; } } return true; } finalizeChunk(code, map, sourcemapFileName, hashesByPlaceholder) { const renderedChunkInfo = this.getRenderedChunkInfo(); const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder); const preliminaryFileName = renderedChunkInfo.fileName; const fileName = (this.fileName = finalize(preliminaryFileName)); return { ...renderedChunkInfo, code, dynamicImports: renderedChunkInfo.dynamicImports.map(finalize), fileName, implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize), importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [ finalize(fileName), bindings ])), imports: renderedChunkInfo.imports.map(finalize), map, preliminaryFileName, referencedFiles: renderedChunkInfo.referencedFiles.map(finalize), sourcemapFileName }; } generateExports() { this.sortedExportNames = null; const remainingExports = new Set(this.exports); if (this.facadeModule !== null && (this.facadeModule.preserveSignature !== false || this.strictFacade)) { const exportNamesByVariable = this.facadeModule.getExportNamesByVariable(); for (const [variable, exportNames] of exportNamesByVariable) { this.exportNamesByVariable.set(variable, [...exportNames]); for (const exportName of exportNames) { this.exportsByName.set(exportName, variable); } remainingExports.delete(variable); } } if (this.outputOptions.minifyInternalExports) { assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable); } else { assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable); } if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry)) this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onLog); } generateFacades() { const facades = []; const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]); const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace)); for (const module of entryModules) { if (module.preserveSignature) { for (const exportedVariable of module.getExportNamesByVariable().keys()) { // We need to expose all entry exports from this chunk if (this.chunkByModule.get(exportedVariable.module) === this) { exposedVariables.add(exportedVariable); } } } } for (const module of entryModules) { // eslint-disable-next-line unicorn/prefer-spread const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)), // mapping must run after Set 'name' dedupe name => ({ name })); if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) { requiredFacades.push({}); } // eslint-disable-next-line unicorn/prefer-spread requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName }))); if (requiredFacades.length === 0) { requiredFacades.push({}); } if (!this.facadeModule) { const needsStrictFacade = !this.outputOptions.preserveModules && (module.preserveSignature === 'strict' || (module.preserveSignature === 'exports-only' && module.getExportNamesByVariable().size > 0)); if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) { this.facadeModule = module; this.facadeChunkByModule.set(module, this); if (module.preserveSignature) { this.strictFacade = needsStrictFacade; } this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules); } } for (const facadeName of requiredFacades) { facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.externalChunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName, this.getPlaceholder, this.bundle, this.inputBase, this.snippets)); } } for (const module of this.dynamicEntryModules) { if (module.info.syntheticNamedExports) continue; if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) { this.facadeModule = module; this.facadeChunkByModule.set(module, this); this.strictFacade = true; this.dynamicName = getChunkNameFromModule(module); } else if (this.facadeModule === module && !this.strictFacade && this.canModuleBeFacade(module, exposedVariables)) { this.strictFacade = true; } else if (!this.facadeChunkByModule.get(module)?.strictFacade) { this.includedNamespaces.add(module); this.exports.add(module.namespace); } } if (!this.outputOptions.preserveModules) { this.addNecessaryImportsForFacades(); } return facades; } getChunkName() { return (this.name ?? (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName()))); } getExportNames() { return (this.sortedExportNames ?? (this.sortedExportNames = [...this.exportsByName.keys()].sort())); } getFileName() { return this.fileName || this.getPreliminaryFileName().fileName; } getImportPath(importer) { return escapeId$1(getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true)); } getPreliminaryFileName() { if (this.preliminaryFileName) { return this.preliminaryFileName; } let fileName; let hashPlaceholder = null; const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions; if (file) { fileName = basename$1(file); } else if (this.fileName === null) { const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint ? [entryFileNames, 'output.entryFileNames'] : [chunkFileNames, 'output.chunkFileNames']; fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, { format: () => format, hash: size => hashPlaceholder || (hashPlaceholder = this.getPlaceholder(patternName, size)), name: () => this.getChunkName() }); if (!hashPlaceholder) { fileName = makeUnique(fileName, this.bundle); } } else { fileName = this.fileName; } if (!hashPlaceholder) { this.bundle[fileName] = FILE_PLACEHOLDER; } // Caching is essential to not conflict with the file name reservation above return (this.preliminaryFileName = { fileName, hashPlaceholder }); } getPreliminarySourcemapFileName() { if (this.preliminarySourcemapFileName) { return this.preliminarySourcemapFileName; } let sourcemapFileName = null; let hashPlaceholder = null; const { sourcemapFileNames, format } = this.outputOptions; if (sourcemapFileNames) { const [pattern, patternName] = [sourcemapFileNames, 'output.sourcemapFileNames']; sourcemapFileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, { chunkhash: () => this.getPreliminaryFileName().hashPlaceholder || '', format: () => format, hash: size => hashPlaceholder || (hashPlaceholder = this.getPlaceholder(patternName, size)), name: () => this.getChunkName() }); if (!hashPlaceholder) { sourcemapFileName = makeUnique(sourcemapFileName, this.bundle); } } else { return null; } return (this.preliminarySourcemapFileName = { fileName: sourcemapFileName, hashPlaceholder }); } getRenderedChunkInfo() { if (this.renderedChunkInfo) { return this.renderedChunkInfo; } return (this.renderedChunkInfo = { ...this.getPreRenderedChunkInfo(), dynamicImports: this.getDynamicDependencies().map(resolveFileName), fileName: this.getFileName(), // eslint-disable-next-line unicorn/prefer-spread implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName), importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName), // eslint-disable-next-line unicorn/prefer-spread imports: Array.from(this.dependencies, resolveFileName), modules: this.renderedModules, referencedFiles: this.getReferencedFiles() }); } getVariableExportName(variable) { if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) { return '*'; } return this.exportNamesByVariable.get(variable)[0]; } link() { this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule); for (const module of this.orderedModules) { this.addImplicitlyLoadedBeforeFromModule(module); this.setUpChunkImportsAndExportsForModule(module); } } async render() { const { dependencies, exportMode, facadeModule, inputOptions: { onLog }, outputOptions, pluginDriver, snippets } = this; const { format, hoistTransitiveImports, preserveModules } = outputOptions; // for static and dynamic entry points, add transitive dependencies to this // chunk's dependencies to avoid loading latency if (hoistTransitiveImports && !preserveModules && facadeModule !== null) { for (const dep of dependencies) { if (dep instanceof Chunk) this.inlineChunkDependencies(dep); } } const preliminaryFileName = this.getPreliminaryFileName(); const preliminarySourcemapFileName = this.getPreliminarySourcemapFileName(); const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName); const renderedDependencies = [...this.getRenderedDependencies().values()]; const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format); let hasExports = renderedExports.length > 0; let hasDefaultExport = false; for (const renderedDependence of renderedDependencies) { const { reexports } = renderedDependence; if (reexports?.length) { hasExports = true; if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) { hasDefaultExport = true; } if (format === 'es') { renderedDependence.reexports = reexports.filter( // eslint-disable-next-line unicorn/prefer-array-some ({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported)); } } } if (!hasDefaultExport) { for (const { exported } of renderedExports) { if (exported === 'default') { hasDefaultExport = true; break; } } } const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo()); finalisers[format](renderedSource, { accessedGlobals, dependencies: renderedDependencies, exports: renderedExports, hasDefaultExport, hasExports, id: preliminaryFileName.fileName, indent, intro, isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry), isModuleFacade: facadeModule !== null, log: onLog, namedExportsMode: exportMode !== 'default', outro, snippets, usesTopLevelAwait }, outputOptions); if (banner) magicString.prepend(banner); if (footer) magicString.append(footer); return { chunk: this, magicString, preliminaryFileName, preliminarySourcemapFileName, usedModules }; } addImplicitlyLoadedBeforeFromModule(baseModule) { const { chunkByModule, implicitlyLoadedBefore } = this; for (const module of baseModule.implicitlyLoadedBefore) { const chunk = chunkByModule.get(module); if (chunk && chunk !== this) { implicitlyLoadedBefore.add(chunk); } } } addNecessaryImportsForFacades() { for (const [module, variables] of this.includedReexportsByModule) { if (this.includedNamespaces.has(module)) { for (const variable of variables) { this.imports.add(variable); } } } } assignFacadeName({ fileName, name }, facadedModule, preservePath) { if (fileName) { this.fileName = fileName; } else { this.name = this.outputOptions.sanitizeFileName(name || (preservePath ? this.getPreserveModulesChunkNameFromModule(facadedModule) : getChunkNameFromModule(facadedModule))); } } checkCircularDependencyImport(variable, importingModule) { const variableModule = variable.module; if (variableModule instanceof Module) { const exportChunk = this.chunkByModule.get(variableModule); let alternativeReexportModule; do { alternativeReexportModule = importingModule.alternativeReexportModules.get(variable); if (alternativeReexportModule) { const exportingChunk = this.chunkByModule.get(alternativeReexportModule); if (exportingChunk !== exportChunk) { this.inputOptions.onLog(LOGLEVEL_WARN, logCyclicCrossChunkReexport( // Namespaces do not have an export name variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules)); } importingModule = alternativeReexportModule; } } while (alternativeReexportModule); } } ensureReexportsAreAvailableForModule(module) { const includedReexports = []; const map = module.getExportNamesByVariable(); for (const exportedVariable of map.keys()) { const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable; const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable; this.checkCircularDependencyImport(importedVariable, module); // When preserving modules, we do not create namespace objects but directly // use the actual namespaces, which would be broken by this logic. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) { const exportingModule = importedVariable.module; if (exportingModule instanceof Module) { const chunk = this.chunkByModule.get(exportingModule); if (chunk && chunk !== this) { chunk.exports.add(importedVariable); includedReexports.push(importedVariable); if (isSynthetic) { this.imports.add(importedVariable); } } } } } if (includedReexports.length > 0) { this.includedReexportsByModule.set(module, includedReexports); } } generateVariableName() { if (this.manualChunkAlias) { return this.manualChunkAlias; } const moduleForNaming = this.entryModules[0] || this.implicitEntryModules[0] || this.dynamicEntryModules[0] || this.orderedModules[this.orderedModules.length - 1]; if (moduleForNaming) { return getChunkNameFromModule(moduleForNaming); } return 'chunk'; } getChunkExportDeclarations(format) { const exports = []; for (const exportName of this.getExportNames()) { if (exportName[0] === '*') continue; const variable = this.exportsByName.get(exportName); if (!(variable instanceof SyntheticNamedExportVariable)) { const module = variable.module; if (module) { const chunk = this.chunkByModule.get(module); if (chunk !== this) { if (!chunk || format !== 'es') { continue; } const chunkDep = this.renderedDependencies.get(chunk); if (!chunkDep) { continue; } const { imports, reexports } = chunkDep; const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName); const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported); if (!isImported) { continue; } } } } let expression = null; let hoisted = false; let local = variable.getName(this.snippets.getPropertyAccess); if (variable instanceof LocalVariable) { for (const declaration of variable.declarations) { if (declaration.parent instanceof FunctionDeclaration || (declaration instanceof ExportDefaultDeclaration && declaration.declaration instanceof FunctionDeclaration)) { hoisted = true; break; } } } else if (variable instanceof SyntheticNamedExportVariable) { expression = local; if (format === 'es') { local = variable.renderName; } } exports.push({ exported: exportName, expression, hoisted, local }); } return exports; } getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) { const dependencies = new Set(); const deconflictedDefault = new Set(); const deconflictedNamespace = new Set(); for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) { if (addNonNamespacesAndInteropHelpers || variable.isNamespace) { const module = variable.module; if (module instanceof ExternalModule) { const chunk = this.externalChunkByModule.get(module); dependencies.add(chunk); if (addNonNamespacesAndInteropHelpers) { if (variable.name === 'default') { if (defaultInteropHelpersByInteropType[interop(module.id)]) { deconflictedDefault.add(chunk); } } else if (variable.name === '*' && namespaceInteropHelpersByInteropType[interop(module.id)]) { deconflictedNamespace.add(chunk); } } } else { const chunk = this.chunkByModule.get(module); if (chunk !== this) { dependencies.add(chunk); if (addNonNamespacesAndInteropHelpers && chunk.exportMode === 'default' && variable.isNamespace) { deconflictedNamespace.add(chunk); } } } } } if (addDependenciesWithoutBindings) { for (const dependency of this.dependencies) { dependencies.add(dependency); } } return { deconflictedDefault, deconflictedNamespace, dependencies }; } getDynamicDependencies() { return this.getIncludedDynamicImports() .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk || resolvedDynamicImport.chunk || resolvedDynamicImport.externalChunk || resolvedDynamicImport.resolution) .filter((resolution) => resolution !== this && (resolution instanceof Chunk || resolution instanceof ExternalChunk)); } getDynamicImportStringAndAssertions(resolution, fileName) { if (resolution instanceof ExternalModule) { const chunk = this.externalChunkByModule.get(resolution); return [`'${chunk.getImportPath(fileName)}'`, chunk.getImportAssertions(this.snippets)]; } return [ resolution || '', (this.outputOptions.format === 'es' && this.outputOptions.externalImportAssertions) || null ]; } getFallbackChunkName() { if (this.manualChunkAlias) { return this.manualChunkAlias; } if (this.dynamicName) { return this.dynamicName; } if (this.fileName) { return getAliasName(this.fileName); } return getAliasName(this.orderedModules[this.orderedModules.length - 1].id); } getImportSpecifiers() { const { interop } = this.outputOptions; const importsByDependency = new Map(); for (const variable of this.imports) { const module = variable.module; let dependency; let imported; if (module instanceof ExternalModule) { dependency = this.externalChunkByModule.get(module); imported = variable.name; if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') { return error$4(logUnexpectedNamedImport(module.id, imported, false)); } } else { dependency = this.chunkByModule.get(module); imported = dependency.getVariableExportName(variable); } getOrCreate(importsByDependency, dependency, getNewArray).push({ imported, local: variable.getName(this.snippets.getPropertyAccess) }); } return importsByDependency; } getIncludedDynamicImports() { if (this.includedDynamicImports) { return this.includedDynamicImports; } const includedDynamicImports = []; for (const module of this.orderedModules) { for (const { node, resolution } of module.dynamicImports) { if (!node.included) { continue; } includedDynamicImports.push(resolution instanceof Module ? { chunk: this.chunkByModule.get(resolution), externalChunk: null, facadeChunk: this.facadeChunkByModule.get(resolution), node, resolution } : resolution instanceof ExternalModule ? { chunk: null, externalChunk: this.externalChunkByModule.get(resolution), facadeChunk: null, node, resolution } : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution }); } } return (this.includedDynamicImports = includedDynamicImports); } getPreRenderedChunkInfo() { if (this.preRenderedChunkInfo) { return this.preRenderedChunkInfo; } const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this; return (this.preRenderedChunkInfo = { exports: this.getExportNames(), facadeModuleId: facadeModule && facadeModule.id, isDynamicEntry: dynamicEntryModules.length > 0, isEntry: !!facadeModule?.info.isEntry, isImplicitEntry: implicitEntryModules.length > 0, moduleIds: orderedModules.map(({ id }) => id), name: this.getChunkName(), type: 'chunk' }); } getPreserveModulesChunkNameFromModule(module) { const predefinedChunkName = getPredefinedChunkNameFromModule(module); if (predefinedChunkName) return predefinedChunkName; const { preserveModulesRoot, sanitizeFileName } = this.outputOptions; const sanitizedId = sanitizeFileName(normalize$1(module.id.split(QUERY_HASH_REGEX, 1)[0])); const extensionName = extname(sanitizedId); const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName) ? sanitizedId.slice(0, -extensionName.length) : sanitizedId; if (isAbsolute$2(idWithoutExtension)) { return preserveModulesRoot && resolve$4(idWithoutExtension).startsWith(preserveModulesRoot) ? idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '') : relative$1(this.inputBase, idWithoutExtension); } else { return `_virtual/${basename$1(idWithoutExtension)}`; } } getReexportSpecifiers() { const { externalLiveBindings, interop } = this.outputOptions; const reexportSpecifiers = new Map(); for (let exportName of this.getExportNames()) { let dependency; let imported; let needsLiveBinding = false; if (exportName[0] === '*') { const id = exportName.slice(1); if (interop(id) === 'defaultOnly') { this.inputOptions.onLog(LOGLEVEL_WARN, logUnexpectedNamespaceReexport(id)); } needsLiveBinding = externalLiveBindings; dependency = this.externalChunkByModule.get(this.modulesById.get(id)); imported = exportName = '*'; } else { const variable = this.exportsByName.get(exportName); if (variable instanceof SyntheticNamedExportVariable) continue; const module = variable.module; if (module instanceof Module) { dependency = this.chunkByModule.get(module); if (dependency === this) continue; imported = dependency.getVariableExportName(variable); needsLiveBinding = variable.isReassigned; } else { dependency = this.externalChunkByModule.get(module); imported = variable.name; if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') { return error$4(logUnexpectedNamedImport(module.id, imported, true)); } needsLiveBinding = externalLiveBindings && (imported !== 'default' || isDefaultAProperty(interop(module.id), true)); } } getOrCreate(reexportSpecifiers, dependency, getNewArray).push({ imported, needsLiveBinding, reexported: exportName }); } return reexportSpecifiers; } getReferencedFiles() { const referencedFiles = new Set(); for (const module of this.orderedModules) { for (const meta of module.importMetas) { const fileName = meta.getReferencedFileName(this.pluginDriver); if (fileName) { referencedFiles.add(fileName); } } } return [...referencedFiles]; } getRenderedDependencies() { if (this.renderedDependencies) { return this.renderedDependencies; } const importSpecifiers = this.getImportSpecifiers(); const reexportSpecifiers = this.getReexportSpecifiers(); const renderedDependencies = new Map(); const fileName = this.getFileName(); for (const dep of this.dependencies) { const imports = importSpecifiers.get(dep) || null; const reexports = reexportSpecifiers.get(dep) || null; const namedExportsMode = dep instanceof ExternalChunk || dep.exportMode !== 'default'; const importPath = dep.getImportPath(fileName); renderedDependencies.set(dep, { assertions: dep instanceof ExternalChunk ? dep.getImportAssertions(this.snippets) : null, defaultVariableName: dep.defaultVariableName, globalName: dep instanceof ExternalChunk && (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') && getGlobalName(dep, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog), importPath, imports, isChunk: dep instanceof Chunk, name: dep.variableName, namedExportsMode, namespaceVariableName: dep.namespaceVariableName, reexports }); } return (this.renderedDependencies = renderedDependencies); } inlineChunkDependencies(chunk) { for (const dep of chunk.dependencies) { if (this.dependencies.has(dep)) continue; this.dependencies.add(dep); if (dep instanceof Chunk) { this.inlineChunkDependencies(dep); } } } // This method changes properties on the AST before rendering and must not be async renderModules(fileName) { const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onLog }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this; const { compact, dynamicImportFunction, format, freeze, namespaceToStringTag } = outputOptions; const { _, cnst, n } = snippets; this.setDynamicImportResolutions(fileName); this.setImportMetaResolutions(fileName); this.setIdentifierRenderResolutions(); const magicString = new Bundle$1({ separator: `${n}${n}` }); const indent = getIndentString(orderedModules, outputOptions); const usedModules = []; let hoistedSource = ''; const accessedGlobals = new Set(); const renderedModuleSources = new Map(); const renderOptions = { accessedDocumentCurrentScript: false, dynamicImportFunction, exportNamesByVariable, format, freeze, indent, namespaceToStringTag, pluginDriver, snippets, useOriginalName: null }; let usesTopLevelAwait = false; for (const module of orderedModules) { let renderedLength = 0; let source; if (module.isIncluded() || includedNamespaces.has(module)) { const rendered = module.render(renderOptions); if (!renderOptions.accessedDocumentCurrentScript && formatsMaybeAccessDocumentCurrentScript.includes(format)) { // eslint-disable-next-line unicorn/consistent-destructuring this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT); } renderOptions.accessedDocumentCurrentScript = false; ({ source } = rendered); usesTopLevelAwait || (usesTopLevelAwait = rendered.usesTopLevelAwait); renderedLength = source.length(); if (renderedLength) { if (compact && source.lastLine().includes('//')) source.append('\n'); renderedModuleSources.set(module, source); magicString.addSource(source); usedModules.push(module); } const namespace = module.namespace; if (includedNamespaces.has(module)) { const rendered = namespace.renderBlock(renderOptions); if (namespace.renderFirst()) hoistedSource += n + rendered; else magicString.addSource(new MagicString$3(rendered)); } const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope); if (accessedGlobalVariables) { for (const name of accessedGlobalVariables) { accessedGlobals.add(name); } } } const { renderedExports, removedExports } = module.getRenderedExports(); renderedModules[module.id] = { get code() { return source?.toString() ?? null; }, originalLength: module.originalCode.length, removedExports, renderedExports, renderedLength }; } if (hoistedSource) magicString.prepend(hoistedSource + n + n); // eslint-disable-next-line unicorn/consistent-destructuring if (this.needsExportsShim) { magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`); } const renderedSource = compact ? magicString : magicString.trim(); if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) { onLog(LOGLEVEL_WARN, logEmptyChunk(this.getChunkName())); } return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait }; } setDynamicImportResolutions(fileName) { const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this; for (const resolvedDynamicImport of this.getIncludedDynamicImports()) { if (resolvedDynamicImport.chunk) { const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport; if (chunk === this) { node.setInternalResolution(resolution.namespace); } else { node.setExternalResolution((facadeChunk || chunk).exportMode, resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null); } } else { const { node, resolution } = resolvedDynamicImport; const [resolutionString, assertions] = this.getDynamicImportStringAndAssertions(resolution, fileName); node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, assertions); } } } setIdentifierRenderResolutions() { const { format, interop, namespaceToStringTag, preserveModules, externalLiveBindings } = this.outputOptions; const syntheticExports = new Set(); for (const exportName of this.getExportNames()) { const exportVariable = this.exportsByName.get(exportName); if (format !== 'es' && format !== 'system' && exportVariable.isReassigned && !exportVariable.isId) { exportVariable.setRenderNames('exports', exportName); } else if (exportVariable instanceof SyntheticNamedExportVariable) { syntheticExports.add(exportVariable); } else { exportVariable.setRenderNames(null, null); } } for (const module of this.orderedModules) { if (module.needsExportShim) { this.needsExportsShim = true; break; } } const usedNames = new Set(['Object', 'Promise']); if (this.needsExportsShim) { usedNames.add(MISSING_EXPORT_SHIM_VARIABLE); } if (namespaceToStringTag) { usedNames.add('Symbol'); } switch (format) { case 'system': { usedNames.add('module').add('exports'); break; } case 'es': { break; } case 'cjs': { usedNames.add('module').add('require').add('__filename').add('__dirname'); } // fallthrough default: { usedNames.add('exports'); for (const helper of HELPER_NAMES) { usedNames.add(helper); } } } deconflictChunk(this.orderedModules, this.getDependenciesToBeDeconflicted(format !== 'es' && format !== 'system', format === 'amd' || format === 'umd' || format === 'iife', interop), this.imports, usedNames, format, interop, preserveModules, externalLiveBindings, this.chunkByModule, this.externalChunkByModule, syntheticExports, this.exportNamesByVariable, this.accessedGlobalsByScope, this.includedNamespaces); } setImportMetaResolutions(fileName) { const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this; for (const module of orderedModules) { for (const importMeta of module.importMetas) { importMeta.setResolution(format, accessedGlobalsByScope, fileName); } if (includedNamespaces.has(module)) { module.namespace.prepare(accessedGlobalsByScope); } } } setUpChunkImportsAndExportsForModule(module) { const moduleImports = new Set(module.includedImports); // when we are not preserving modules, we need to make all namespace variables available for // rendering the namespace object if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) { const memberVariables = module.namespace.getMemberVariables(); for (const variable of Object.values(memberVariables)) { if (variable.included) { moduleImports.add(variable); } } } for (let variable of moduleImports) { if (variable instanceof ExportDefaultVariable) { variable = variable.getOriginalVariable(); } if (variable instanceof SyntheticNamedExportVariable) { variable = variable.getBaseVariable(); } const chunk = this.chunkByModule.get(variable.module); if (chunk !== this) { this.imports.add(variable); if (variable.module instanceof Module) { this.checkCircularDependencyImport(variable, module); // When preserving modules, we do not create namespace objects but directly // use the actual namespaces, which would be broken by this logic. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) { chunk.exports.add(variable); } } } } if (this.includedNamespaces.has(module) || (module.info.isEntry && module.preserveSignature !== false) || module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) { this.ensureReexportsAreAvailableForModule(module); } for (const { node, resolution } of module.dynamicImports) { if (node.included && resolution instanceof Module && this.chunkByModule.get(resolution) === this && !this.includedNamespaces.has(resolution)) { this.includedNamespaces.add(resolution); this.ensureReexportsAreAvailableForModule(resolution); } } } }; function getChunkNameFromModule(module) { return getPredefinedChunkNameFromModule(module) ?? getAliasName(module.id); } function getPredefinedChunkNameFromModule(module) { return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name); } function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) { const importedBindingsPerDependency = {}; for (const [dependency, declaration] of renderedDependencies) { const specifiers = new Set(); if (declaration.imports) { for (const { imported } of declaration.imports) { specifiers.add(imported); } } if (declaration.reexports) { for (const { imported } of declaration.reexports) { specifiers.add(imported); } } importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers]; } return importedBindingsPerDependency; } const QUERY_HASH_REGEX = /[#?]/; const resolveFileName = (dependency) => dependency.getFileName(); /** * Concatenate a number of iterables to a new iterable without fully evaluating * their iterators. Useful when e.g. working with large sets or lists and when * there is a chance that the iterators will not be fully exhausted. */ function* concatLazy(iterables) { for (const iterable of iterables) { yield* iterable; } } /** * At its core, the algorithm first starts from each static or dynamic entry * point and then assigns that entry point to all modules than can be reached * via static imports. We call this the *dependent entry points* of that * module. * * Then we group all modules with the same dependent entry points into chunks * as those modules will always be loaded together. * * One non-trivial optimization we can apply is that dynamic entries are * different from static entries in so far as when a dynamic import occurs, * some * modules are already in memory. If some of these modules are also * dependencies * of the dynamic entry, then it does not make sense to create a separate chunk * for them. Instead, the dynamic import target can load them from the * importing * chunk. * * With regard to chunking, if B is implicitly loaded after A, then this can be * handled the same way as if there was a dynamic import A => B. * * Example: * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B. * Then the initial algorithm would assign A into the A chunk, C into the C * chunk and B into the AC chunk, i.e. the chunk with the dependent entry * points * A and C. * However we know that C can only be loaded from A, so A and its dependency B * must already be in memory when C is loaded. So it is enough to create only * two chunks A containing [AB] and C containing [C]. * * So we do not assign the dynamic entry C as dependent entry point to modules * that are already loaded. * * In a more complex example, let us assume that we have entry points X and Y. * Further, let us assume * X -> A, X -> B, X -> C, * Y -> A, Y -> B, * A => D, * D -> B, D -> C * So without dynamic import optimization, the dependent entry points are * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y, * so we would for now create six chunks. * * Now D is loaded only after A is loaded. But A is loaded if either X is * loaded * or Y is loaded. So the modules that are already in memory when D is loaded * are the intersection of all modules that X depends on with all modules that * Y * depends on, which in this case are the modules A and B. * We could also say they are all modules that have both X and Y as dependent * entry points. * * So we can remove D as dependent entry point from A and B, which means they * both now have only XY as dependent entry points and can be merged into the * same chunk. * * Now let us extend this to the most general case where we have several * dynamic * importers for one dynamic entry point. * * In the most general form, it works like this: * For each dynamic entry point, we have a number of dynamic importers, which * are the modules importing it. Using the previous ideas, we can determine * the modules already in memory for each dynamic importer by looking for all * modules that have all the dependent entry points of the dynamic importer as * dependent entry points. * So the modules that are guaranteed to be in memory when the dynamic entry * point is loaded are the intersection of the modules already in memory for * each dynamic importer. * * Assuming that A => D and B => D and A has dependent entry points XY and B * has * dependent entry points YZ, then the modules guaranteed to be in memory are * all modules that have at least XYZ as dependent entry points. * We call XYZ the *dynamically dependent entry points* of D. * * Now there is one last case to consider: If one of the dynamically dependent * entries is itself a dynamic entry, then any module is in memory that either * is a dependency of that dynamic entry or again has the dynamic dependent * entries of that dynamic entry as dependent entry points. * * A naive algorithm for this proved to be costly as it contained an O(n^3) * complexity with regard to dynamic entries that blew up for very large * projects. * * If we have an efficient way to do Set operations, an alternative approach * would be to instead collect already loaded modules per dynamic entry. And as * all chunks from the initial grouping would behave the same, we can instead * collect already loaded chunks for a performance improvement. * * To do that efficiently, need * - a Map of dynamic imports per dynamic entry, which contains all dynamic * imports that can be triggered by a dynamic entry * - a Map of static dependencies per entry * - a Map of already loaded chunks per entry that we initially populate with * empty Sets for static entries and Sets containing all entries for dynamic * entries * * For efficient operations, we assign each entry a numerical index and * represent Sets of Chunks as BigInt values where each chunk corresponds to a * bit index. Then thw last two maps can be represented as arrays of BigInt * values. * * Then we iterate through each dynamic entry. We set the already loaded modules * to the intersection of the previously already loaded modules with the union * of the already loaded modules of that chunk with its static dependencies. * * If the already loaded modules changed, then we use the Map of dynamic imports * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put * them back into the iteration. As an additional optimization, we note for * each dynamic entry which dynamic dependent entries have changed and only * intersect those entries again on subsequent interations. * * Then we remove the dynamic entries from the list of dependent entries for * those chunks that are already loaded for that dynamic entry and create * another round of chunks. */ function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log) { const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry); const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry } = analyzeModuleGraph(entries); // Each chunk is identified by its position in this array const initialChunks = getChunksFromDependentEntries(getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks)); // This mutates initialChunks but also clears // dynamicallyDependentEntriesByDynamicEntry as side effect removeUnnecessaryDependentEntries(initialChunks, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries); chunkDefinitions.push(...getOptimizedChunks(getChunksFromDependentEntries(initialChunks), allEntries.length, minChunkSize, log).map(({ modules }) => ({ alias: null, modules }))); return chunkDefinitions; } function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry) { const chunkDefinitions = []; const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys()); const manualChunkModulesByAlias = Object.create(null); for (const [entry, alias] of manualChunkAliasByEntry) { addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] || (manualChunkModulesByAlias[alias] = [])), modulesInManualChunks); } for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) { chunkDefinitions.push({ alias, modules }); } return { chunkDefinitions, modulesInManualChunks }; } function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) { const modulesToHandle = new Set([entry]); for (const module of modulesToHandle) { modulesInManualChunks.add(module); manualChunkModules.push(module); for (const dependency of module.dependencies) { if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) { modulesToHandle.add(dependency); } } } } function analyzeModuleGraph(entries) { const dynamicEntryModules = new Set(); const dependentEntriesByModule = new Map(); const dynamicImportModulesByEntry = []; const allEntriesSet = new Set(entries); let entryIndex = 0; for (const currentEntry of allEntriesSet) { const dynamicImportsForCurrentEntry = new Set(); dynamicImportModulesByEntry.push(dynamicImportsForCurrentEntry); const modulesToHandle = new Set([currentEntry]); for (const module of modulesToHandle) { getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex); for (const dependency of module.getDependenciesToBeIncluded()) { if (!(dependency instanceof ExternalModule)) { modulesToHandle.add(dependency); } } for (const { resolution } of module.dynamicImports) { if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0 && !allEntriesSet.has(resolution)) { dynamicEntryModules.add(resolution); allEntriesSet.add(resolution); dynamicImportsForCurrentEntry.add(resolution); } } for (const dependency of module.implicitlyLoadedBefore) { if (!allEntriesSet.has(dependency)) { dynamicEntryModules.add(dependency); allEntriesSet.add(dependency); } } } entryIndex++; } const allEntries = [...allEntriesSet]; const { dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry); return { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries), dynamicImportsByEntry }; } function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry) { const entryIndexByModule = new Map(); const dynamicEntries = new Set(); for (const [entryIndex, entry] of allEntries.entries()) { entryIndexByModule.set(entry, entryIndex); if (dynamicEntryModules.has(entry)) { dynamicEntries.add(entryIndex); } } const dynamicImportsByEntry = []; for (const dynamicImportModules of dynamicImportModulesByEntry) { const dynamicImports = new Set(); for (const dynamicEntry of dynamicImportModules) { dynamicImports.add(entryIndexByModule.get(dynamicEntry)); } dynamicImportsByEntry.push(dynamicImports); } return { dynamicEntries, dynamicImportsByEntry }; } function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries) { const dynamicallyDependentEntriesByDynamicEntry = new Map(); for (const dynamicEntryIndex of dynamicEntries) { const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet)); const dynamicEntry = allEntries[dynamicEntryIndex]; for (const importer of concatLazy([ dynamicEntry.includedDynamicImporters, dynamicEntry.implicitlyLoadedAfter ])) { for (const entry of dependentEntriesByModule.get(importer)) { dynamicallyDependentEntries.add(entry); } } } return dynamicallyDependentEntriesByDynamicEntry; } function getChunksFromDependentEntries(modulesWithDependentEntries) { var _a; const chunkModules = Object.create(null); for (const { dependentEntries, modules } of modulesWithDependentEntries) { let chunkSignature = 0n; for (const entryIndex of dependentEntries) { chunkSignature |= 1n << BigInt(entryIndex); } (chunkModules[_a = String(chunkSignature)] || (chunkModules[_a] = { dependentEntries: new Set(dependentEntries), modules: [] })).modules.push(...modules); } return Object.values(chunkModules); } function* getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks) { for (const [module, dependentEntries] of dependentEntriesByModule) { if (!modulesInManualChunks.has(module)) { yield { dependentEntries, modules: [module] }; } } } /** * This removes all unnecessary dynamic entries from the dependenEntries in its * first argument. It will also consume its second argument, so if * dynamicallyDependentEntriesByDynamicEntry is ever needed after this, we * should make a copy. */ function removeUnnecessaryDependentEntries(chunks, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) { // The indices correspond to the indices in allEntries. The chunks correspond // to bits in the bigint values where chunk 0 is the lowest bit. const staticDependenciesPerEntry = allEntries.map(() => 0n); const alreadyLoadedChunksPerEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n); // This toggles the bits for each chunk that is a dependency of an entry let chunkMask = 1n; for (const { dependentEntries } of chunks) { for (const entryIndex of dependentEntries) { staticDependenciesPerEntry[entryIndex] |= chunkMask; } chunkMask <<= 1n; } // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry. // If we no longer want this, we should make a copy here. const updatedDynamicallyDependentEntriesByDynamicEntry = dynamicallyDependentEntriesByDynamicEntry; for (const [dynamicEntryIndex, updatedDynamicallyDependentEntries] of updatedDynamicallyDependentEntriesByDynamicEntry) { updatedDynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex); const previousLoadedModules = alreadyLoadedChunksPerEntry[dynamicEntryIndex]; let newLoadedModules = previousLoadedModules; for (const entryIndex of updatedDynamicallyDependentEntries) { newLoadedModules &= staticDependenciesPerEntry[entryIndex] | alreadyLoadedChunksPerEntry[entryIndex]; } if (newLoadedModules !== previousLoadedModules) { alreadyLoadedChunksPerEntry[dynamicEntryIndex] = newLoadedModules; for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) { getOrCreate(updatedDynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex); } } } // Remove entries from dependent entries if a chunk is already loaded without // that entry. chunkMask = 1n; for (const { dependentEntries } of chunks) { for (const entryIndex of dependentEntries) { if ((alreadyLoadedChunksPerEntry[entryIndex] & chunkMask) === chunkMask) { dependentEntries.delete(entryIndex); } } chunkMask <<= 1n; } } /** * This function tries to get rid of small chunks by merging them with other * chunks. * * We can only merge chunks safely if after the merge, loading any entry point * in any allowed order will not trigger side effects that should not have been * triggered. While side effects are usually things like global function calls, * global variable mutations or potentially thrown errors, details do not * matter here, and we just discern chunks without side effects (pure chunks) * from other chunks. * * As a first step, we assign each pre-generated chunk with side effects a * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded. * * Now to determine the side effects of loading a chunk, one also has to take * the side effects of its dependencies into account. So if A depends on B * (A -> B) and both have side effects, loading A triggers effects AB. * * Now from the previous step we know that each chunk is uniquely determine by * the entry points that depend on it and cause it to load, which we will call * its dependent entry points. * * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY. * Starting from that idea, we can determine a set of chunks—and thus a set * of side effects—that must have been triggered if a certain chunk has been * loaded. Basically, it is the intersection of all chunks loaded by the * dependent entry points of a given chunk. We call the corresponding side * effects the correlated side effects of that chunk. * * Example: * X -> ABC, Y -> ADE, A-> F, B -> D * Then taking dependencies into account, X -> ABCDF, Y -> ADEF * The intersection is ADF. So we know that when A is loaded, D and F must also * be in memory even though neither D nor A is a dependency of the other. * If all have side effects, we call ADF the correlated side effects of A. The * correlated side effects need to remain constant when merging chunks. * * In contrast, we have the dependency side effects of A, which represents * the side effects we trigger if we directly load A. In this example, the * dependency side effects are AF. * For entry chunks, dependency and correlated side effects are the same. * * With these concepts, merging chunks is allowed if the correlated side * effects of each entry do not change. Thus, we are allowed to merge two * chunks if * * a) the dependency side effects of each chunk are a subset of the correlated * side effects of the other chunk, so no additional side effects are * triggered for any entry, or * b) The dependent entry points of chunk A are a subset of the dependent entry * points of chunk B while the dependency side effects of A are a subset of * the correlated side effects of B. Because in that scenario, whenever A is * loaded, B is loaded as well. But there are cases when B is loaded where A * is not loaded. So if we merge the chunks, all dependency side effects of * A will be added to the correlated side effects of B, and as the latter is * not allowed to change, the former need to be a subset of the latter. * * Another consideration when merging small chunks into other chunks is to * avoid * that too much additional code is loaded. This is achieved when the dependent * entries of the small chunk are a subset of the dependent entries of the * other * chunk. Because then when the small chunk is loaded, the other chunk was * loaded/in memory anyway, so at most when the other chunk is loaded, the * additional size of the small chunk is loaded unnecessarily. * * So the algorithm performs merges in two passes: * * 1. First we try to merge small chunks A only into other chunks B if the * dependent entries of A are a subset of the dependent entries of B and the * dependency side effects of A are a subset of the correlated side effects * of B. * 2. Only then for all remaining small chunks, we look for arbitrary merges * following the rule (a), starting with the smallest chunks to look for * possible merge targets. */ function getOptimizedChunks(initialChunks, numberOfEntries, minChunkSize, log) { timeStart('optimize chunks', 3); const chunkPartition = getPartitionedChunks(initialChunks, numberOfEntries, minChunkSize); if (!chunkPartition) { timeEnd('optimize chunks', 3); return initialChunks; // the actual modules } minChunkSize > 1 && log('info', logOptimizeChunkStatus(initialChunks.length, chunkPartition.small.size, 'Initially')); mergeChunks(chunkPartition, minChunkSize); minChunkSize > 1 && log('info', logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks')); timeEnd('optimize chunks', 3); return [...chunkPartition.small, ...chunkPartition.big]; } function getPartitionedChunks(initialChunks, numberOfEntries, minChunkSize) { const smallChunks = []; const bigChunks = []; const chunkByModule = new Map(); const sizeByAtom = []; let sideEffectAtoms = 0n; let containedAtoms = 1n; for (const { dependentEntries, modules } of initialChunks) { const chunkDescription = { containedAtoms, correlatedAtoms: 0n, dependencies: new Set(), dependentChunks: new Set(), dependentEntries, modules, pure: true, size: 0 }; let size = 0; let pure = true; for (const module of modules) { chunkByModule.set(module, chunkDescription); // Unfortunately, we cannot take tree-shaking into account here because // rendering did not happen yet, but we can detect empty modules if (module.isIncluded()) { pure && (pure = !module.hasEffects()); // we use a trivial size for the default minChunkSize to improve // performance size += minChunkSize > 1 ? module.estimateSize() : 1; } } chunkDescription.pure = pure; chunkDescription.size = size; sizeByAtom.push(size); if (!pure) { sideEffectAtoms |= containedAtoms; } (size < minChunkSize ? smallChunks : bigChunks).push(chunkDescription); containedAtoms <<= 1n; } // If there are no small chunks, we will not optimize if (smallChunks.length === 0) { return null; } sideEffectAtoms |= addChunkDependenciesAndAtomsAndGetSideEffectAtoms([bigChunks, smallChunks], chunkByModule, numberOfEntries, containedAtoms); return { big: new Set(bigChunks), sideEffectAtoms, sizeByAtom, small: new Set(smallChunks) }; } function mergeChunks(chunkPartition, minChunkSize) { const { small } = chunkPartition; for (const mergedChunk of small) { const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition, // In the default case, we do not accept size increases minChunkSize <= 1 ? 1 : Infinity); if (bestTargetChunk) { const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk; small.delete(mergedChunk); getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk); bestTargetChunk.modules.push(...modules); bestTargetChunk.size += size; bestTargetChunk.pure && (bestTargetChunk.pure = pure); const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk; bestTargetChunk.correlatedAtoms &= correlatedAtoms; bestTargetChunk.containedAtoms |= containedAtoms; for (const entry of mergedChunk.dependentEntries) { dependentEntries.add(entry); } for (const dependency of mergedChunk.dependencies) { dependencies.add(dependency); dependency.dependentChunks.delete(mergedChunk); dependency.dependentChunks.add(bestTargetChunk); } for (const dependentChunk of mergedChunk.dependentChunks) { dependentChunks.add(dependentChunk); dependentChunk.dependencies.delete(mergedChunk); dependentChunk.dependencies.add(bestTargetChunk); } dependencies.delete(bestTargetChunk); dependentChunks.delete(bestTargetChunk); getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk); } } } function addChunkDependenciesAndAtomsAndGetSideEffectAtoms(chunkLists, chunkByModule, numberOfEntries, nextAtomSignature) { const signatureByExternalModule = new Map(); let sideEffectAtoms = 0n; const atomsByEntry = []; for (let index = 0; index < numberOfEntries; index++) { atomsByEntry.push(0n); } for (const chunks of chunkLists) { chunks.sort(compareChunkSize); for (const chunk of chunks) { const { dependencies, dependentEntries, modules } = chunk; for (const module of modules) { for (const dependency of module.getDependenciesToBeIncluded()) { if (dependency instanceof ExternalModule) { if (dependency.info.moduleSideEffects) { chunk.containedAtoms |= getOrCreate(signatureByExternalModule, dependency, () => { const signature = nextAtomSignature; nextAtomSignature <<= 1n; sideEffectAtoms |= signature; return signature; }); } } else { const dependencyChunk = chunkByModule.get(dependency); if (dependencyChunk && dependencyChunk !== chunk) { dependencies.add(dependencyChunk); dependencyChunk.dependentChunks.add(chunk); } } } } const { containedAtoms } = chunk; for (const entryIndex of dependentEntries) { atomsByEntry[entryIndex] |= containedAtoms; } } } for (const chunks of chunkLists) { for (const chunk of chunks) { const { dependentEntries } = chunk; // Correlated atoms are the intersection of all entry atoms chunk.correlatedAtoms = -1n; for (const entryIndex of dependentEntries) { chunk.correlatedAtoms &= atomsByEntry[entryIndex]; } } } return sideEffectAtoms; } function findBestMergeTarget(mergedChunk, { big, sideEffectAtoms, sizeByAtom, small }, smallestAdditionalSize) { let bestTargetChunk = null; // In the default case, we do not accept size increases for (const targetChunk of concatLazy([small, big])) { if (mergedChunk === targetChunk) continue; const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom); if (additionalSizeAfterMerge < smallestAdditionalSize) { bestTargetChunk = targetChunk; if (additionalSizeAfterMerge === 0) break; smallestAdditionalSize = additionalSizeAfterMerge; } } return bestTargetChunk; } function getChunksInPartition(chunk, minChunkSize, chunkPartition) { return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big; } function compareChunkSize({ size: sizeA }, { size: sizeB }) { return sizeA - sizeB; } /** * Determine the additional unused code size that would be added by merging the * two chunks. This is not an exact measurement but rather an upper bound. If * the merge produces cycles or adds non-correlated side effects, `Infinity` * is returned. * Merging will not produce cycles if none of the direct non-merged * dependencies of a chunk have the other chunk as a transitive dependency. */ function getAdditionalSizeAfterMerge(mergedChunk, targetChunk, // The maximum additional unused code size allowed to be added by the merge, // taking dependencies into account, needs to be below this number currentAdditionalSize, sideEffectAtoms, sizeByAtom) { const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom); return firstSize < currentAdditionalSize ? firstSize + getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom) : Infinity; } function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) { const { correlatedAtoms } = dependencyChunk; let dependencyAtoms = dependentChunk.containedAtoms; const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms; if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) { return Infinity; } const chunksToCheck = new Set(dependentChunk.dependencies); for (const { dependencies, containedAtoms } of chunksToCheck) { dependencyAtoms |= containedAtoms; const containedSideEffects = containedAtoms & sideEffectAtoms; if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) { return Infinity; } for (const dependency of dependencies) { if (dependency === dependencyChunk) { return Infinity; } chunksToCheck.add(dependency); } } return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom); } function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) { let size = 0; let atomIndex = 0; let atomSignature = 1n; const { length } = sizeByAtom; for (; atomIndex < length; atomIndex++) { if ((atoms & atomSignature) === atomSignature) { size += sizeByAtom[atomIndex]; } atomSignature <<= 1n; if (size >= currentAdditionalSize) { return Infinity; } } return size; } // ported from https://github.com/substack/node-commondir function commondir$1(files) { if (files.length === 0) return '/'; if (files.length === 1) return dirname$1(files[0]); const commonSegments = files.slice(1).reduce((commonSegments, file) => { const pathSegements = file.split(/\/+|\\+/); let index; for (index = 0; commonSegments[index] === pathSegements[index] && index < Math.min(commonSegments.length, pathSegements.length); index++) ; return commonSegments.slice(0, index); }, files[0].split(/\/+|\\+/)); // Windows correctly handles paths with forward-slashes return commonSegments.length > 1 ? commonSegments.join('/') : '/'; } const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1; function sortByExecutionOrder(units) { units.sort(compareExecIndex); } function analyseModuleExecution(entryModules) { let nextExecIndex = 0; const cyclePaths = []; const analysedModules = new Set(); const dynamicImports = new Set(); const parents = new Map(); const orderedModules = []; const analyseModule = (module) => { if (module instanceof Module) { for (const dependency of module.dependencies) { if (parents.has(dependency)) { if (!analysedModules.has(dependency)) { cyclePaths.push(getCyclePath(dependency, module, parents)); } continue; } parents.set(dependency, module); analyseModule(dependency); } for (const dependency of module.implicitlyLoadedBefore) { dynamicImports.add(dependency); } for (const { resolution } of module.dynamicImports) { if (resolution instanceof Module) { dynamicImports.add(resolution); } } orderedModules.push(module); } module.execIndex = nextExecIndex++; analysedModules.add(module); }; for (const currentEntry of entryModules) { if (!parents.has(currentEntry)) { parents.set(currentEntry, null); analyseModule(currentEntry); } } for (const currentEntry of dynamicImports) { if (!parents.has(currentEntry)) { parents.set(currentEntry, null); analyseModule(currentEntry); } } return { cyclePaths, orderedModules }; } function getCyclePath(module, parent, parents) { const cycleSymbol = Symbol(module.id); const path = [module.id]; let nextModule = parent; module.cycles.add(cycleSymbol); while (nextModule !== module) { nextModule.cycles.add(cycleSymbol); path.push(nextModule.id); nextModule = parents.get(nextModule); } path.push(path[0]); path.reverse(); return path; } function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) { const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' }; const cnst = constBindings ? 'const' : 'var'; const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`; const getFunctionIntro = arrowFunctions ? (parameters, { isAsync, name }) => { const singleParameter = parameters.length === 1; const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : ''; return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`; } : getNonArrowFunctionIntro; const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [ `${getFunctionIntro(parameters, { isAsync: false, name })}${arrowFunctions ? lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : '' : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`, arrowFunctions ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}` : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}` ]; const isValidPropertyName = reservedNamesAsProps ? (name) => validPropertyName.test(name) : (name) => !RESERVED_NAMES$1.has(name) && validPropertyName.test(name); return { _, cnst, getDirectReturnFunction, getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => { const [left, right] = getDirectReturnFunction(parameters, { functionReturn: true, lineBreakIndent: null, name: null }); return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`; }, getFunctionIntro, getNonArrowFunctionIntro, getObject(fields, { lineBreakIndent }) { const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _; return `{${fields .map(([key, value]) => { if (key === null) return `${prefix}${value}`; const needsQuotes = !isValidPropertyName(key); return key === value && objectShorthand && !needsQuotes ? prefix + key : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`; }) .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`; }, getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`, n, s }; } const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code; const validPropertyName = /^(?!\d)[\w$]+$/; let Source$1 = class Source { constructor(filename, content) { this.isOriginal = true; this.filename = filename; this.content = content; } traceSegment(line, column, name) { return { column, line, name, source: this }; } }; class Link { constructor(map, sources) { this.sources = sources; this.names = map.names; this.mappings = map.mappings; } traceMappings() { const sources = []; const sourceIndexMap = new Map(); const sourcesContent = []; const names = []; const nameIndexMap = new Map(); const mappings = []; for (const line of this.mappings) { const tracedLine = []; for (const segment of line) { if (segment.length === 1) continue; const source = this.sources[segment[1]]; if (!source) continue; const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : ''); if (traced) { const { column, line, name, source: { content, filename } } = traced; let sourceIndex = sourceIndexMap.get(filename); if (sourceIndex === undefined) { sourceIndex = sources.length; sources.push(filename); sourceIndexMap.set(filename, sourceIndex); sourcesContent[sourceIndex] = content; } else if (sourcesContent[sourceIndex] == null) { sourcesContent[sourceIndex] = content; } else if (content != null && sourcesContent[sourceIndex] !== content) { return error$4(logConflictingSourcemapSources(filename)); } const tracedSegment = [segment[0], sourceIndex, line, column]; if (name) { let nameIndex = nameIndexMap.get(name); if (nameIndex === undefined) { nameIndex = names.length; names.push(name); nameIndexMap.set(name, nameIndex); } tracedSegment[4] = nameIndex; } tracedLine.push(tracedSegment); } } mappings.push(tracedLine); } return { mappings, names, sources, sourcesContent }; } traceSegment(line, column, name) { const segments = this.mappings[line]; if (!segments) return null; // binary search through segments for the given column let searchStart = 0; let searchEnd = segments.length - 1; while (searchStart <= searchEnd) { const m = (searchStart + searchEnd) >> 1; const segment = segments[m]; // If a sourcemap does not have sufficient resolution to contain a // necessary mapping, e.g. because it only contains line information, we // use the best approximation we could find if (segment[0] === column || searchStart === searchEnd) { if (segment.length == 1) return null; const source = this.sources[segment[1]]; if (!source) return null; return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name); } if (segment[0] > column) { searchEnd = m - 1; } else { searchStart = m + 1; } } return null; } } function getLinkMap(log) { return function linkMap(source, map) { if (!map.missing) { return new Link(map, [source]); } log(LOGLEVEL_WARN, logSourcemapBroken(map.plugin)); return new Link({ mappings: [], names: [] }, [source]); }; } function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) { let source; if (originalSourcemap) { const sources = originalSourcemap.sources; const sourcesContent = originalSourcemap.sourcesContent || []; const directory = dirname$1(id) || '.'; const sourceRoot = originalSourcemap.sourceRoot || '.'; const baseSources = sources.map((source, index) => new Source$1(resolve$4(directory, sourceRoot, source), sourcesContent[index])); source = new Link(originalSourcemap, baseSources); } else { source = new Source$1(id, originalCode); } return sourcemapChain.reduce(linkMap, source); } function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, log) { const linkMap = getLinkMap(log); const moduleSources = modules .filter(module => !module.excludeFromSourcemap) .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap)); const link = new Link(map, moduleSources); const source = bundleSourcemapChain.reduce(linkMap, link); let { sources, sourcesContent, names, mappings } = source.traceMappings(); if (file) { const directory = dirname$1(file); sources = sources.map((source) => relative$2(directory, source)); file = basename$1(file); } sourcesContent = (excludeContent ? null : sourcesContent); for (const module of modules) { resetSourcemapCache(module.originalSourcemap, module.sourcemapChain); } return new SourceMap$4({ file, mappings, names, sources, sourcesContent }); } function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) { if (sourcemapChain.length === 0) { return originalSourcemap; } const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log)); const map = source.traceMappings(); return decodedSourcemap({ version: 3, ...map }); } const createHash$3 = () => createHash$4('sha256'); async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) { timeStart('render chunks', 2); reserveEntryChunksInBundle(chunks); const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render())); timeEnd('render chunks', 2); timeStart('transform chunks', 2); const chunkGraph = getChunkGraph(chunks); const { initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, renderedChunksByPlaceholder, hashDependenciesByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, log); const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, bundle); addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions); timeEnd('transform chunks', 2); } function reserveEntryChunksInBundle(chunks) { for (const chunk of chunks) { if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) { // reserves name in bundle as side effect if it does not contain a hash chunk.getPreliminaryFileName(); } } } function getChunkGraph(chunks) { return Object.fromEntries(chunks.map(chunk => { const renderedChunkInfo = chunk.getRenderedChunkInfo(); return [renderedChunkInfo.fileName, renderedChunkInfo]; })); } async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, log) { let map = null; const sourcemapChain = []; let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => { if (result == null) return code; if (typeof result === 'string') result = { code: result, map: undefined }; // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning if (result.map !== null) { const map = decodedSourcemap(result.map); sourcemapChain.push(map || { missing: true, plugin: plugin.name }); } return result.code; }); const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options; if (!compact && code[code.length - 1] !== '\n') code += '\n'; if (sourcemap) { timeStart('sourcemaps', 3); let resultingFile; if (file) resultingFile = resolve$4(sourcemapFile || file); else if (dir) resultingFile = resolve$4(dir, fileName); else resultingFile = resolve$4(fileName); const decodedMap = magicString.generateDecodedMap({}); map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log); for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) { let sourcePath = map.sources[sourcesIndex]; const sourcemapPath = `${resultingFile}.map`; const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath); if (typeof ignoreList !== 'boolean') { error$4(logFailedValidation('sourcemapIgnoreList function must return a boolean.')); } if (ignoreList) { if (map.x_google_ignoreList === undefined) { map.x_google_ignoreList = []; } if (!map.x_google_ignoreList.includes(sourcesIndex)) { map.x_google_ignoreList.push(sourcesIndex); } } if (sourcemapPathTransform) { sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath); if (typeof sourcePath !== 'string') { error$4(logFailedValidation(`sourcemapPathTransform function must return a string.`)); } } map.sources[sourcesIndex] = normalize$1(sourcePath); } timeEnd('sourcemaps', 3); } return { code, map }; } async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, log) { const nonHashedChunksWithPlaceholders = []; const renderedChunksByPlaceholder = new Map(); const hashDependenciesByPlaceholder = new Map(); const initialHashesByPlaceholder = new Map(); const placeholders = new Set(); for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) { if (hashPlaceholder) placeholders.add(hashPlaceholder); } await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => { const transformedChunk = { chunk, fileName, sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null, ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log)) }; const { code, map } = transformedChunk; if (hashPlaceholder) { // To create a reproducible content-only hash, all placeholders are // replaced with the same value before hashing const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders); const hash = createHash$3().update(transformedCode); const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => { if (pluginHash) { augmentation += pluginHash; } return augmentation; }); if (hashAugmentation) { hash.update(hashAugmentation); } renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk); hashDependenciesByPlaceholder.set(hashPlaceholder, { containedPlaceholders, contentHash: hash.digest('hex') }); } else { nonHashedChunksWithPlaceholders.push(transformedChunk); } const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder; if (map && sourcemapHashPlaceholder) { initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, createHash$3() .update(map.toString()) .digest('hex') .slice(0, preliminarySourcemapFileName.hashPlaceholder.length)); } })); return { hashDependenciesByPlaceholder, initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, renderedChunksByPlaceholder }; } function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, bundle) { const hashesByPlaceholder = new Map(initialHashesByPlaceholder); for (const [placeholder, { fileName }] of renderedChunksByPlaceholder) { let hash = createHash$3(); const hashDependencyPlaceholders = new Set([placeholder]); for (const dependencyPlaceholder of hashDependencyPlaceholders) { const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder); hash.update(contentHash); for (const containedPlaceholder of containedPlaceholders) { // When looping over a map, setting an entry only causes a new iteration if the key is new hashDependencyPlaceholders.add(containedPlaceholder); } } let finalFileName; let finalHash; do { // In case of a hash collision, create a hash of the hash if (finalHash) { hash = createHash$3().update(finalHash); } finalHash = hash.digest('hex').slice(0, placeholder.length); finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash); } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase())); bundle[finalFileName] = FILE_PLACEHOLDER; hashesByPlaceholder.set(placeholder, finalHash); } return hashesByPlaceholder; } function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) { for (const { chunk, code, fileName, sourcemapFileName, map } of renderedChunksByPlaceholder.values()) { let updatedCode = replacePlaceholders(code, hashesByPlaceholder); const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder); let finalSourcemapFileName = null; if (map) { finalSourcemapFileName = sourcemapFileName ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder) : `${finalFileName}.map`; map.file = replacePlaceholders(map.file, hashesByPlaceholder); updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options); } bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder); } for (const { chunk, code, fileName, sourcemapFileName, map } of nonHashedChunksWithPlaceholders) { let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code; let finalSourcemapFileName = null; if (map) { finalSourcemapFileName = sourcemapFileName ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder) : `${fileName}.map`; updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options); } bundle[fileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder); } } function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) { let url; if (sourcemap === 'inline') { url = map.toUrl(); } else { const sourcemapFileName = basename$1(fileName); url = sourcemapBaseUrl ? new URL(sourcemapFileName, sourcemapBaseUrl).toString() : sourcemapFileName; pluginDriver.emitFile({ fileName, source: map.toString(), type: 'asset' }); } return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`; } class Bundle { constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) { this.outputOptions = outputOptions; this.unsetOptions = unsetOptions; this.inputOptions = inputOptions; this.pluginDriver = pluginDriver; this.graph = graph; this.facadeChunkByModule = new Map(); this.includedNamespaces = new Set(); } async generate(isWrite) { timeStart('GENERATE', 1); const outputBundleBase = Object.create(null); const outputBundle = getOutputBundle(outputBundleBase); this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions); try { timeStart('initialize render', 2); await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]); timeEnd('initialize render', 2); timeStart('generate chunks', 2); const getHashPlaceholder = getHashPlaceholderGenerator(); const chunks = await this.generateChunks(outputBundle, getHashPlaceholder); if (chunks.length > 1) { validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog); } this.pluginDriver.setChunkInformation(this.facadeChunkByModule); for (const chunk of chunks) { chunk.generateExports(); } timeEnd('generate chunks', 2); await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog); } catch (error_) { await this.pluginDriver.hookParallel('renderError', [error_]); throw error_; } removeUnreferencedAssets(outputBundle); timeStart('generate bundle', 2); await this.pluginDriver.hookSeq('generateBundle', [ this.outputOptions, outputBundle, isWrite ]); this.finaliseAssets(outputBundle); timeEnd('generate bundle', 2); timeEnd('GENERATE', 1); return outputBundleBase; } async addManualChunks(manualChunks) { const manualChunkAliasByEntry = new Map(); const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({ alias, entries: await this.graph.moduleLoader.addAdditionalModules(files, true) }))); for (const { alias, entries } of chunkEntries) { for (const entry of entries) { addModuleToManualChunk(alias, entry, manualChunkAliasByEntry); } } return manualChunkAliasByEntry; } assignManualChunks(getManualChunk) { // eslint-disable-next-line unicorn/prefer-module const manualChunkAliasesWithEntry = []; const manualChunksApi = { getModuleIds: () => this.graph.modulesById.keys(), getModuleInfo: this.graph.getModuleInfo }; for (const module of this.graph.modulesById.values()) { if (module instanceof Module) { const manualChunkAlias = getManualChunk(module.id, manualChunksApi); if (typeof manualChunkAlias === 'string') { manualChunkAliasesWithEntry.push([manualChunkAlias, module]); } } } manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0); const manualChunkAliasByEntry = new Map(); for (const [alias, module] of manualChunkAliasesWithEntry) { addModuleToManualChunk(alias, module, manualChunkAliasByEntry); } return manualChunkAliasByEntry; } finaliseAssets(bundle) { if (this.outputOptions.validate) { for (const file of Object.values(bundle)) { if ('code' in file) { try { this.graph.contextParse(file.code, { ecmaVersion: 'latest' }); } catch (error_) { this.inputOptions.onLog(LOGLEVEL_WARN, logChunkInvalid(file, error_)); } } } } this.pluginDriver.finaliseAssets(); } async generateChunks(bundle, getHashPlaceholder) { const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules } = this.outputOptions; const manualChunkAliasByEntry = typeof manualChunks === 'object' ? await this.addManualChunks(manualChunks) : this.assignManualChunks(manualChunks); const snippets = getGenerateCodeSnippets(this.outputOptions); const includedModules = getIncludedModules(this.graph.modulesById); const inputBase = commondir$1(getAbsoluteEntryModulePaths(includedModules, preserveModules)); const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase); const chunks = []; const chunkByModule = new Map(); for (const { alias, modules } of inlineDynamicImports ? [{ alias: null, modules: includedModules }] : preserveModules ? includedModules.map(module => ({ alias: null, modules: [module] })) : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog)) { sortByExecutionOrder(modules); const chunk = new Chunk$3(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, externalChunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias, getHashPlaceholder, bundle, inputBase, snippets); chunks.push(chunk); } for (const chunk of chunks) { chunk.link(); } const facades = []; for (const chunk of chunks) { facades.push(...chunk.generateFacades()); } return [...chunks, ...facades]; } } function validateOptionsForMultiChunkOutput(outputOptions, log) { if (outputOptions.format === 'umd' || outputOptions.format === 'iife') return error$4(logInvalidOption('output.format', URL_OUTPUT_FORMAT, 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format)); if (typeof outputOptions.file === 'string') return error$4(logInvalidOption('output.file', URL_OUTPUT_DIR, 'when building multiple chunks, the "output.dir" option must be used, not "output.file". To inline dynamic imports, set the "inlineDynamicImports" option')); if (outputOptions.sourcemapFile) return error$4(logInvalidOption('output.sourcemapFile', URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds')); if (!outputOptions.amd.autoId && outputOptions.amd.id) log(LOGLEVEL_WARN, logInvalidOption('output.amd.id', URL_OUTPUT_AMD_ID, 'this option is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath" instead')); } function getIncludedModules(modulesById) { const includedModules = []; for (const module of modulesById.values()) { if (module instanceof Module && (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) { includedModules.push(module); } } return includedModules; } function getAbsoluteEntryModulePaths(includedModules, preserveModules) { const absoluteEntryModulePaths = []; for (const module of includedModules) { if ((module.info.isEntry || preserveModules) && isAbsolute$2(module.id)) { absoluteEntryModulePaths.push(module.id); } } return absoluteEntryModulePaths; } function getExternalChunkByModule(modulesById, outputOptions, inputBase) { const externalChunkByModule = new Map(); for (const module of modulesById.values()) { if (module instanceof ExternalModule) { externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase)); } } return externalChunkByModule; } function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) { const existingAlias = manualChunkAliasByEntry.get(module); if (typeof existingAlias === 'string' && existingAlias !== alias) { return error$4(logCannotAssignModuleToChunk(module.id, alias, existingAlias)); } manualChunkAliasByEntry.set(module, alias); } // This file was generated. Do not modify manually! var astralIdentifierCodes$2 = [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, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 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, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 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, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; // This file was generated. Do not modify manually! var astralIdentifierStartCodes$2 = [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, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 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, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 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, 20, 1, 64, 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, 38, 6, 186, 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, 19, 72, 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, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 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, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 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, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 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, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191]; // This file was generated. Do not modify manually! var nonASCIIidentifierChars$2 = "\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\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\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\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\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-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\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-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; // This file was generated. Do not modify manually! var nonASCIIidentifierStartChars$2 = "\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\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\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\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\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-\u1b4c\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-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; // 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. // Reserved word lists for various dialects of the language var reservedWords$4 = { 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", 5: "class enum extends super const export import", 6: "enum", strict: "implements interface let package private protected public static yield", strictBind: "eval arguments" }; // And the keywords var ecma5AndLessKeywords$2 = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; var keywords$1$2 = { 5: ecma5AndLessKeywords$2, "5module": ecma5AndLessKeywords$2 + " export import", 6: ecma5AndLessKeywords$2 + " const class extends export import super" }; var keywordRelationalOperator$2 = /^in(stanceof)?$/; // ## Character categories var nonASCIIidentifierStart$2 = new RegExp("[" + nonASCIIidentifierStartChars$2 + "]"); var nonASCIIidentifier$2 = new RegExp("[" + nonASCIIidentifierStartChars$2 + nonASCIIidentifierChars$2 + "]"); // This has a complexity linear to the value of the code. The // assumption is that looking up astral identifier characters is // rare. function isInAstralSet$2(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 } } return false } // Test whether a given character code starts an identifier. function isIdentifierStart$2(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$2.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet$2(code, astralIdentifierStartCodes$2) } // Test whether a given character is part of an identifier. function isIdentifierChar$2(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$2.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet$2(code, astralIdentifierStartCodes$2) || isInAstralSet$2(code, astralIdentifierCodes$2) } // ## Token types // The assignment of fine-grained, information-carrying type objects // allows the tokenizer to store the information it has about a // token in a way that is very cheap for the parser to look up. // All token type variables start with an underscore, to make them // easy to recognize. // The `beforeExpr` property is used to disambiguate between regular // expressions and divisions. It is set on all token types that can // be followed by an expression (thus, a slash after them would be a // regular expression). // // The `startsExpr` property is used to check if the token ends a // `yield` expression. It is set on all token types that either can // directly start an expression (like a quotation mark) or can // continue an expression (like the body of a string). // // `isLoop` marks a keyword as starting a loop, which is important // to know when parsing a label, in order to allow or disallow // continue jumps to that label. var TokenType$3 = function TokenType(label, conf) { if ( conf === void 0 ) conf = {}; this.label = label; this.keyword = conf.keyword; this.beforeExpr = !!conf.beforeExpr; this.startsExpr = !!conf.startsExpr; this.isLoop = !!conf.isLoop; this.isAssign = !!conf.isAssign; this.prefix = !!conf.prefix; this.postfix = !!conf.postfix; this.binop = conf.binop || null; this.updateContext = null; }; function binop$2(name, prec) { return new TokenType$3(name, {beforeExpr: true, binop: prec}) } var beforeExpr$2 = {beforeExpr: true}, startsExpr$2 = {startsExpr: true}; // Map keyword names to token types. var keywords$4 = {}; // Succinct definitions of keyword token types function kw$2(name, options) { if ( options === void 0 ) options = {}; options.keyword = name; return keywords$4[name] = new TokenType$3(name, options) } var types$1$2 = { num: new TokenType$3("num", startsExpr$2), regexp: new TokenType$3("regexp", startsExpr$2), string: new TokenType$3("string", startsExpr$2), name: new TokenType$3("name", startsExpr$2), privateId: new TokenType$3("privateId", startsExpr$2), eof: new TokenType$3("eof"), // Punctuation token types. bracketL: new TokenType$3("[", {beforeExpr: true, startsExpr: true}), bracketR: new TokenType$3("]"), braceL: new TokenType$3("{", {beforeExpr: true, startsExpr: true}), braceR: new TokenType$3("}"), parenL: new TokenType$3("(", {beforeExpr: true, startsExpr: true}), parenR: new TokenType$3(")"), comma: new TokenType$3(",", beforeExpr$2), semi: new TokenType$3(";", beforeExpr$2), colon: new TokenType$3(":", beforeExpr$2), dot: new TokenType$3("."), question: new TokenType$3("?", beforeExpr$2), questionDot: new TokenType$3("?."), arrow: new TokenType$3("=>", beforeExpr$2), template: new TokenType$3("template"), invalidTemplate: new TokenType$3("invalidTemplate"), ellipsis: new TokenType$3("...", beforeExpr$2), backQuote: new TokenType$3("`", startsExpr$2), dollarBraceL: new TokenType$3("${", {beforeExpr: true, startsExpr: true}), // Operators. These carry several kinds of properties to help the // parser use them properly (the presence of these properties is // what categorizes them as operators). // // `binop`, when present, specifies that this operator is a binary // operator, and will refer to its precedence. // // `prefix` and `postfix` mark the operator as a prefix or postfix // unary operator. // // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as // binary operators with a very low precedence, that should result // in AssignmentExpression nodes. eq: new TokenType$3("=", {beforeExpr: true, isAssign: true}), assign: new TokenType$3("_=", {beforeExpr: true, isAssign: true}), incDec: new TokenType$3("++/--", {prefix: true, postfix: true, startsExpr: true}), prefix: new TokenType$3("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), logicalOR: binop$2("||", 1), logicalAND: binop$2("&&", 2), bitwiseOR: binop$2("|", 3), bitwiseXOR: binop$2("^", 4), bitwiseAND: binop$2("&", 5), equality: binop$2("==/!=/===/!==", 6), relational: binop$2("/<=/>=", 7), bitShift: binop$2("<>/>>>", 8), plusMin: new TokenType$3("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), modulo: binop$2("%", 10), star: binop$2("*", 10), slash: binop$2("/", 10), starstar: new TokenType$3("**", {beforeExpr: true}), coalesce: binop$2("??", 1), // Keyword token types. _break: kw$2("break"), _case: kw$2("case", beforeExpr$2), _catch: kw$2("catch"), _continue: kw$2("continue"), _debugger: kw$2("debugger"), _default: kw$2("default", beforeExpr$2), _do: kw$2("do", {isLoop: true, beforeExpr: true}), _else: kw$2("else", beforeExpr$2), _finally: kw$2("finally"), _for: kw$2("for", {isLoop: true}), _function: kw$2("function", startsExpr$2), _if: kw$2("if"), _return: kw$2("return", beforeExpr$2), _switch: kw$2("switch"), _throw: kw$2("throw", beforeExpr$2), _try: kw$2("try"), _var: kw$2("var"), _const: kw$2("const"), _while: kw$2("while", {isLoop: true}), _with: kw$2("with"), _new: kw$2("new", {beforeExpr: true, startsExpr: true}), _this: kw$2("this", startsExpr$2), _super: kw$2("super", startsExpr$2), _class: kw$2("class", startsExpr$2), _extends: kw$2("extends", beforeExpr$2), _export: kw$2("export"), _import: kw$2("import", startsExpr$2), _null: kw$2("null", startsExpr$2), _true: kw$2("true", startsExpr$2), _false: kw$2("false", startsExpr$2), _in: kw$2("in", {beforeExpr: true, binop: 7}), _instanceof: kw$2("instanceof", {beforeExpr: true, binop: 7}), _typeof: kw$2("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), _void: kw$2("void", {beforeExpr: true, prefix: true, startsExpr: true}), _delete: kw$2("delete", {beforeExpr: true, prefix: true, startsExpr: true}) }; // Matches a whole line break (where CRLF is considered a single // line break). Used to count lines. var lineBreak$2 = /\r\n?|\n|\u2028|\u2029/; var lineBreakG$2 = new RegExp(lineBreak$2.source, "g"); function isNewLine$2(code) { return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 } function nextLineBreak$2(code, from, end) { if ( end === void 0 ) end = code.length; for (var i = from; i < end; i++) { var next = code.charCodeAt(i); if (isNewLine$2(next)) { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 } } return -1 } var nonASCIIwhitespace$2 = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; var skipWhiteSpace$3 = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; var ref$2 = Object.prototype; var hasOwnProperty$3 = ref$2.hasOwnProperty; var toString$5 = ref$2.toString; var hasOwn$2 = Object.hasOwn || (function (obj, propName) { return ( hasOwnProperty$3.call(obj, propName) ); }); var isArray$4 = Array.isArray || (function (obj) { return ( toString$5.call(obj) === "[object Array]" ); }); function wordsRegexp$2(words) { return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") } function codePointToString$2(code) { // UTF-16 Decoding if (code <= 0xFFFF) { return String.fromCharCode(code) } code -= 0x10000; return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) } var loneSurrogate$2 = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; // These are used when `options.locations` is on, for the // `startLoc` and `endLoc` properties. var Position$2 = function Position(line, col) { this.line = line; this.column = col; }; Position$2.prototype.offset = function offset (n) { return new Position$2(this.line, this.column + n) }; var SourceLocation$2 = function SourceLocation(p, start, end) { this.start = start; this.end = end; if (p.sourceFile !== null) { this.source = p.sourceFile; } }; // The `getLineInfo` function is mostly useful when the // `locations` option is off (for performance reasons) and you // want to find the line/column position for a given character // offset. `input` should be the code string that the offset refers // into. function getLineInfo$2(input, offset) { for (var line = 1, cur = 0;;) { var nextBreak = nextLineBreak$2(input, cur, offset); if (nextBreak < 0) { return new Position$2(line, offset - cur) } ++line; cur = nextBreak; } } // A second argument must be given to configure the parser process. // These options are recognized (only `ecmaVersion` is required): var defaultOptions$2 = { // `ecmaVersion` indicates the ECMAScript version to parse. Must be // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` // (the latest version the library supports). This influences // support for strict mode, the set of reserved words, and support // for new syntax features. ecmaVersion: null, // `sourceType` indicates the mode the code should be parsed in. // Can be either `"script"` or `"module"`. This influences global // strict mode and parsing of `import` and `export` declarations. sourceType: "script", // `onInsertedSemicolon` can be a callback that will be called // when a semicolon is automatically inserted. It will be passed // the position of the comma as an offset, and if `locations` is // enabled, it is given the location as a `{line, column}` object // as second argument. onInsertedSemicolon: null, // `onTrailingComma` is similar to `onInsertedSemicolon`, but for // trailing commas. onTrailingComma: null, // By default, reserved words are only enforced if ecmaVersion >= 5. // Set `allowReserved` to a boolean value to explicitly turn this on // an off. When this option has the value "never", reserved words // and keywords can also not be used as property names. allowReserved: null, // When enabled, a return at the top level is not considered an // error. allowReturnOutsideFunction: false, // When enabled, import/export statements are not constrained to // appearing at the top of the program, and an import.meta expression // in a script isn't considered an error. allowImportExportEverywhere: false, // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. // When enabled, await identifiers are allowed to appear at the top-level scope, // but they are still not allowed in non-async functions. allowAwaitOutsideFunction: null, // When enabled, super identifiers are not constrained to // appearing in methods and do not raise an error when they appear elsewhere. allowSuperOutsideMethod: null, // When enabled, hashbang directive in the beginning of file is // allowed and treated as a line comment. Enabled by default when // `ecmaVersion` >= 2023. allowHashBang: false, // By default, the parser will verify that private properties are // only used in places where they are valid and have been declared. // Set this to false to turn such checks off. checkPrivateFields: true, // When `locations` is on, `loc` properties holding objects with // `start` and `end` properties in `{line, column}` form (with // line being 1-based and column 0-based) will be attached to the // nodes. locations: false, // A function can be passed as `onToken` option, which will // cause Acorn to call that function with object in the same // format as tokens returned from `tokenizer().getToken()`. Note // that you are not allowed to call the parser from the // callback—that will corrupt its internal state. onToken: null, // A function can be passed as `onComment` option, which will // cause Acorn to call that function with `(block, text, start, // end)` parameters whenever a comment is skipped. `block` is a // boolean indicating whether this is a block (`/* */`) comment, // `text` is the content of the comment, and `start` and `end` are // character offsets that denote the start and end of the comment. // When the `locations` option is on, two more parameters are // passed, the full `{line, column}` locations of the start and // end of the comments. Note that you are not allowed to call the // parser from the callback—that will corrupt its internal state. onComment: null, // Nodes have their start and end characters offsets recorded in // `start` and `end` properties (directly on the node, rather than // the `loc` object, which holds line/column data. To also add a // [semi-standardized][range] `range` property holding a `[start, // end]` array with the same numbers, set the `ranges` option to // `true`. // // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 ranges: false, // It is possible to parse multiple files into a single AST by // passing the tree produced by parsing the first file as // `program` option in subsequent parses. This will add the // toplevel forms of the parsed file to the `Program` (top) node // of an existing parse tree. program: null, // When `locations` is on, you can pass this to record the source // file in every node's `loc` object. sourceFile: null, // This value, if given, is stored in every node, whether // `locations` is on or off. directSourceFile: null, // When enabled, parenthesized expressions are represented by // (non-standard) ParenthesizedExpression nodes preserveParens: false }; // Interpret and default an options object var warnedAboutEcmaVersion$2 = false; function getOptions$2(opts) { var options = {}; for (var opt in defaultOptions$2) { options[opt] = opts && hasOwn$2(opts, opt) ? opts[opt] : defaultOptions$2[opt]; } if (options.ecmaVersion === "latest") { options.ecmaVersion = 1e8; } else if (options.ecmaVersion == null) { if (!warnedAboutEcmaVersion$2 && typeof console === "object" && console.warn) { warnedAboutEcmaVersion$2 = true; console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); } options.ecmaVersion = 11; } else if (options.ecmaVersion >= 2015) { options.ecmaVersion -= 2009; } if (options.allowReserved == null) { options.allowReserved = options.ecmaVersion < 5; } if (!opts || opts.allowHashBang == null) { options.allowHashBang = options.ecmaVersion >= 14; } if (isArray$4(options.onToken)) { var tokens = options.onToken; options.onToken = function (token) { return tokens.push(token); }; } if (isArray$4(options.onComment)) { options.onComment = pushComment$2(options, options.onComment); } return options } function pushComment$2(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$2(this, startLoc, endLoc); } if (options.ranges) { comment.range = [start, end]; } array.push(comment); } } // Each scope gets a bitset that may contain these flags var SCOPE_TOP$2 = 1, SCOPE_FUNCTION$2 = 2, SCOPE_ASYNC$2 = 4, SCOPE_GENERATOR$2 = 8, SCOPE_ARROW$2 = 16, SCOPE_SIMPLE_CATCH$2 = 32, SCOPE_SUPER$2 = 64, SCOPE_DIRECT_SUPER$2 = 128, SCOPE_CLASS_STATIC_BLOCK$2 = 256, SCOPE_VAR$2 = SCOPE_TOP$2 | SCOPE_FUNCTION$2 | SCOPE_CLASS_STATIC_BLOCK$2; function functionFlags$2(async, generator) { return SCOPE_FUNCTION$2 | (async ? SCOPE_ASYNC$2 : 0) | (generator ? SCOPE_GENERATOR$2 : 0) } // Used in checkLVal* and declareName to determine the type of a binding var BIND_NONE$2 = 0, // Not a binding BIND_VAR$2 = 1, // Var-style binding BIND_LEXICAL$2 = 2, // Let- or const-style binding BIND_FUNCTION$2 = 3, // Function declaration BIND_SIMPLE_CATCH$2 = 4, // Simple (identifier pattern) catch binding BIND_OUTSIDE$2 = 5; // Special case for function names as bound inside the function var Parser$2 = function Parser(options, input, startPos) { this.options = options = getOptions$2(options); this.sourceFile = options.sourceFile; this.keywords = wordsRegexp$2(keywords$1$2[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); var reserved = ""; if (options.allowReserved !== true) { reserved = reservedWords$4[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; if (options.sourceType === "module") { reserved += " await"; } } this.reservedWords = wordsRegexp$2(reserved); var reservedStrict = (reserved ? reserved + " " : "") + reservedWords$4.strict; this.reservedWordsStrict = wordsRegexp$2(reservedStrict); this.reservedWordsStrictBind = wordsRegexp$2(reservedStrict + " " + reservedWords$4.strictBind); this.input = String(input); // Used to signal to callers of `readWord1` whether the word // contained any escape sequences. This is needed because words with // escape sequences must not be interpreted as keywords. this.containsEsc = false; // Set up token state // The current position of the tokenizer in the input. if (startPos) { this.pos = startPos; this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; this.curLine = this.input.slice(0, this.lineStart).split(lineBreak$2).length; } else { this.pos = this.lineStart = 0; this.curLine = 1; } // Properties of the current token: // Its type this.type = types$1$2.eof; // For tokens that include more information than their type, the value this.value = null; // Its start and end offset this.start = this.end = this.pos; // And, if locations are used, the {line, column} object // corresponding to those offsets this.startLoc = this.endLoc = this.curPosition(); // Position information for the previous token this.lastTokEndLoc = this.lastTokStartLoc = null; this.lastTokStart = this.lastTokEnd = this.pos; // The context stack is used to superficially track syntactic // context to predict whether a regular expression is allowed in a // given position. this.context = this.initialContext(); this.exprAllowed = true; // Figure out if it's a module code. this.inModule = options.sourceType === "module"; this.strict = this.inModule || this.strictDirective(this.pos); // Used to signify the start of a potential arrow function this.potentialArrowAt = -1; this.potentialArrowInForAwait = false; // Positions to delayed-check that yield/await does not exist in default parameters. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; // Labels in scope. this.labels = []; // Thus-far undefined exports. this.undefinedExports = Object.create(null); // If enabled, skip leading hashbang line. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") { this.skipLineComment(2); } // Scope tracking for duplicate variable names (see scope.js) this.scopeStack = []; this.enterScope(SCOPE_TOP$2); // For RegExp validation this.regexpState = null; // The stack of private names. // Each element has two properties: 'declared' and 'used'. // When it exited from the outermost class definition, all used private names must be declared. this.privateNameStack = []; }; var prototypeAccessors$2 = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } }; Parser$2.prototype.parse = function parse () { var node = this.options.program || this.startNode(); this.nextToken(); return this.parseTopLevel(node) }; prototypeAccessors$2.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION$2) > 0 }; prototypeAccessors$2.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR$2) > 0 && !this.currentVarScope().inClassFieldInit }; prototypeAccessors$2.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC$2) > 0 && !this.currentVarScope().inClassFieldInit }; prototypeAccessors$2.canAwait.get = function () { for (var i = this.scopeStack.length - 1; i >= 0; i--) { var scope = this.scopeStack[i]; if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK$2) { return false } if (scope.flags & SCOPE_FUNCTION$2) { return (scope.flags & SCOPE_ASYNC$2) > 0 } } return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction }; prototypeAccessors$2.allowSuper.get = function () { var ref = this.currentThisScope(); var flags = ref.flags; var inClassFieldInit = ref.inClassFieldInit; return (flags & SCOPE_SUPER$2) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod }; prototypeAccessors$2.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER$2) > 0 }; prototypeAccessors$2.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; prototypeAccessors$2.allowNewDotTarget.get = function () { var ref = this.currentThisScope(); var flags = ref.flags; var inClassFieldInit = ref.inClassFieldInit; return (flags & (SCOPE_FUNCTION$2 | SCOPE_CLASS_STATIC_BLOCK$2)) > 0 || inClassFieldInit }; prototypeAccessors$2.inClassStaticBlock.get = function () { return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK$2) > 0 }; Parser$2.extend = function extend () { var plugins = [], len = arguments.length; while ( len-- ) plugins[ len ] = arguments[ len ]; var cls = this; for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } return cls }; Parser$2.parse = function parse (input, options) { return new this(options, input).parse() }; Parser$2.parseExpressionAt = function parseExpressionAt (input, pos, options) { var parser = new this(options, input, pos); parser.nextToken(); return parser.parseExpression() }; Parser$2.tokenizer = function tokenizer (input, options) { return new this(options, input) }; Object.defineProperties( Parser$2.prototype, prototypeAccessors$2 ); var pp$9$2 = Parser$2.prototype; // ## Parser utilities var literal$2 = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; pp$9$2.strictDirective = function(start) { if (this.options.ecmaVersion < 5) { return false } for (;;) { // Try to find string literal. skipWhiteSpace$3.lastIndex = start; start += skipWhiteSpace$3.exec(this.input)[0].length; var match = literal$2.exec(this.input.slice(start)); if (!match) { return false } if ((match[1] || match[2]) === "use strict") { skipWhiteSpace$3.lastIndex = start + match[0].length; var spaceAfter = skipWhiteSpace$3.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; var next = this.input.charAt(end); return next === ";" || next === "}" || (lineBreak$2.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) } start += match[0].length; // Skip semicolon, if any. skipWhiteSpace$3.lastIndex = start; start += skipWhiteSpace$3.exec(this.input)[0].length; if (this.input[start] === ";") { start++; } } }; // Predicate that tests whether the next token is of the given // type, and if yes, consumes it as a side effect. pp$9$2.eat = function(type) { if (this.type === type) { this.next(); return true } else { return false } }; // Tests whether parsed token is a contextual keyword. pp$9$2.isContextual = function(name) { return this.type === types$1$2.name && this.value === name && !this.containsEsc }; // Consumes contextual keyword if possible. pp$9$2.eatContextual = function(name) { if (!this.isContextual(name)) { return false } this.next(); return true }; // Asserts that following token is given contextual keyword. pp$9$2.expectContextual = function(name) { if (!this.eatContextual(name)) { this.unexpected(); } }; // Test whether a semicolon can be inserted at the current position. pp$9$2.canInsertSemicolon = function() { return this.type === types$1$2.eof || this.type === types$1$2.braceR || lineBreak$2.test(this.input.slice(this.lastTokEnd, this.start)) }; pp$9$2.insertSemicolon = function() { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon) { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } return true } }; // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. pp$9$2.semicolon = function() { if (!this.eat(types$1$2.semi) && !this.insertSemicolon()) { this.unexpected(); } }; pp$9$2.afterTrailingComma = function(tokType, notNext) { if (this.type === tokType) { if (this.options.onTrailingComma) { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } if (!notNext) { this.next(); } return true } }; // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error. pp$9$2.expect = function(type) { this.eat(type) || this.unexpected(); }; // Raise an unexpected token error. pp$9$2.unexpected = function(pos) { this.raise(pos != null ? pos : this.start, "Unexpected token"); }; var DestructuringErrors$2 = function DestructuringErrors() { this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1; }; pp$9$2.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, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); } }; pp$9$2.checkExpressionErrors = function(refDestructuringErrors, andThrow) { if (!refDestructuringErrors) { return false } var shorthandAssign = refDestructuringErrors.shorthandAssign; var doubleProto = refDestructuringErrors.doubleProto; if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } if (shorthandAssign >= 0) { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } if (doubleProto >= 0) { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } }; pp$9$2.checkYieldAwaitInDefaultParams = function() { if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } if (this.awaitPos) { this.raise(this.awaitPos, "Await expression cannot be a default value"); } }; pp$9$2.isSimpleAssignTarget = function(expr) { if (expr.type === "ParenthesizedExpression") { return this.isSimpleAssignTarget(expr.expression) } return expr.type === "Identifier" || expr.type === "MemberExpression" }; var pp$8$2 = Parser$2.prototype; // ### Statement parsing // Parse a program. Initializes the parser, reads any number of // statements, and wraps them in a Program node. Optionally takes a // `program` argument. If present, the statements will be appended // to its body instead of creating a new node. pp$8$2.parseTopLevel = function(node) { var exports = Object.create(null); if (!node.body) { node.body = []; } while (this.type !== types$1$2.eof) { var stmt = this.parseStatement(null, true, exports); node.body.push(stmt); } if (this.inModule) { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) { var name = list[i]; this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); } } this.adaptDirectivePrologue(node.body); this.next(); node.sourceType = this.options.sourceType; return this.finishNode(node, "Program") }; var loopLabel$2 = {kind: "loop"}, switchLabel$2 = {kind: "switch"}; pp$8$2.isLet = function(context) { if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } skipWhiteSpace$3.lastIndex = this.pos; var skip = skipWhiteSpace$3.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 || nextCh === 92) { return true } // '[', '/' if (context) { return false } if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral if (isIdentifierStart$2(nextCh, true)) { var pos = next + 1; while (isIdentifierChar$2(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } var ident = this.input.slice(next, pos); if (!keywordRelationalOperator$2.test(ident)) { return true } } return false }; // check 'async [no LineTerminator here] function' // - 'async /*foo*/ function' is OK. // - 'async /*\n*/ function' is invalid. pp$8$2.isAsyncFunction = function() { if (this.options.ecmaVersion < 8 || !this.isContextual("async")) { return false } skipWhiteSpace$3.lastIndex = this.pos; var skip = skipWhiteSpace$3.exec(this.input); var next = this.pos + skip[0].length, after; return !lineBreak$2.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar$2(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) }; // Parse a single statement. // // If expecting a statement and finding a slash operator, parse a // regular expression literal. This is to handle cases like // `if (foo) /blah/.exec(foo)`, where looking at the previous token // does not help. pp$8$2.parseStatement = function(context, topLevel, exports) { var starttype = this.type, node = this.startNode(), kind; if (this.isLet(context)) { starttype = types$1$2._var; kind = "let"; } // Most types of statements are recognized by the keyword they // start with. Many are trivial to parse, some require a bit of // complexity. switch (starttype) { case types$1$2._break: case types$1$2._continue: return this.parseBreakContinueStatement(node, starttype.keyword) case types$1$2._debugger: return this.parseDebuggerStatement(node) case types$1$2._do: return this.parseDoStatement(node) case types$1$2._for: return this.parseForStatement(node) case types$1$2._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$1$2._class: if (context) { this.unexpected(); } return this.parseClass(node, true) case types$1$2._if: return this.parseIfStatement(node) case types$1$2._return: return this.parseReturnStatement(node) case types$1$2._switch: return this.parseSwitchStatement(node) case types$1$2._throw: return this.parseThrowStatement(node) case types$1$2._try: return this.parseTryStatement(node) case types$1$2._const: case types$1$2._var: kind = kind || this.value; if (context && kind !== "var") { this.unexpected(); } return this.parseVarStatement(node, kind) case types$1$2._while: return this.parseWhileStatement(node) case types$1$2._with: return this.parseWithStatement(node) case types$1$2.braceL: return this.parseBlock(true, node) case types$1$2.semi: return this.parseEmptyStatement(node) case types$1$2._export: case types$1$2._import: if (this.options.ecmaVersion > 10 && starttype === types$1$2._import) { skipWhiteSpace$3.lastIndex = this.pos; var skip = skipWhiteSpace$3.exec(this.input); var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); if (nextCh === 40 || nextCh === 46) // '(' or '.' { return this.parseExpressionStatement(node, this.parseExpression()) } } if (!this.options.allowImportExportEverywhere) { if (!topLevel) { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } if (!this.inModule) { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } } return starttype === types$1$2._import ? this.parseImport(node) : this.parseExport(node, exports) // If the statement does not start with a statement keyword or a // brace, it's an ExpressionStatement or LabeledStatement. We // simply start parsing an expression, and afterwards, if the // next token is a colon and the expression was a simple // Identifier node, we switch to interpreting it as a label. default: if (this.isAsyncFunction()) { if (context) { this.unexpected(); } this.next(); return this.parseFunctionStatement(node, true, !context) } var maybeName = this.value, expr = this.parseExpression(); if (starttype === types$1$2.name && expr.type === "Identifier" && this.eat(types$1$2.colon)) { return this.parseLabeledStatement(node, maybeName, expr, context) } else { return this.parseExpressionStatement(node, expr) } } }; pp$8$2.parseBreakContinueStatement = function(node, keyword) { var isBreak = keyword === "break"; this.next(); if (this.eat(types$1$2.semi) || this.insertSemicolon()) { node.label = null; } else if (this.type !== types$1$2.name) { this.unexpected(); } else { node.label = this.parseIdent(); this.semicolon(); } // Verify that there is an actual destination to break or // continue to. var i = 0; for (; i < this.labels.length; ++i) { var lab = this.labels[i]; if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } if (node.label && isBreak) { break } } } if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") }; pp$8$2.parseDebuggerStatement = function(node) { this.next(); this.semicolon(); return this.finishNode(node, "DebuggerStatement") }; pp$8$2.parseDoStatement = function(node) { this.next(); this.labels.push(loopLabel$2); node.body = this.parseStatement("do"); this.labels.pop(); this.expect(types$1$2._while); node.test = this.parseParenExpression(); if (this.options.ecmaVersion >= 6) { this.eat(types$1$2.semi); } else { this.semicolon(); } return this.finishNode(node, "DoWhileStatement") }; // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpression`), and then check // whether the next token is `in` or `of`. When there is no init // part (semicolon immediately after the opening parenthesis), it // is a regular `for` loop. pp$8$2.parseForStatement = function(node) { this.next(); var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; this.labels.push(loopLabel$2); this.enterScope(0); this.expect(types$1$2.parenL); if (this.type === types$1$2.semi) { if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, null) } var isLet = this.isLet(); if (this.type === types$1$2._var || this.type === types$1$2._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$1$2._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { if (this.options.ecmaVersion >= 9) { if (this.type === types$1$2._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 startsWithLet = this.isContextual("let"), isForOf = false; var refDestructuringErrors = new DestructuringErrors$2; var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); if (this.type === types$1$2._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { if (this.options.ecmaVersion >= 9) { if (this.type === types$1$2._in) { if (awaitAt > -1) { this.unexpected(awaitAt); } } else { node.await = awaitAt > -1; } } if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); } this.toAssignable(init, false, refDestructuringErrors); this.checkLValPattern(init); return this.parseForIn(node, init) } else { this.checkExpressionErrors(refDestructuringErrors, true); } if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, init) }; pp$8$2.parseFunctionStatement = function(node, isAsync, declarationPosition) { this.next(); return this.parseFunction(node, FUNC_STATEMENT$1$1 | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT$2), false, isAsync) }; pp$8$2.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$1$2._else) ? this.parseStatement("if") : null; return this.finishNode(node, "IfStatement") }; pp$8$2.parseReturnStatement = function(node) { if (!this.inFunction && !this.options.allowReturnOutsideFunction) { this.raise(this.start, "'return' outside of function"); } this.next(); // In `return` (and `break`/`continue`), the keywords with // optional arguments, we eagerly look for a semicolon or the // possibility to insert one. if (this.eat(types$1$2.semi) || this.insertSemicolon()) { node.argument = null; } else { node.argument = this.parseExpression(); this.semicolon(); } return this.finishNode(node, "ReturnStatement") }; pp$8$2.parseSwitchStatement = function(node) { this.next(); node.discriminant = this.parseParenExpression(); node.cases = []; this.expect(types$1$2.braceL); this.labels.push(switchLabel$2); this.enterScope(0); // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is used to keep the node that we are currently // adding statements to. var cur; for (var sawDefault = false; this.type !== types$1$2.braceR;) { if (this.type === types$1$2._case || this.type === types$1$2._default) { var isCase = this.type === types$1$2._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$1$2.colon); } else { if (!cur) { this.unexpected(); } cur.consequent.push(this.parseStatement(null)); } } this.exitScope(); if (cur) { this.finishNode(cur, "SwitchCase"); } this.next(); // Closing brace this.labels.pop(); return this.finishNode(node, "SwitchStatement") }; pp$8$2.parseThrowStatement = function(node) { this.next(); if (lineBreak$2.test(this.input.slice(this.lastTokEnd, this.start))) { this.raise(this.lastTokEnd, "Illegal newline after throw"); } node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement") }; // Reused empty array added for node fields that are always empty. var empty$1$2 = []; pp$8$2.parseCatchClauseParam = function() { var param = this.parseBindingAtom(); var simple = param.type === "Identifier"; this.enterScope(simple ? SCOPE_SIMPLE_CATCH$2 : 0); this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH$2 : BIND_LEXICAL$2); this.expect(types$1$2.parenR); return param }; pp$8$2.parseTryStatement = function(node) { this.next(); node.block = this.parseBlock(); node.handler = null; if (this.type === types$1$2._catch) { var clause = this.startNode(); this.next(); if (this.eat(types$1$2.parenL)) { clause.param = this.parseCatchClauseParam(); } 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$1$2._finally) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) { this.raise(node.start, "Missing catch or finally clause"); } return this.finishNode(node, "TryStatement") }; pp$8$2.parseVarStatement = function(node, kind, allowMissingInitializer) { this.next(); this.parseVar(node, false, kind, allowMissingInitializer); this.semicolon(); return this.finishNode(node, "VariableDeclaration") }; pp$8$2.parseWhileStatement = function(node) { this.next(); node.test = this.parseParenExpression(); this.labels.push(loopLabel$2); node.body = this.parseStatement("while"); this.labels.pop(); return this.finishNode(node, "WhileStatement") }; pp$8$2.parseWithStatement = function(node) { if (this.strict) { this.raise(this.start, "'with' in strict mode"); } this.next(); node.object = this.parseParenExpression(); node.body = this.parseStatement("with"); return this.finishNode(node, "WithStatement") }; pp$8$2.parseEmptyStatement = function(node) { this.next(); return this.finishNode(node, "EmptyStatement") }; pp$8$2.parseLabeledStatement = function(node, maybeName, expr, context) { for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) { var label = list[i$1]; if (label.name === maybeName) { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); } } var kind = this.type.isLoop ? "loop" : this.type === types$1$2._switch ? "switch" : null; for (var i = this.labels.length - 1; i >= 0; i--) { var label$1 = this.labels[i]; if (label$1.statementStart === node.start) { // Update information about previous labels on this node label$1.statementStart = this.start; label$1.kind = kind; } else { break } } this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); this.labels.pop(); node.label = expr; return this.finishNode(node, "LabeledStatement") }; pp$8$2.parseExpressionStatement = function(node, expr) { node.expression = expr; this.semicolon(); return this.finishNode(node, "ExpressionStatement") }; // Parse a semicolon-enclosed block of statements, handling `"use // strict"` declarations when `allowStrict` is true (used for // function bodies). pp$8$2.parseBlock = function(createNewLexicalScope, node, exitStrict) { if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; if ( node === void 0 ) node = this.startNode(); node.body = []; this.expect(types$1$2.braceL); if (createNewLexicalScope) { this.enterScope(0); } while (this.type !== types$1$2.braceR) { var stmt = this.parseStatement(null); node.body.push(stmt); } if (exitStrict) { this.strict = false; } this.next(); if (createNewLexicalScope) { this.exitScope(); } return this.finishNode(node, "BlockStatement") }; // Parse a regular `for` loop. The disambiguation code in // `parseStatement` will already have parsed the init statement or // expression. pp$8$2.parseFor = function(node, init) { node.init = init; this.expect(types$1$2.semi); node.test = this.type === types$1$2.semi ? null : this.parseExpression(); this.expect(types$1$2.semi); node.update = this.type === types$1$2.parenR ? null : this.parseExpression(); this.expect(types$1$2.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, "ForStatement") }; // Parse a `for`/`in` and `for`/`of` loop, which are almost // same from parser's perspective. pp$8$2.parseForIn = function(node, init) { var isForIn = this.type === types$1$2._in; this.next(); if ( init.type === "VariableDeclaration" && init.declarations[0].init != null && ( !isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier" ) ) { this.raise( init.start, ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") ); } node.left = init; node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); this.expect(types$1$2.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") }; // Parse a list of variable declarations. pp$8$2.parseVar = function(node, isFor, kind, allowMissingInitializer) { node.declarations = []; node.kind = kind; for (;;) { var decl = this.startNode(); this.parseVarId(decl, kind); if (this.eat(types$1$2.eq)) { decl.init = this.parseMaybeAssign(isFor); } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1$2._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { this.unexpected(); } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1$2._in || this.isContextual("of")))) { this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); } else { decl.init = null; } node.declarations.push(this.finishNode(decl, "VariableDeclarator")); if (!this.eat(types$1$2.comma)) { break } } return node }; pp$8$2.parseVarId = function(decl, kind) { decl.id = this.parseBindingAtom(); this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR$2 : BIND_LEXICAL$2, false); }; var FUNC_STATEMENT$1$1 = 1, FUNC_HANGING_STATEMENT$2 = 2, FUNC_NULLABLE_ID$1$1 = 4; // Parse a function declaration or literal (depending on the // `statement & FUNC_STATEMENT`). // Remove `allowExpressionBody` for 7.0.0, as it is only called with false pp$8$2.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { this.initFunction(node); if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { if (this.type === types$1$2.star && (statement & FUNC_HANGING_STATEMENT$2)) { this.unexpected(); } node.generator = this.eat(types$1$2.star); } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } if (statement & FUNC_STATEMENT$1$1) { node.id = (statement & FUNC_NULLABLE_ID$1$1) && this.type !== types$1$2.name ? null : this.parseIdent(); if (node.id && !(statement & FUNC_HANGING_STATEMENT$2)) // If it is a regular function declaration in sloppy mode, then it is // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding // mode depends on properties of the current scope (see // treatFunctionsAsVar). { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR$2 : BIND_LEXICAL$2 : BIND_FUNCTION$2); } } var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags$2(node.async, node.generator)); if (!(statement & FUNC_STATEMENT$1$1)) { node.id = this.type === types$1$2.name ? this.parseIdent() : null; } this.parseFunctionParams(node); this.parseFunctionBody(node, allowExpressionBody, false, forInit); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, (statement & FUNC_STATEMENT$1$1) ? "FunctionDeclaration" : "FunctionExpression") }; pp$8$2.parseFunctionParams = function(node) { this.expect(types$1$2.parenL); node.params = this.parseBindingList(types$1$2.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); }; // Parse a class declaration or literal (depending on the // `isStatement` parameter). pp$8$2.parseClass = function(node, isStatement) { this.next(); // ecma-262 14.6 Class Definitions // A class definition is always strict mode code. var oldStrict = this.strict; this.strict = true; this.parseClassId(node, isStatement); this.parseClassSuper(node); var privateNameMap = this.enterClassBody(); var classBody = this.startNode(); var hadConstructor = false; classBody.body = []; this.expect(types$1$2.braceL); while (this.type !== types$1$2.braceR) { var element = this.parseClassElement(node.superClass !== null); if (element) { classBody.body.push(element); if (element.type === "MethodDefinition" && element.kind === "constructor") { if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); } hadConstructor = true; } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted$2(privateNameMap, element)) { this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); } } } this.strict = oldStrict; this.next(); node.body = this.finishNode(classBody, "ClassBody"); this.exitClassBody(); return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") }; pp$8$2.parseClassElement = function(constructorAllowsSuper) { if (this.eat(types$1$2.semi)) { return null } var ecmaVersion = this.options.ecmaVersion; var node = this.startNode(); var keyName = ""; var isGenerator = false; var isAsync = false; var kind = "method"; var isStatic = false; if (this.eatContextual("static")) { // Parse static init block if (ecmaVersion >= 13 && this.eat(types$1$2.braceL)) { this.parseClassStaticBlock(node); return node } if (this.isClassElementNameStart() || this.type === types$1$2.star) { isStatic = true; } else { keyName = "static"; } } node.static = isStatic; if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { if ((this.isClassElementNameStart() || this.type === types$1$2.star) && !this.canInsertSemicolon()) { isAsync = true; } else { keyName = "async"; } } if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1$2.star)) { isGenerator = true; } if (!keyName && !isAsync && !isGenerator) { var lastValue = this.value; if (this.eatContextual("get") || this.eatContextual("set")) { if (this.isClassElementNameStart()) { kind = lastValue; } else { keyName = lastValue; } } } // Parse element name if (keyName) { // 'async', 'get', 'set', or 'static' were not a keyword contextually. // The last token is any of those. Make it the element name. node.computed = false; node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); node.key.name = keyName; this.finishNode(node.key, "Identifier"); } else { this.parseClassElementName(node); } // Parse element value if (ecmaVersion < 13 || this.type === types$1$2.parenL || kind !== "method" || isGenerator || isAsync) { var isConstructor = !node.static && checkKeyName$2(node, "constructor"); var allowsDirectSuper = isConstructor && constructorAllowsSuper; // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } node.kind = isConstructor ? "constructor" : kind; this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); } else { this.parseClassField(node); } return node }; pp$8$2.isClassElementNameStart = function() { return ( this.type === types$1$2.name || this.type === types$1$2.privateId || this.type === types$1$2.num || this.type === types$1$2.string || this.type === types$1$2.bracketL || this.type.keyword ) }; pp$8$2.parseClassElementName = function(element) { if (this.type === types$1$2.privateId) { if (this.value === "constructor") { this.raise(this.start, "Classes can't have an element named '#constructor'"); } element.computed = false; element.key = this.parsePrivateIdent(); } else { this.parsePropertyName(element); } }; pp$8$2.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { // Check key and flags var key = method.key; if (method.kind === "constructor") { 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"); } } else if (method.static && checkKeyName$2(method, "prototype")) { this.raise(key.start, "Classes may not have a static property named prototype"); } // Parse value var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); // Check value if (method.kind === "get" && value.params.length !== 0) { this.raiseRecoverable(value.start, "getter should have no params"); } if (method.kind === "set" && value.params.length !== 1) { this.raiseRecoverable(value.start, "setter should have exactly one param"); } if (method.kind === "set" && value.params[0].type === "RestElement") { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } return this.finishNode(method, "MethodDefinition") }; pp$8$2.parseClassField = function(field) { if (checkKeyName$2(field, "constructor")) { this.raise(field.key.start, "Classes can't have a field named 'constructor'"); } else if (field.static && checkKeyName$2(field, "prototype")) { this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); } if (this.eat(types$1$2.eq)) { // To raise SyntaxError if 'arguments' exists in the initializer. var scope = this.currentThisScope(); var inClassFieldInit = scope.inClassFieldInit; scope.inClassFieldInit = true; field.value = this.parseMaybeAssign(); scope.inClassFieldInit = inClassFieldInit; } else { field.value = null; } this.semicolon(); return this.finishNode(field, "PropertyDefinition") }; pp$8$2.parseClassStaticBlock = function(node) { node.body = []; var oldLabels = this.labels; this.labels = []; this.enterScope(SCOPE_CLASS_STATIC_BLOCK$2 | SCOPE_SUPER$2); while (this.type !== types$1$2.braceR) { var stmt = this.parseStatement(null); node.body.push(stmt); } this.next(); this.exitScope(); this.labels = oldLabels; return this.finishNode(node, "StaticBlock") }; pp$8$2.parseClassId = function(node, isStatement) { if (this.type === types$1$2.name) { node.id = this.parseIdent(); if (isStatement) { this.checkLValSimple(node.id, BIND_LEXICAL$2, false); } } else { if (isStatement === true) { this.unexpected(); } node.id = null; } }; pp$8$2.parseClassSuper = function(node) { node.superClass = this.eat(types$1$2._extends) ? this.parseExprSubscripts(null, false) : null; }; pp$8$2.enterClassBody = function() { var element = {declared: Object.create(null), used: []}; this.privateNameStack.push(element); return element.declared }; pp$8$2.exitClassBody = function() { var ref = this.privateNameStack.pop(); var declared = ref.declared; var used = ref.used; if (!this.options.checkPrivateFields) { return } var len = this.privateNameStack.length; var parent = len === 0 ? null : this.privateNameStack[len - 1]; for (var i = 0; i < used.length; ++i) { var id = used[i]; if (!hasOwn$2(declared, id.name)) { if (parent) { parent.used.push(id); } else { this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); } } } }; function isPrivateNameConflicted$2(privateNameMap, element) { var name = element.key.name; var curr = privateNameMap[name]; var next = "true"; if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { next = (element.static ? "s" : "i") + element.kind; } // `class { get #a(){}; static set #a(_){} }` is also conflict. if ( curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget" ) { privateNameMap[name] = "true"; return false } else if (!curr) { privateNameMap[name] = next; return false } else { return true } } function checkKeyName$2(node, name) { var computed = node.computed; var key = node.key; return !computed && ( key.type === "Identifier" && key.name === name || key.type === "Literal" && key.value === name ) } // Parses module export declaration. pp$8$2.parseExportAllDeclaration = function(node, exports) { if (this.options.ecmaVersion >= 11) { if (this.eatContextual("as")) { node.exported = this.parseModuleExportName(); this.checkExport(exports, node.exported, this.lastTokStart); } else { node.exported = null; } } this.expectContextual("from"); if (this.type !== types$1$2.string) { this.unexpected(); } node.source = this.parseExprAtom(); this.semicolon(); return this.finishNode(node, "ExportAllDeclaration") }; pp$8$2.parseExport = function(node, exports) { this.next(); // export * from '...' if (this.eat(types$1$2.star)) { return this.parseExportAllDeclaration(node, exports) } if (this.eat(types$1$2._default)) { // export default ... this.checkExport(exports, "default", this.lastTokStart); node.declaration = this.parseExportDefaultDeclaration(); return this.finishNode(node, "ExportDefaultDeclaration") } // export var|const|let|function|class ... if (this.shouldParseExportStatement()) { node.declaration = this.parseExportDeclaration(node); if (node.declaration.type === "VariableDeclaration") { this.checkVariableExport(exports, node.declaration.declarations); } else { this.checkExport(exports, node.declaration.id, 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$1$2.string) { this.unexpected(); } node.source = this.parseExprAtom(); } else { for (var i = 0, list = node.specifiers; i < list.length; i += 1) { // check for keywords used as local names var spec = list[i]; this.checkUnreserved(spec.local); // check if export is defined this.checkLocalExport(spec.local); if (spec.local.type === "Literal") { this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); } } node.source = null; } this.semicolon(); } return this.finishNode(node, "ExportNamedDeclaration") }; pp$8$2.parseExportDeclaration = function(node) { return this.parseStatement(null) }; pp$8$2.parseExportDefaultDeclaration = function() { var isAsync; if (this.type === types$1$2._function || (isAsync = this.isAsyncFunction())) { var fNode = this.startNode(); this.next(); if (isAsync) { this.next(); } return this.parseFunction(fNode, FUNC_STATEMENT$1$1 | FUNC_NULLABLE_ID$1$1, false, isAsync) } else if (this.type === types$1$2._class) { var cNode = this.startNode(); return this.parseClass(cNode, "nullableID") } else { var declaration = this.parseMaybeAssign(); this.semicolon(); return declaration } }; pp$8$2.checkExport = function(exports, name, pos) { if (!exports) { return } if (typeof name !== "string") { name = name.type === "Identifier" ? name.name : name.value; } if (hasOwn$2(exports, name)) { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } exports[name] = true; }; pp$8$2.checkPatternExport = function(exports, pat) { var type = pat.type; if (type === "Identifier") { this.checkExport(exports, pat, pat.start); } else if (type === "ObjectPattern") { for (var i = 0, list = pat.properties; i < list.length; i += 1) { var prop = list[i]; this.checkPatternExport(exports, prop); } } else if (type === "ArrayPattern") { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { var elt = list$1[i$1]; if (elt) { this.checkPatternExport(exports, elt); } } } else if (type === "Property") { this.checkPatternExport(exports, pat.value); } else if (type === "AssignmentPattern") { this.checkPatternExport(exports, pat.left); } else if (type === "RestElement") { this.checkPatternExport(exports, pat.argument); } else if (type === "ParenthesizedExpression") { this.checkPatternExport(exports, pat.expression); } }; pp$8$2.checkVariableExport = function(exports, decls) { if (!exports) { return } for (var i = 0, list = decls; i < list.length; i += 1) { var decl = list[i]; this.checkPatternExport(exports, decl.id); } }; pp$8$2.shouldParseExportStatement = function() { return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction() }; // Parses a comma-separated list of module exports. pp$8$2.parseExportSpecifier = function(exports) { var node = this.startNode(); node.local = this.parseModuleExportName(); node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; this.checkExport( exports, node.exported, node.exported.start ); return this.finishNode(node, "ExportSpecifier") }; pp$8$2.parseExportSpecifiers = function(exports) { var nodes = [], first = true; // export { x, y as z } [from '...'] this.expect(types$1$2.braceL); while (!this.eat(types$1$2.braceR)) { if (!first) { this.expect(types$1$2.comma); if (this.afterTrailingComma(types$1$2.braceR)) { break } } else { first = false; } nodes.push(this.parseExportSpecifier(exports)); } return nodes }; // Parses import declaration. pp$8$2.parseImport = function(node) { this.next(); // import '...' if (this.type === types$1$2.string) { node.specifiers = empty$1$2; node.source = this.parseExprAtom(); } else { node.specifiers = this.parseImportSpecifiers(); this.expectContextual("from"); node.source = this.type === types$1$2.string ? this.parseExprAtom() : this.unexpected(); } this.semicolon(); return this.finishNode(node, "ImportDeclaration") }; // Parses a comma-separated list of module imports. pp$8$2.parseImportSpecifier = function() { var node = this.startNode(); node.imported = this.parseModuleExportName(); if (this.eatContextual("as")) { node.local = this.parseIdent(); } else { this.checkUnreserved(node.imported); node.local = node.imported; } this.checkLValSimple(node.local, BIND_LEXICAL$2); return this.finishNode(node, "ImportSpecifier") }; pp$8$2.parseImportDefaultSpecifier = function() { // import defaultObj, { x, y as z } from '...' var node = this.startNode(); node.local = this.parseIdent(); this.checkLValSimple(node.local, BIND_LEXICAL$2); return this.finishNode(node, "ImportDefaultSpecifier") }; pp$8$2.parseImportNamespaceSpecifier = function() { var node = this.startNode(); this.next(); this.expectContextual("as"); node.local = this.parseIdent(); this.checkLValSimple(node.local, BIND_LEXICAL$2); return this.finishNode(node, "ImportNamespaceSpecifier") }; pp$8$2.parseImportSpecifiers = function() { var nodes = [], first = true; if (this.type === types$1$2.name) { nodes.push(this.parseImportDefaultSpecifier()); if (!this.eat(types$1$2.comma)) { return nodes } } if (this.type === types$1$2.star) { nodes.push(this.parseImportNamespaceSpecifier()); return nodes } this.expect(types$1$2.braceL); while (!this.eat(types$1$2.braceR)) { if (!first) { this.expect(types$1$2.comma); if (this.afterTrailingComma(types$1$2.braceR)) { break } } else { first = false; } nodes.push(this.parseImportSpecifier()); } return nodes }; pp$8$2.parseModuleExportName = function() { if (this.options.ecmaVersion >= 13 && this.type === types$1$2.string) { var stringLiteral = this.parseLiteral(this.value); if (loneSurrogate$2.test(stringLiteral.value)) { this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); } return stringLiteral } return this.parseIdent(true) }; // Set `ExpressionStatement#directive` property for directive prologues. pp$8$2.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$8$2.isDirectiveCandidate = function(statement) { return ( this.options.ecmaVersion >= 5 && statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && // Reject parenthesized strings. (this.input[statement.start] === "\"" || this.input[statement.start] === "'") ) }; var pp$7$2 = Parser$2.prototype; // Convert existing expression atom to assignable pattern // if possible. pp$7$2.toAssignable = function(node, isBinding, refDestructuringErrors) { if (this.options.ecmaVersion >= 6 && node) { switch (node.type) { case "Identifier": if (this.inAsync && node.name === "await") { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } break case "ObjectPattern": case "ArrayPattern": case "AssignmentPattern": case "RestElement": break case "ObjectExpression": node.type = "ObjectPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } for (var i = 0, list = node.properties; i < list.length; i += 1) { var prop = list[i]; this.toAssignable(prop, isBinding); // Early error: // AssignmentRestProperty[Yield, Await] : // `...` DestructuringAssignmentTarget[Yield, Await] // // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. if ( prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") ) { this.raise(prop.argument.start, "Unexpected token"); } } break case "Property": // AssignmentProperty has type === "Property" if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } this.toAssignable(node.value, isBinding); break case "ArrayExpression": node.type = "ArrayPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } this.toAssignableList(node.elements, isBinding); break case "SpreadElement": node.type = "RestElement"; this.toAssignable(node.argument, isBinding); if (node.argument.type === "AssignmentPattern") { this.raise(node.argument.start, "Rest elements cannot have a default value"); } break case "AssignmentExpression": if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } node.type = "AssignmentPattern"; delete node.operator; this.toAssignable(node.left, isBinding); break case "ParenthesizedExpression": this.toAssignable(node.expression, isBinding, refDestructuringErrors); break case "ChainExpression": this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); break case "MemberExpression": if (!isBinding) { break } default: this.raise(node.start, "Assigning to rvalue"); } } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } return node }; // Convert list of expression atoms to binding list. pp$7$2.toAssignableList = function(exprList, isBinding) { var end = exprList.length; for (var i = 0; i < end; i++) { var elt = exprList[i]; if (elt) { this.toAssignable(elt, isBinding); } } if (end) { var last = exprList[end - 1]; if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") { this.unexpected(last.argument.start); } } return exprList }; // Parses spread element. pp$7$2.parseSpread = function(refDestructuringErrors) { var node = this.startNode(); this.next(); node.argument = this.parseMaybeAssign(false, refDestructuringErrors); return this.finishNode(node, "SpreadElement") }; pp$7$2.parseRestBinding = function() { var node = this.startNode(); this.next(); // RestElement inside of a function parameter must be an identifier if (this.options.ecmaVersion === 6 && this.type !== types$1$2.name) { this.unexpected(); } node.argument = this.parseBindingAtom(); return this.finishNode(node, "RestElement") }; // Parses lvalue (assignable) atom. pp$7$2.parseBindingAtom = function() { if (this.options.ecmaVersion >= 6) { switch (this.type) { case types$1$2.bracketL: var node = this.startNode(); this.next(); node.elements = this.parseBindingList(types$1$2.bracketR, true, true); return this.finishNode(node, "ArrayPattern") case types$1$2.braceL: return this.parseObj(true) } } return this.parseIdent() }; pp$7$2.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) { var elts = [], first = true; while (!this.eat(close)) { if (first) { first = false; } else { this.expect(types$1$2.comma); } if (allowEmpty && this.type === types$1$2.comma) { elts.push(null); } else if (allowTrailingComma && this.afterTrailingComma(close)) { break } else if (this.type === types$1$2.ellipsis) { var rest = this.parseRestBinding(); this.parseBindingListItem(rest); elts.push(rest); if (this.type === types$1$2.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); } this.expect(close); break } else { elts.push(this.parseAssignableListItem(allowModifiers)); } } return elts }; pp$7$2.parseAssignableListItem = function(allowModifiers) { var elem = this.parseMaybeDefault(this.start, this.startLoc); this.parseBindingListItem(elem); return elem }; pp$7$2.parseBindingListItem = function(param) { return param }; // Parses assignment pattern around given atom if possible. pp$7$2.parseMaybeDefault = function(startPos, startLoc, left) { left = left || this.parseBindingAtom(); if (this.options.ecmaVersion < 6 || !this.eat(types$1$2.eq)) { return left } var node = this.startNodeAt(startPos, startLoc); node.left = left; node.right = this.parseMaybeAssign(); return this.finishNode(node, "AssignmentPattern") }; // The following three functions all verify that a node is an lvalue — // something that can be bound, or assigned to. In order to do so, they perform // a variety of checks: // // - Check that none of the bound/assigned-to identifiers are reserved words. // - Record name declarations for bindings in the appropriate scope. // - Check duplicate argument names, if checkClashes is set. // // If a complex binding pattern is encountered (e.g., object and array // destructuring), the entire pattern is recursively checked. // // There are three versions of checkLVal*() appropriate for different // circumstances: // // - checkLValSimple() shall be used if the syntactic construct supports // nothing other than identifiers and member expressions. Parenthesized // expressions are also correctly handled. This is generally appropriate for // constructs for which the spec says // // > It is a Syntax Error if AssignmentTargetType of [the production] is not // > simple. // // It is also appropriate for checking if an identifier is valid and not // defined elsewhere, like import declarations or function/class identifiers. // // Examples where this is used include: // a += …; // import a from '…'; // where a is the node to be checked. // // - checkLValPattern() shall be used if the syntactic construct supports // anything checkLValSimple() supports, as well as object and array // destructuring patterns. This is generally appropriate for constructs for // which the spec says // // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor // > an ArrayLiteral and AssignmentTargetType of [the production] is not // > simple. // // Examples where this is used include: // (a = …); // const a = …; // try { … } catch (a) { … } // where a is the node to be checked. // // - checkLValInnerPattern() shall be used if the syntactic construct supports // anything checkLValPattern() supports, as well as default assignment // patterns, rest elements, and other constructs that may appear within an // object or array destructuring pattern. // // As a special case, function parameters also use checkLValInnerPattern(), // as they also support defaults and rest constructs. // // These functions deliberately support both assignment and binding constructs, // as the logic for both is exceedingly similar. If the node is the target of // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it // should be set to the appropriate BIND_* constant, like BIND_VAR or // BIND_LEXICAL. // // If the function is called with a non-BIND_NONE bindingType, then // additionally a checkClashes object may be specified to allow checking for // duplicate argument names. checkClashes is ignored if the provided construct // is an assignment (i.e., bindingType is BIND_NONE). pp$7$2.checkLValSimple = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE$2; var isBind = bindingType !== BIND_NONE$2; switch (expr.type) { case "Identifier": if (this.strict && this.reservedWordsStrictBind.test(expr.name)) { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } if (isBind) { if (bindingType === BIND_LEXICAL$2 && expr.name === "let") { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } if (checkClashes) { if (hasOwn$2(checkClashes, expr.name)) { this.raiseRecoverable(expr.start, "Argument name clash"); } checkClashes[expr.name] = true; } if (bindingType !== BIND_OUTSIDE$2) { this.declareName(expr.name, bindingType, expr.start); } } break case "ChainExpression": this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); break case "MemberExpression": if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } break case "ParenthesizedExpression": if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } return this.checkLValSimple(expr.expression, bindingType, checkClashes) default: this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); } }; pp$7$2.checkLValPattern = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE$2; switch (expr.type) { case "ObjectPattern": for (var i = 0, list = expr.properties; i < list.length; i += 1) { var prop = list[i]; this.checkLValInnerPattern(prop, bindingType, checkClashes); } break case "ArrayPattern": for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { var elem = list$1[i$1]; if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } } break default: this.checkLValSimple(expr, bindingType, checkClashes); } }; pp$7$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE$2; switch (expr.type) { case "Property": // AssignmentProperty has type === "Property" this.checkLValInnerPattern(expr.value, bindingType, checkClashes); break case "AssignmentPattern": this.checkLValPattern(expr.left, bindingType, checkClashes); break case "RestElement": this.checkLValPattern(expr.argument, bindingType, checkClashes); break default: this.checkLValPattern(expr, bindingType, checkClashes); } }; // The algorithm used to determine whether a regexp can appear at a // given point in the program is loosely based on sweet.js' approach. // See https://github.com/mozilla/sweet.js/wiki/design var TokContext$2 = function TokContext(token, isExpr, preserveSpace, override, generator) { this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override; this.generator = !!generator; }; var types$5 = { b_stat: new TokContext$2("{", false), b_expr: new TokContext$2("{", true), b_tmpl: new TokContext$2("${", false), p_stat: new TokContext$2("(", false), p_expr: new TokContext$2("(", true), q_tmpl: new TokContext$2("`", true, true, function (p) { return p.tryReadTemplateToken(); }), f_stat: new TokContext$2("function", false), f_expr: new TokContext$2("function", true), f_expr_gen: new TokContext$2("function", true, false, null, true), f_gen: new TokContext$2("function", false, false, null, true) }; var pp$6$2 = Parser$2.prototype; pp$6$2.initialContext = function() { return [types$5.b_stat] }; pp$6$2.curContext = function() { return this.context[this.context.length - 1] }; pp$6$2.braceIsBlock = function(prevType) { var parent = this.curContext(); if (parent === types$5.f_expr || parent === types$5.f_stat) { return true } if (prevType === types$1$2.colon && (parent === types$5.b_stat || parent === types$5.b_expr)) { return !parent.isExpr } // The check for `tt.name && exprAllowed` detects whether we are // after a `yield` or `of` construct. See the `updateContext` for // `tt.name`. if (prevType === types$1$2._return || prevType === types$1$2.name && this.exprAllowed) { return lineBreak$2.test(this.input.slice(this.lastTokEnd, this.start)) } if (prevType === types$1$2._else || prevType === types$1$2.semi || prevType === types$1$2.eof || prevType === types$1$2.parenR || prevType === types$1$2.arrow) { return true } if (prevType === types$1$2.braceL) { return parent === types$5.b_stat } if (prevType === types$1$2._var || prevType === types$1$2._const || prevType === types$1$2.name) { return false } return !this.exprAllowed }; pp$6$2.inGeneratorContext = function() { for (var i = this.context.length - 1; i >= 1; i--) { var context = this.context[i]; if (context.token === "function") { return context.generator } } return false }; pp$6$2.updateContext = function(prevType) { var update, type = this.type; if (type.keyword && prevType === types$1$2.dot) { this.exprAllowed = false; } else if (update = type.updateContext) { update.call(this, prevType); } else { this.exprAllowed = type.beforeExpr; } }; // Used to handle egde cases when token context could not be inferred correctly during tokenization phase pp$6$2.overrideContext = function(tokenCtx) { if (this.curContext() !== tokenCtx) { this.context[this.context.length - 1] = tokenCtx; } }; // Token-specific context update code types$1$2.parenR.updateContext = types$1$2.braceR.updateContext = function() { if (this.context.length === 1) { this.exprAllowed = true; return } var out = this.context.pop(); if (out === types$5.b_stat && this.curContext().token === "function") { out = this.context.pop(); } this.exprAllowed = !out.isExpr; }; types$1$2.braceL.updateContext = function(prevType) { this.context.push(this.braceIsBlock(prevType) ? types$5.b_stat : types$5.b_expr); this.exprAllowed = true; }; types$1$2.dollarBraceL.updateContext = function() { this.context.push(types$5.b_tmpl); this.exprAllowed = true; }; types$1$2.parenL.updateContext = function(prevType) { var statementParens = prevType === types$1$2._if || prevType === types$1$2._for || prevType === types$1$2._with || prevType === types$1$2._while; this.context.push(statementParens ? types$5.p_stat : types$5.p_expr); this.exprAllowed = true; }; types$1$2.incDec.updateContext = function() { // tokExprAllowed stays unchanged }; types$1$2._function.updateContext = types$1$2._class.updateContext = function(prevType) { if (prevType.beforeExpr && prevType !== types$1$2._else && !(prevType === types$1$2.semi && this.curContext() !== types$5.p_stat) && !(prevType === types$1$2._return && lineBreak$2.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types$1$2.colon || prevType === types$1$2.braceL) && this.curContext() === types$5.b_stat)) { this.context.push(types$5.f_expr); } else { this.context.push(types$5.f_stat); } this.exprAllowed = false; }; types$1$2.backQuote.updateContext = function() { if (this.curContext() === types$5.q_tmpl) { this.context.pop(); } else { this.context.push(types$5.q_tmpl); } this.exprAllowed = false; }; types$1$2.star.updateContext = function(prevType) { if (prevType === types$1$2._function) { var index = this.context.length - 1; if (this.context[index] === types$5.f_expr) { this.context[index] = types$5.f_expr_gen; } else { this.context[index] = types$5.f_gen; } } this.exprAllowed = true; }; types$1$2.name.updateContext = function(prevType) { var allowed = false; if (this.options.ecmaVersion >= 6 && prevType !== types$1$2.dot) { if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) { allowed = true; } } this.exprAllowed = allowed; }; // A recursive descent parser operates by defining functions for all // syntactic elements, and recursively calling those, each function // advancing the input stream and returning an AST node. Precedence // of constructs (for example, the fact that `!x[1]` means `!(x[1])` // instead of `(!x)[1]` is handled by the fact that the parser // function that parses unary prefix operators is called first, and // in turn calls the function that parses `[]` subscripts — that // way, it'll receive the node for `x[1]` already parsed, and wraps // *that* in the unary operator node. // // Acorn uses an [operator precedence parser][opp] to handle binary // operator precedence, because it is much more compact than using // the technique outlined above, which uses different, nesting // functions to specify precedence, for all of the ten binary // precedence levels that JavaScript defines. // // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser var pp$5$2 = Parser$2.prototype; // Check if property name clashes with already added. // Object/class getters and setters are not allowed to clash — // either with each other or with an init property — and in // strict mode, init properties are also not allowed to be repeated. pp$5$2.checkPropClash = function(prop, propHash, refDestructuringErrors) { if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") { return } if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) { return } var key = prop.key; var name; switch (key.type) { case "Identifier": name = key.name; break case "Literal": name = String(key.value); break default: return } var kind = prop.kind; if (this.options.ecmaVersion >= 6) { if (name === "__proto__" && kind === "init") { if (propHash.proto) { if (refDestructuringErrors) { if (refDestructuringErrors.doubleProto < 0) { refDestructuringErrors.doubleProto = key.start; } } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } } propHash.proto = true; } return } name = "$" + name; var other = propHash[name]; if (other) { var redefinition; if (kind === "init") { redefinition = this.strict && other.init || other.get || other.set; } else { redefinition = other.init || other[kind]; } if (redefinition) { this.raiseRecoverable(key.start, "Redefinition of property"); } } else { other = propHash[name] = { init: false, get: false, set: false }; } other[kind] = true; }; // ### Expression parsing // These nest, from the most general expression type at the top to // 'atomic', nondivisible expression types at the bottom. Most of // the functions will simply let the function(s) below them parse, // and, *if* the syntactic construct they handle is present, wrap // the AST node that the inner parser gave them in another node. // Parse a full expression. The optional arguments are used to // forbid the `in` operator (in for loops initalization expressions) // and provide reference for storing '=' operator inside shorthand // property assignment in contexts where both object expression // and object pattern might appear (so it's possible to raise // delayed syntax error at correct position). pp$5$2.parseExpression = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); if (this.type === types$1$2.comma) { var node = this.startNodeAt(startPos, startLoc); node.expressions = [expr]; while (this.eat(types$1$2.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } return this.finishNode(node, "SequenceExpression") } return expr }; // Parse an assignment expression. This includes applications of // operators like `+=`. pp$5$2.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { if (this.isContextual("yield")) { if (this.inGenerator) { return this.parseYield(forInit) } // The tokenizer will assume an expression is allowed after // `yield`, but this isn't that kind of yield else { this.exprAllowed = false; } } var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; if (refDestructuringErrors) { oldParenAssign = refDestructuringErrors.parenthesizedAssign; oldTrailingComma = refDestructuringErrors.trailingComma; oldDoubleProto = refDestructuringErrors.doubleProto; refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; } else { refDestructuringErrors = new DestructuringErrors$2; ownDestructuringErrors = true; } var startPos = this.start, startLoc = this.startLoc; if (this.type === types$1$2.parenL || this.type === types$1$2.name) { this.potentialArrowAt = this.start; this.potentialArrowInForAwait = forInit === "await"; } var left = this.parseMaybeConditional(forInit, refDestructuringErrors); if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } if (this.type.isAssign) { var node = this.startNodeAt(startPos, startLoc); node.operator = this.value; if (this.type === types$1$2.eq) { left = this.toAssignable(left, false, refDestructuringErrors); } if (!ownDestructuringErrors) { refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; } if (refDestructuringErrors.shorthandAssign >= left.start) { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly if (this.type === types$1$2.eq) { this.checkLValPattern(left); } else { this.checkLValSimple(left); } node.left = left; this.next(); node.right = this.parseMaybeAssign(forInit); if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; } return this.finishNode(node, "AssignmentExpression") } else { if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } } if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } return left }; // Parse a ternary conditional (`?:`) operator. pp$5$2.parseMaybeConditional = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprOps(forInit, refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } if (this.eat(types$1$2.question)) { var node = this.startNodeAt(startPos, startLoc); node.test = expr; node.consequent = this.parseMaybeAssign(); this.expect(types$1$2.colon); node.alternate = this.parseMaybeAssign(forInit); return this.finishNode(node, "ConditionalExpression") } return expr }; // Start the precedence parser. pp$5$2.parseExprOps = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) }; // Parse binary operators with the operator precedence parsing // algorithm. `left` is the left-hand side of the operator. // `minPrec` provides context that allows the function to stop and // defer further parser to one of its callers when it encounters an // operator that has a lower precedence than the set it is parsing. pp$5$2.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { var prec = this.type.binop; if (prec != null && (!forInit || this.type !== types$1$2._in)) { if (prec > minPrec) { var logical = this.type === types$1$2.logicalOR || this.type === types$1$2.logicalAND; var coalesce = this.type === types$1$2.coalesce; if (coalesce) { // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. prec = types$1$2.logicalAND.binop; } var op = this.value; this.next(); var startPos = this.start, startLoc = this.startLoc; var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); if ((logical && this.type === types$1$2.coalesce) || (coalesce && (this.type === types$1$2.logicalOR || this.type === types$1$2.logicalAND))) { this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); } return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) } } return left }; pp$5$2.buildBinary = function(startPos, startLoc, left, right, op, logical) { if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); } var node = this.startNodeAt(startPos, startLoc); node.left = left; node.operator = op; node.right = right; return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") }; // Parse unary operators, both prefix and postfix. pp$5$2.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { var startPos = this.start, startLoc = this.startLoc, expr; if (this.isContextual("await") && this.canAwait) { expr = this.parseAwait(forInit); sawUnary = true; } else if (this.type.prefix) { var node = this.startNode(), update = this.type === types$1$2.incDec; node.operator = this.value; node.prefix = true; this.next(); node.argument = this.parseMaybeUnary(null, true, update, forInit); this.checkExpressionErrors(refDestructuringErrors, true); if (update) { this.checkLValSimple(node.argument); } else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } else if (node.operator === "delete" && isPrivateFieldAccess$2(node.argument)) { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } else { sawUnary = true; } expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); } else if (!sawUnary && this.type === types$1$2.privateId) { if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { this.unexpected(); } expr = this.parsePrivateIdent(); // only could be private fields in 'in', such as #x in obj if (this.type !== types$1$2._in) { this.unexpected(); } } else { expr = this.parseExprSubscripts(refDestructuringErrors, forInit); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } while (this.type.postfix && !this.canInsertSemicolon()) { var node$1 = this.startNodeAt(startPos, startLoc); node$1.operator = this.value; node$1.prefix = false; node$1.argument = expr; this.checkLValSimple(expr); this.next(); expr = this.finishNode(node$1, "UpdateExpression"); } } if (!incDec && this.eat(types$1$2.starstar)) { if (sawUnary) { this.unexpected(this.lastTokStart); } else { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) } } else { return expr } }; function isPrivateFieldAccess$2(node) { return ( node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess$2(node.expression) ) } // Parse call, dot, and `[]`-subscript expressions. pp$5$2.parseExprSubscripts = function(refDestructuringErrors, forInit) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprAtom(refDestructuringErrors, forInit); if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") { return expr } var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); if (refDestructuringErrors && result.type === "MemberExpression") { if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } } return result }; pp$5$2.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.potentialArrowAt === base.start; var optionalChained = false; while (true) { var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); if (element.optional) { optionalChained = true; } if (element === base || element.type === "ArrowFunctionExpression") { if (optionalChained) { var chainNode = this.startNodeAt(startPos, startLoc); chainNode.expression = element; element = this.finishNode(chainNode, "ChainExpression"); } return element } base = element; } }; pp$5$2.shouldParseAsyncArrow = function() { return !this.canInsertSemicolon() && this.eat(types$1$2.arrow) }; pp$5$2.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit) }; pp$5$2.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { var optionalSupported = this.options.ecmaVersion >= 11; var optional = optionalSupported && this.eat(types$1$2.questionDot); if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } var computed = this.eat(types$1$2.bracketL); if (computed || (optional && this.type !== types$1$2.parenL && this.type !== types$1$2.backQuote) || this.eat(types$1$2.dot)) { var node = this.startNodeAt(startPos, startLoc); node.object = base; if (computed) { node.property = this.parseExpression(); this.expect(types$1$2.bracketR); } else if (this.type === types$1$2.privateId && base.type !== "Super") { node.property = this.parsePrivateIdent(); } else { node.property = this.parseIdent(this.options.allowReserved !== "never"); } node.computed = !!computed; if (optionalSupported) { node.optional = optional; } base = this.finishNode(node, "MemberExpression"); } else if (!noCalls && this.eat(types$1$2.parenL)) { var refDestructuringErrors = new DestructuringErrors$2, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; var exprList = this.parseExprList(types$1$2.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) { 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.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit) } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; var node$1 = this.startNodeAt(startPos, startLoc); node$1.callee = base; node$1.arguments = exprList; if (optionalSupported) { node$1.optional = optional; } base = this.finishNode(node$1, "CallExpression"); } else if (this.type === types$1$2.backQuote) { if (optional || optionalChained) { this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); } var node$2 = this.startNodeAt(startPos, startLoc); node$2.tag = base; node$2.quasi = this.parseTemplate({isTagged: true}); base = this.finishNode(node$2, "TaggedTemplateExpression"); } return base }; // Parse an atomic expression — either a single token that is an // expression, an expression started by a keyword like `function` or // `new`, or an expression wrapped in punctuation like `()`, `[]`, // or `{}`. pp$5$2.parseExprAtom = function(refDestructuringErrors, forInit, forNew) { // 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$1$2.slash) { this.readRegexp(); } var node, canBeArrow = this.potentialArrowAt === this.start; switch (this.type) { case types$1$2._super: if (!this.allowSuper) { this.raise(this.start, "'super' keyword outside a method"); } node = this.startNode(); this.next(); if (this.type === types$1$2.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$1$2.dot && this.type !== types$1$2.bracketL && this.type !== types$1$2.parenL) { this.unexpected(); } return this.finishNode(node, "Super") case types$1$2._this: node = this.startNode(); this.next(); return this.finishNode(node, "ThisExpression") case types$1$2.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$1$2._function)) { this.overrideContext(types$5.f_expr); return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit) } if (canBeArrow && !this.canInsertSemicolon()) { if (this.eat(types$1$2.arrow)) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) } if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1$2.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { id = this.parseIdent(false); if (this.canInsertSemicolon() || !this.eat(types$1$2.arrow)) { this.unexpected(); } return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit) } } return id case types$1$2.regexp: var value = this.value; node = this.parseLiteral(value.value); node.regex = {pattern: value.pattern, flags: value.flags}; return node case types$1$2.num: case types$1$2.string: return this.parseLiteral(this.value) case types$1$2._null: case types$1$2._true: case types$1$2._false: node = this.startNode(); node.value = this.type === types$1$2._null ? null : this.type === types$1$2._true; node.raw = this.type.keyword; this.next(); return this.finishNode(node, "Literal") case types$1$2.parenL: var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); if (refDestructuringErrors) { if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) { refDestructuringErrors.parenthesizedAssign = start; } if (refDestructuringErrors.parenthesizedBind < 0) { refDestructuringErrors.parenthesizedBind = start; } } return expr case types$1$2.bracketL: node = this.startNode(); this.next(); node.elements = this.parseExprList(types$1$2.bracketR, true, true, refDestructuringErrors); return this.finishNode(node, "ArrayExpression") case types$1$2.braceL: this.overrideContext(types$5.b_expr); return this.parseObj(false, refDestructuringErrors) case types$1$2._function: node = this.startNode(); this.next(); return this.parseFunction(node, 0) case types$1$2._class: return this.parseClass(this.startNode(), false) case types$1$2._new: return this.parseNew() case types$1$2.backQuote: return this.parseTemplate() case types$1$2._import: if (this.options.ecmaVersion >= 11) { return this.parseExprImport(forNew) } else { return this.unexpected() } default: return this.parseExprAtomDefault() } }; pp$5$2.parseExprAtomDefault = function() { this.unexpected(); }; pp$5$2.parseExprImport = function(forNew) { var node = this.startNode(); // Consume `import` as an identifier for `import.meta`. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } var meta = this.parseIdent(true); if (this.type === types$1$2.parenL && !forNew) { return this.parseDynamicImport(node) } else if (this.type === types$1$2.dot) { node.meta = meta; return this.parseImportMeta(node) } else { this.unexpected(); } }; pp$5$2.parseDynamicImport = function(node) { this.next(); // skip `(` // Parse node.source. node.source = this.parseMaybeAssign(); // Verify ending. if (!this.eat(types$1$2.parenR)) { var errorPos = this.start; if (this.eat(types$1$2.comma) && this.eat(types$1$2.parenR)) { this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); } else { this.unexpected(errorPos); } } return this.finishNode(node, "ImportExpression") }; pp$5$2.parseImportMeta = function(node) { this.next(); // skip `.` var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "meta") { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } if (containsEsc) { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } return this.finishNode(node, "MetaProperty") }; pp$5$2.parseLiteral = function(value) { var node = this.startNode(); node.value = value; node.raw = this.input.slice(this.start, this.end); if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } this.next(); return this.finishNode(node, "Literal") }; pp$5$2.parseParenExpression = function() { this.expect(types$1$2.parenL); var val = this.parseExpression(); this.expect(types$1$2.parenR); return val }; pp$5$2.shouldParseArrow = function(exprList) { return !this.canInsertSemicolon() }; pp$5$2.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; if (this.options.ecmaVersion >= 6) { this.next(); var innerStartPos = this.start, innerStartLoc = this.startLoc; var exprList = [], first = true, lastIsComma = false; var refDestructuringErrors = new DestructuringErrors$2, 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$1$2.parenR) { first ? first = false : this.expect(types$1$2.comma); if (allowTrailingComma && this.afterTrailingComma(types$1$2.parenR, true)) { lastIsComma = true; break } else if (this.type === types$1$2.ellipsis) { spreadStart = this.start; exprList.push(this.parseParenItem(this.parseRestBinding())); if (this.type === types$1$2.comma) { this.raiseRecoverable( this.start, "Comma is not permitted after the rest element" ); } break } else { exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); } } var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; this.expect(types$1$2.parenR); if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1$2.arrow)) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; return this.parseParenArrowList(startPos, startLoc, exprList, forInit) } if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } if (spreadStart) { this.unexpected(spreadStart); } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; if (exprList.length > 1) { val = this.startNodeAt(innerStartPos, innerStartLoc); val.expressions = exprList; this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); } else { val = exprList[0]; } } else { val = this.parseParenExpression(); } if (this.options.preserveParens) { var par = this.startNodeAt(startPos, startLoc); par.expression = val; return this.finishNode(par, "ParenthesizedExpression") } else { return val } }; pp$5$2.parseParenItem = function(item) { return item }; pp$5$2.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit) }; // New's precedence is slightly tricky. It must allow its argument to // be a `[]` or dot subscript expression, but not a call — at least, // not without wrapping it in parentheses. Thus, it uses the noCalls // argument to parseSubscripts to prevent it from consuming the // argument list. var empty$3 = []; pp$5$2.parseNew = function() { if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } var node = this.startNode(); var meta = this.parseIdent(true); if (this.options.ecmaVersion >= 6 && this.eat(types$1$2.dot)) { node.meta = meta; var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "target") { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } if (containsEsc) { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } if (!this.allowNewDotTarget) { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); } return this.finishNode(node, "MetaProperty") } var startPos = this.start, startLoc = this.startLoc; node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false); if (this.eat(types$1$2.parenL)) { node.arguments = this.parseExprList(types$1$2.parenR, this.options.ecmaVersion >= 8, false); } else { node.arguments = empty$3; } return this.finishNode(node, "NewExpression") }; // Parse template expression. pp$5$2.parseTemplateElement = function(ref) { var isTagged = ref.isTagged; var elem = this.startNode(); if (this.type === types$1$2.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$1$2.backQuote; return this.finishNode(elem, "TemplateElement") }; pp$5$2.parseTemplate = function(ref) { if ( ref === void 0 ) ref = {}; var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; var node = this.startNode(); this.next(); node.expressions = []; var curElt = this.parseTemplateElement({isTagged: isTagged}); node.quasis = [curElt]; while (!curElt.tail) { if (this.type === types$1$2.eof) { this.raise(this.pos, "Unterminated template literal"); } this.expect(types$1$2.dollarBraceL); node.expressions.push(this.parseExpression()); this.expect(types$1$2.braceR); node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); } this.next(); return this.finishNode(node, "TemplateLiteral") }; pp$5$2.isAsyncProp = function(prop) { return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types$1$2.name || this.type === types$1$2.num || this.type === types$1$2.string || this.type === types$1$2.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1$2.star)) && !lineBreak$2.test(this.input.slice(this.lastTokEnd, this.start)) }; // Parse an object literal or binding pattern. pp$5$2.parseObj = function(isPattern, refDestructuringErrors) { var node = this.startNode(), first = true, propHash = {}; node.properties = []; this.next(); while (!this.eat(types$1$2.braceR)) { if (!first) { this.expect(types$1$2.comma); if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1$2.braceR)) { break } } else { first = false; } var prop = this.parseProperty(isPattern, refDestructuringErrors); if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } node.properties.push(prop); } return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") }; pp$5$2.parseProperty = function(isPattern, refDestructuringErrors) { var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; if (this.options.ecmaVersion >= 9 && this.eat(types$1$2.ellipsis)) { if (isPattern) { prop.argument = this.parseIdent(false); if (this.type === types$1$2.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); } return this.finishNode(prop, "RestElement") } // Parse argument. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); // To disallow trailing comma via `this.toAssignable()`. if (this.type === types$1$2.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$1$2.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$1$2.star); this.parsePropertyName(prop); } else { isAsync = false; } this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); return this.finishNode(prop, "Property") }; pp$5$2.parseGetterSetter = function(prop) { 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"); } } }; pp$5$2.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { if ((isGenerator || isAsync) && this.type === types$1$2.colon) { this.unexpected(); } if (this.eat(types$1$2.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$1$2.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$1$2.comma && this.type !== types$1$2.braceR && this.type !== types$1$2.eq)) { if (isGenerator || isAsync) { this.unexpected(); } this.parseGetterSetter(prop); } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { if (isGenerator || isAsync) { this.unexpected(); } this.checkUnreserved(prop.key); if (prop.key.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = startPos; } prop.kind = "init"; if (isPattern) { prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); } else if (this.type === types$1$2.eq && refDestructuringErrors) { if (refDestructuringErrors.shorthandAssign < 0) { refDestructuringErrors.shorthandAssign = this.start; } prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); } else { prop.value = this.copyNode(prop.key); } prop.shorthand = true; } else { this.unexpected(); } }; pp$5$2.parsePropertyName = function(prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(types$1$2.bracketL)) { prop.computed = true; prop.key = this.parseMaybeAssign(); this.expect(types$1$2.bracketR); return prop.key } else { prop.computed = false; } } return prop.key = this.type === types$1$2.num || this.type === types$1$2.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") }; // Initialize empty function node. pp$5$2.initFunction = function(node) { node.id = null; if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } if (this.options.ecmaVersion >= 8) { node.async = false; } }; // Parse object or class method. pp$5$2.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.initFunction(node); if (this.options.ecmaVersion >= 6) { node.generator = isGenerator; } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags$2(isAsync, node.generator) | SCOPE_SUPER$2 | (allowDirectSuper ? SCOPE_DIRECT_SUPER$2 : 0)); this.expect(types$1$2.parenL); node.params = this.parseBindingList(types$1$2.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); this.parseFunctionBody(node, false, true, false); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "FunctionExpression") }; // Parse arrow function expression with given parameters. pp$5$2.parseArrowExpression = function(node, params, isAsync, forInit) { var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.enterScope(functionFlags$2(isAsync, false) | SCOPE_ARROW$2); this.initFunction(node); if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; node.params = this.toAssignableList(params, true); this.parseFunctionBody(node, true, false, forInit); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "ArrowFunctionExpression") }; // Parse function body and check parameters. pp$5$2.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { var isExpression = isArrowFunction && this.type !== types$1$2.braceL; var oldStrict = this.strict, useStrict = false; if (isExpression) { node.body = this.parseMaybeAssign(forInit); node.expression = true; this.checkParams(node, false); } else { var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); if (!oldStrict || nonSimple) { useStrict = this.strictDirective(this.end); // If this is a strict mode function, verify that argument names // are not repeated, and it does not try to bind the words `eval` // or `arguments`. if (useStrict && nonSimple) { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } } // Start a new scope with regard to labels and the `inFunction` // flag (restore them to their old value afterwards). var oldLabels = this.labels; this.labels = []; if (useStrict) { this.strict = true; } // Add the params to varDeclaredNames to ensure that an error is thrown // if a let/const declaration in the function clashes with one of the params. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE$2); } node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); node.expression = false; this.adaptDirectivePrologue(node.body.body); this.labels = oldLabels; } this.exitScope(); }; pp$5$2.isSimpleParamList = function(params) { for (var i = 0, list = params; i < list.length; i += 1) { var param = list[i]; if (param.type !== "Identifier") { return false } } return true }; // Checks function params for various disallowed patterns such as using "eval" // or "arguments" and duplicate parameters. pp$5$2.checkParams = function(node, allowDuplicates) { var nameHash = Object.create(null); for (var i = 0, list = node.params; i < list.length; i += 1) { var param = list[i]; this.checkLValInnerPattern(param, BIND_VAR$2, allowDuplicates ? null : nameHash); } }; // Parses a comma-separated list of expressions, and returns them as // an array. `close` is the token type that ends the list, and // `allowEmpty` can be turned on to allow subsequent commas with // nothing in between them to be parsed as `null` (which is needed // for array literals). pp$5$2.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { var elts = [], first = true; while (!this.eat(close)) { if (!first) { this.expect(types$1$2.comma); if (allowTrailingComma && this.afterTrailingComma(close)) { break } } else { first = false; } var elt = (void 0); if (allowEmpty && this.type === types$1$2.comma) { elt = null; } else if (this.type === types$1$2.ellipsis) { elt = this.parseSpread(refDestructuringErrors); if (refDestructuringErrors && this.type === types$1$2.comma && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this.start; } } else { elt = this.parseMaybeAssign(false, refDestructuringErrors); } elts.push(elt); } return elts }; pp$5$2.checkUnreserved = function(ref) { var start = ref.start; var end = ref.end; var name = ref.name; if (this.inGenerator && name === "yield") { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } if (this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } if (this.currentThisScope().inClassFieldInit && name === "arguments") { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } if (this.inClassStaticBlock && (name === "arguments" || name === "await")) { this.raise(start, ("Cannot use " + name + " in class static initialization block")); } if (this.keywords.test(name)) { this.raise(start, ("Unexpected keyword '" + name + "'")); } if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) { return } var re = this.strict ? this.reservedWordsStrict : this.reservedWords; if (re.test(name)) { if (!this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); } }; // Parse the next token as an identifier. If `liberal` is true (used // when parsing properties), it will also convert keywords into // identifiers. pp$5$2.parseIdent = function(liberal) { var node = this.parseIdentNode(); this.next(!!liberal); this.finishNode(node, "Identifier"); if (!liberal) { this.checkUnreserved(node); if (node.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = node.start; } } return node }; pp$5$2.parseIdentNode = function() { var node = this.startNode(); if (this.type === types$1$2.name) { node.name = this.value; } else if (this.type.keyword) { node.name = this.type.keyword; // To fix https://github.com/acornjs/acorn/issues/575 // `class` and `function` keywords push new context into this.context. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { this.context.pop(); } } else { this.unexpected(); } return node }; pp$5$2.parsePrivateIdent = function() { var node = this.startNode(); if (this.type === types$1$2.privateId) { node.name = this.value; } else { this.unexpected(); } this.next(); this.finishNode(node, "PrivateIdentifier"); // For validating existence if (this.options.checkPrivateFields) { if (this.privateNameStack.length === 0) { this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); } else { this.privateNameStack[this.privateNameStack.length - 1].used.push(node); } } return node }; // Parses yield expression inside generator. pp$5$2.parseYield = function(forInit) { if (!this.yieldPos) { this.yieldPos = this.start; } var node = this.startNode(); this.next(); if (this.type === types$1$2.semi || this.canInsertSemicolon() || (this.type !== types$1$2.star && !this.type.startsExpr)) { node.delegate = false; node.argument = null; } else { node.delegate = this.eat(types$1$2.star); node.argument = this.parseMaybeAssign(forInit); } return this.finishNode(node, "YieldExpression") }; pp$5$2.parseAwait = function(forInit) { if (!this.awaitPos) { this.awaitPos = this.start; } var node = this.startNode(); this.next(); node.argument = this.parseMaybeUnary(null, true, false, forInit); return this.finishNode(node, "AwaitExpression") }; var pp$4$2 = Parser$2.prototype; // This function is used to raise exceptions on parse errors. It // takes an offset integer (into the current `input`) to indicate // the location of the error, attaches the position to the end // of the error message, and then raises a `SyntaxError` with that // message. pp$4$2.raise = function(pos, message) { var loc = getLineInfo$2(this.input, pos); message += " (" + loc.line + ":" + loc.column + ")"; var err = new SyntaxError(message); err.pos = pos; err.loc = loc; err.raisedAt = this.pos; throw err }; pp$4$2.raiseRecoverable = pp$4$2.raise; pp$4$2.curPosition = function() { if (this.options.locations) { return new Position$2(this.curLine, this.pos - this.lineStart) } }; var pp$3$2 = Parser$2.prototype; var Scope$3 = 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 = []; // A switch to disallow the identifier reference 'arguments' this.inClassFieldInit = false; }; // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. pp$3$2.enterScope = function(flags) { this.scopeStack.push(new Scope$3(flags)); }; pp$3$2.exitScope = function() { this.scopeStack.pop(); }; // The spec says: // > At the top level of a function, or script, function declarations are // > treated like var declarations rather than like lexical declarations. pp$3$2.treatFunctionsAsVarInScope = function(scope) { return (scope.flags & SCOPE_FUNCTION$2) || !this.inModule && (scope.flags & SCOPE_TOP$2) }; pp$3$2.declareName = function(name, bindingType, pos) { var redeclared = false; if (bindingType === BIND_LEXICAL$2) { 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$2)) { delete this.undefinedExports[name]; } } else if (bindingType === BIND_SIMPLE_CATCH$2) { var scope$1 = this.currentScope(); scope$1.lexical.push(name); } else if (bindingType === BIND_FUNCTION$2) { 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$2) && 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$2)) { delete this.undefinedExports[name]; } if (scope$3.flags & SCOPE_VAR$2) { break } } } if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } }; pp$3$2.checkLocalExport = function(id) { // scope.functions must be empty as Module code is always strict. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) { this.undefinedExports[id.name] = id; } }; pp$3$2.currentScope = function() { return this.scopeStack[this.scopeStack.length - 1] }; pp$3$2.currentVarScope = function() { for (var i = this.scopeStack.length - 1;; i--) { var scope = this.scopeStack[i]; if (scope.flags & SCOPE_VAR$2) { return scope } } }; // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. pp$3$2.currentThisScope = function() { for (var i = this.scopeStack.length - 1;; i--) { var scope = this.scopeStack[i]; if (scope.flags & SCOPE_VAR$2 && !(scope.flags & SCOPE_ARROW$2)) { return scope } } }; var Node$2 = function Node(parser, pos, loc) { this.type = ""; this.start = pos; this.end = 0; if (parser.options.locations) { this.loc = new SourceLocation$2(parser, loc); } if (parser.options.directSourceFile) { this.sourceFile = parser.options.directSourceFile; } if (parser.options.ranges) { this.range = [pos, 0]; } }; // Start an AST node, attaching a start offset. var pp$2$2 = Parser$2.prototype; pp$2$2.startNode = function() { return new Node$2(this, this.start, this.startLoc) }; pp$2$2.startNodeAt = function(pos, loc) { return new Node$2(this, pos, loc) }; // Finish an AST node, adding `type` and `end` properties. function finishNodeAt$2(node, type, pos, loc) { node.type = type; node.end = pos; if (this.options.locations) { node.loc.end = loc; } if (this.options.ranges) { node.range[1] = pos; } return node } pp$2$2.finishNode = function(node, type) { return finishNodeAt$2.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) }; // Finish node at given position pp$2$2.finishNodeAt = function(node, type, pos, loc) { return finishNodeAt$2.call(this, node, type, pos, loc) }; pp$2$2.copyNode = function(node) { var newNode = new Node$2(this, node.start, this.startLoc); for (var prop in node) { newNode[prop] = node[prop]; } return newNode }; // This file contains Unicode properties extracted from the ECMAScript specification. // The lists are extracted like so: // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) // #table-binary-unicode-properties var ecma9BinaryProperties$2 = "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$2 = ecma9BinaryProperties$2 + " Extended_Pictographic"; var ecma11BinaryProperties$2 = ecma10BinaryProperties$2; var ecma12BinaryProperties$2 = ecma11BinaryProperties$2 + " EBase EComp EMod EPres ExtPict"; var ecma13BinaryProperties$2 = ecma12BinaryProperties$2; var ecma14BinaryProperties$2 = ecma13BinaryProperties$2; var unicodeBinaryProperties$2 = { 9: ecma9BinaryProperties$2, 10: ecma10BinaryProperties$2, 11: ecma11BinaryProperties$2, 12: ecma12BinaryProperties$2, 13: ecma13BinaryProperties$2, 14: ecma14BinaryProperties$2 }; // #table-binary-unicode-properties-of-strings var ecma14BinaryPropertiesOfStrings$1 = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"; var unicodeBinaryPropertiesOfStrings$1 = { 9: "", 10: "", 11: "", 12: "", 13: "", 14: ecma14BinaryPropertiesOfStrings$1 }; // #table-unicode-general-category-values var unicodeGeneralCategoryValues$2 = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; // #table-unicode-script-values var ecma9ScriptValues$2 = "Adlam Adlm 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 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$2 = ecma9ScriptValues$2 + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; var ecma11ScriptValues$2 = ecma10ScriptValues$2 + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; var ecma12ScriptValues$2 = ecma11ScriptValues$2 + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; var ecma13ScriptValues$2 = ecma12ScriptValues$2 + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; var ecma14ScriptValues$2 = ecma13ScriptValues$2 + " Hrkt Katakana_Or_Hiragana Kawi Nag_Mundari Nagm Unknown Zzzz"; var unicodeScriptValues$2 = { 9: ecma9ScriptValues$2, 10: ecma10ScriptValues$2, 11: ecma11ScriptValues$2, 12: ecma12ScriptValues$2, 13: ecma13ScriptValues$2, 14: ecma14ScriptValues$2 }; var data$2 = {}; function buildUnicodeData$2(ecmaVersion) { var d = data$2[ecmaVersion] = { binary: wordsRegexp$2(unicodeBinaryProperties$2[ecmaVersion] + " " + unicodeGeneralCategoryValues$2), binaryOfStrings: wordsRegexp$2(unicodeBinaryPropertiesOfStrings$1[ecmaVersion]), nonBinary: { General_Category: wordsRegexp$2(unicodeGeneralCategoryValues$2), Script: wordsRegexp$2(unicodeScriptValues$2[ecmaVersion]) } }; d.nonBinary.Script_Extensions = d.nonBinary.Script; d.nonBinary.gc = d.nonBinary.General_Category; d.nonBinary.sc = d.nonBinary.Script; d.nonBinary.scx = d.nonBinary.Script_Extensions; } for (var i$3 = 0, list$2 = [9, 10, 11, 12, 13, 14]; i$3 < list$2.length; i$3 += 1) { var ecmaVersion$2 = list$2[i$3]; buildUnicodeData$2(ecmaVersion$2); } var pp$1$2 = Parser$2.prototype; var RegExpValidationState$2 = function RegExpValidationState(parser) { this.parser = parser; this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : ""); this.unicodeProperties = data$2[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion]; this.source = ""; this.flags = ""; this.start = 0; this.switchU = false; this.switchV = false; this.switchN = false; this.pos = 0; this.lastIntValue = 0; this.lastStringValue = ""; this.lastAssertionIsQuantifiable = false; this.numCapturingParens = 0; this.maxBackReference = 0; this.groupNames = []; this.backReferenceNames = []; }; RegExpValidationState$2.prototype.reset = function reset (start, pattern, flags) { var unicodeSets = flags.indexOf("v") !== -1; var unicode = flags.indexOf("u") !== -1; this.start = start | 0; this.source = pattern + ""; this.flags = flags; if (unicodeSets && this.parser.options.ecmaVersion >= 15) { this.switchU = true; this.switchV = true; this.switchN = true; } else { this.switchU = unicode && this.parser.options.ecmaVersion >= 6; this.switchV = false; this.switchN = unicode && this.parser.options.ecmaVersion >= 9; } }; RegExpValidationState$2.prototype.raise = function raise (message) { this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); }; // If u flag is given, this returns the code point at the index (it combines a surrogate pair). // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). RegExpValidationState$2.prototype.at = function at (i, forceU) { if ( forceU === void 0 ) forceU = false; var s = this.source; var l = s.length; if (i >= l) { return -1 } var c = s.charCodeAt(i); if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { return c } var next = s.charCodeAt(i + 1); return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c }; RegExpValidationState$2.prototype.nextIndex = function nextIndex (i, forceU) { if ( forceU === void 0 ) forceU = false; var s = this.source; var l = s.length; if (i >= l) { return l } var c = s.charCodeAt(i), next; if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { return i + 1 } return i + 2 }; RegExpValidationState$2.prototype.current = function current (forceU) { if ( forceU === void 0 ) forceU = false; return this.at(this.pos, forceU) }; RegExpValidationState$2.prototype.lookahead = function lookahead (forceU) { if ( forceU === void 0 ) forceU = false; return this.at(this.nextIndex(this.pos, forceU), forceU) }; RegExpValidationState$2.prototype.advance = function advance (forceU) { if ( forceU === void 0 ) forceU = false; this.pos = this.nextIndex(this.pos, forceU); }; RegExpValidationState$2.prototype.eat = function eat (ch, forceU) { if ( forceU === void 0 ) forceU = false; if (this.current(forceU) === ch) { this.advance(forceU); return true } return false }; RegExpValidationState$2.prototype.eatChars = function eatChars (chs, forceU) { if ( forceU === void 0 ) forceU = false; var pos = this.pos; for (var i = 0, list = chs; i < list.length; i += 1) { var ch = list[i]; var current = this.at(pos, forceU); if (current === -1 || current !== ch) { return false } pos = this.nextIndex(pos, forceU); } this.pos = pos; return true }; /** * Validate the flags part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp$1$2.validateRegExpFlags = function(state) { var validFlags = state.validFlags; var flags = state.flags; var u = false; var v = false; 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"); } if (flag === "u") { u = true; } if (flag === "v") { v = true; } } if (this.options.ecmaVersion >= 15 && u && v) { this.raise(state.start, "Invalid regular expression flag"); } }; /** * Validate the pattern part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp$1$2.validateRegExpPattern = function(state) { this.regexp_pattern(state); // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of // parsing contains a |GroupName|, reparse with the goal symbol // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* // exception if _P_ did not conform to the grammar, if any elements of _P_ // were not matched by the parse, or if any Early Error conditions exist. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { state.switchN = true; this.regexp_pattern(state); } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern pp$1$2.regexp_pattern = function(state) { state.pos = 0; state.lastIntValue = 0; state.lastStringValue = ""; state.lastAssertionIsQuantifiable = false; state.numCapturingParens = 0; state.maxBackReference = 0; state.groupNames.length = 0; state.backReferenceNames.length = 0; this.regexp_disjunction(state); if (state.pos !== state.source.length) { // Make the same messages as V8. if (state.eat(0x29 /* ) */)) { state.raise("Unmatched ')'"); } if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { state.raise("Lone quantifier brackets"); } } if (state.maxBackReference > state.numCapturingParens) { state.raise("Invalid escape"); } for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { var name = list[i]; if (state.groupNames.indexOf(name) === -1) { state.raise("Invalid named capture referenced"); } } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction pp$1$2.regexp_disjunction = function(state) { this.regexp_alternative(state); while (state.eat(0x7C /* | */)) { this.regexp_alternative(state); } // Make the same message as V8. if (this.regexp_eatQuantifier(state, true)) { state.raise("Nothing to repeat"); } if (state.eat(0x7B /* { */)) { state.raise("Lone quantifier brackets"); } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative pp$1$2.regexp_alternative = function(state) { while (state.pos < state.source.length && this.regexp_eatTerm(state)) { } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term pp$1$2.regexp_eatTerm = function(state) { if (this.regexp_eatAssertion(state)) { // Handle `QuantifiableAssertion Quantifier` alternative. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion // is a QuantifiableAssertion. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { // Make the same message as V8. if (state.switchU) { state.raise("Invalid quantifier"); } } return true } if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { this.regexp_eatQuantifier(state); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion pp$1$2.regexp_eatAssertion = function(state) { var start = state.pos; state.lastAssertionIsQuantifiable = false; // ^, $ if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { return true } // \b \B if (state.eat(0x5C /* \ */)) { if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { return true } state.pos = start; } // Lookahead / Lookbehind if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { var lookbehind = false; if (this.options.ecmaVersion >= 9) { lookbehind = state.eat(0x3C /* < */); } if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { this.regexp_disjunction(state); if (!state.eat(0x29 /* ) */)) { state.raise("Unterminated group"); } state.lastAssertionIsQuantifiable = !lookbehind; return true } } state.pos = start; return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier pp$1$2.regexp_eatQuantifier = function(state, noError) { if ( noError === void 0 ) noError = false; if (this.regexp_eatQuantifierPrefix(state, noError)) { state.eat(0x3F /* ? */); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix pp$1$2.regexp_eatQuantifierPrefix = function(state, noError) { return ( state.eat(0x2A /* * */) || state.eat(0x2B /* + */) || state.eat(0x3F /* ? */) || this.regexp_eatBracedQuantifier(state, noError) ) }; pp$1$2.regexp_eatBracedQuantifier = function(state, noError) { var start = state.pos; if (state.eat(0x7B /* { */)) { var min = 0, max = -1; if (this.regexp_eatDecimalDigits(state)) { min = state.lastIntValue; if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { max = state.lastIntValue; } if (state.eat(0x7D /* } */)) { // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term if (max !== -1 && max < min && !noError) { state.raise("numbers out of order in {} quantifier"); } return true } } if (state.switchU && !noError) { state.raise("Incomplete quantifier"); } state.pos = start; } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom pp$1$2.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$1$2.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$1$2.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$1$2.regexp_eatCapturingGroup = function(state) { if (state.eat(0x28 /* ( */)) { if (this.options.ecmaVersion >= 9) { this.regexp_groupSpecifier(state); } else if (state.current() === 0x3F /* ? */) { state.raise("Invalid group"); } this.regexp_disjunction(state); if (state.eat(0x29 /* ) */)) { state.numCapturingParens += 1; return true } state.raise("Unterminated group"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom pp$1$2.regexp_eatExtendedAtom = function(state) { return ( state.eat(0x2E /* . */) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state) ) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier pp$1$2.regexp_eatInvalidBracedQuantifier = function(state) { if (this.regexp_eatBracedQuantifier(state, true)) { state.raise("Nothing to repeat"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter pp$1$2.regexp_eatSyntaxCharacter = function(state) { var ch = state.current(); if (isSyntaxCharacter$2(ch)) { state.lastIntValue = ch; state.advance(); return true } return false }; function isSyntaxCharacter$2(ch) { return ( ch === 0x24 /* $ */ || ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || ch === 0x2E /* . */ || ch === 0x3F /* ? */ || ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || ch >= 0x7B /* { */ && ch <= 0x7D /* } */ ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter // But eat eager. pp$1$2.regexp_eatPatternCharacters = function(state) { var start = state.pos; var ch = 0; while ((ch = state.current()) !== -1 && !isSyntaxCharacter$2(ch)) { state.advance(); } return state.pos !== start }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter pp$1$2.regexp_eatExtendedPatternCharacter = function(state) { var ch = state.current(); if ( ch !== -1 && ch !== 0x24 /* $ */ && !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && ch !== 0x2E /* . */ && ch !== 0x3F /* ? */ && ch !== 0x5B /* [ */ && ch !== 0x5E /* ^ */ && ch !== 0x7C /* | */ ) { state.advance(); return true } return false }; // GroupSpecifier :: // [empty] // `?` GroupName pp$1$2.regexp_groupSpecifier = function(state) { if (state.eat(0x3F /* ? */)) { if (this.regexp_eatGroupName(state)) { if (state.groupNames.indexOf(state.lastStringValue) !== -1) { state.raise("Duplicate capture group name"); } state.groupNames.push(state.lastStringValue); return } state.raise("Invalid group"); } }; // GroupName :: // `<` RegExpIdentifierName `>` // Note: this updates `state.lastStringValue` property with the eaten name. pp$1$2.regexp_eatGroupName = function(state) { state.lastStringValue = ""; if (state.eat(0x3C /* < */)) { if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { return true } state.raise("Invalid capture group name"); } return false }; // RegExpIdentifierName :: // RegExpIdentifierStart // RegExpIdentifierName RegExpIdentifierPart // Note: this updates `state.lastStringValue` property with the eaten name. pp$1$2.regexp_eatRegExpIdentifierName = function(state) { state.lastStringValue = ""; if (this.regexp_eatRegExpIdentifierStart(state)) { state.lastStringValue += codePointToString$2(state.lastIntValue); while (this.regexp_eatRegExpIdentifierPart(state)) { state.lastStringValue += codePointToString$2(state.lastIntValue); } return true } return false }; // RegExpIdentifierStart :: // UnicodeIDStart // `$` // `_` // `\` RegExpUnicodeEscapeSequence[+U] pp$1$2.regexp_eatRegExpIdentifierStart = function(state) { var start = state.pos; var forceU = this.options.ecmaVersion >= 11; var ch = state.current(forceU); state.advance(forceU); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue; } if (isRegExpIdentifierStart$2(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierStart$2(ch) { return isIdentifierStart$2(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ } // RegExpIdentifierPart :: // UnicodeIDContinue // `$` // `_` // `\` RegExpUnicodeEscapeSequence[+U] // // pp$1$2.regexp_eatRegExpIdentifierPart = function(state) { var start = state.pos; var forceU = this.options.ecmaVersion >= 11; var ch = state.current(forceU); state.advance(forceU); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue; } if (isRegExpIdentifierPart$2(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierPart$2(ch) { return isIdentifierChar$2(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape pp$1$2.regexp_eatAtomEscape = function(state) { if ( this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || (state.switchN && this.regexp_eatKGroupName(state)) ) { return true } if (state.switchU) { // Make the same message as V8. if (state.current() === 0x63 /* c */) { state.raise("Invalid unicode escape"); } state.raise("Invalid escape"); } return false }; pp$1$2.regexp_eatBackReference = function(state) { var start = state.pos; if (this.regexp_eatDecimalEscape(state)) { var n = state.lastIntValue; if (state.switchU) { // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape if (n > state.maxBackReference) { state.maxBackReference = n; } return true } if (n <= state.numCapturingParens) { return true } state.pos = start; } return false }; pp$1$2.regexp_eatKGroupName = function(state) { if (state.eat(0x6B /* k */)) { if (this.regexp_eatGroupName(state)) { state.backReferenceNames.push(state.lastStringValue); return true } state.raise("Invalid named reference"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape pp$1$2.regexp_eatCharacterEscape = function(state) { return ( this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || this.regexp_eatIdentityEscape(state) ) }; pp$1$2.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$1$2.regexp_eatZero = function(state) { if (state.current() === 0x30 /* 0 */ && !isDecimalDigit$3(state.lookahead())) { state.lastIntValue = 0; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape pp$1$2.regexp_eatControlEscape = function(state) { var ch = state.current(); if (ch === 0x74 /* t */) { state.lastIntValue = 0x09; /* \t */ state.advance(); return true } if (ch === 0x6E /* n */) { state.lastIntValue = 0x0A; /* \n */ state.advance(); return true } if (ch === 0x76 /* v */) { state.lastIntValue = 0x0B; /* \v */ state.advance(); return true } if (ch === 0x66 /* f */) { state.lastIntValue = 0x0C; /* \f */ state.advance(); return true } if (ch === 0x72 /* r */) { state.lastIntValue = 0x0D; /* \r */ state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter pp$1$2.regexp_eatControlLetter = function(state) { var ch = state.current(); if (isControlLetter$2(ch)) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; function isControlLetter$2(ch) { return ( (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence pp$1$2.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { if ( forceU === void 0 ) forceU = false; var start = state.pos; var switchU = forceU || state.switchU; if (state.eat(0x75 /* u */)) { if (this.regexp_eatFixedHexDigits(state, 4)) { var lead = state.lastIntValue; if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { var leadSurrogateEnd = state.pos; if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { var trail = state.lastIntValue; if (trail >= 0xDC00 && trail <= 0xDFFF) { state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; return true } } state.pos = leadSurrogateEnd; state.lastIntValue = lead; } return true } if ( switchU && state.eat(0x7B /* { */) && this.regexp_eatHexDigits(state) && state.eat(0x7D /* } */) && isValidUnicode$2(state.lastIntValue) ) { return true } if (switchU) { state.raise("Invalid unicode escape"); } state.pos = start; } return false }; function isValidUnicode$2(ch) { return ch >= 0 && ch <= 0x10FFFF } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape pp$1$2.regexp_eatIdentityEscape = function(state) { if (state.switchU) { if (this.regexp_eatSyntaxCharacter(state)) { return true } if (state.eat(0x2F /* / */)) { state.lastIntValue = 0x2F; /* / */ return true } return false } var ch = state.current(); if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { state.lastIntValue = ch; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape pp$1$2.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 }; // Return values used by character set parsing methods, needed to // forbid negation of sets that can match strings. var CharSetNone$1 = 0; // Nothing parsed var CharSetOk$1 = 1; // Construct parsed, cannot contain strings var CharSetString$1 = 2; // Construct parsed, can contain strings // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape pp$1$2.regexp_eatCharacterClassEscape = function(state) { var ch = state.current(); if (isCharacterClassEscape$2(ch)) { state.lastIntValue = -1; state.advance(); return CharSetOk$1 } var negate = false; if ( state.switchU && this.options.ecmaVersion >= 9 && ((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */) ) { state.lastIntValue = -1; state.advance(); var result; if ( state.eat(0x7B /* { */) && (result = this.regexp_eatUnicodePropertyValueExpression(state)) && state.eat(0x7D /* } */) ) { if (negate && result === CharSetString$1) { state.raise("Invalid property name"); } return result } state.raise("Invalid property name"); } return CharSetNone$1 }; function isCharacterClassEscape$2(ch) { return ( ch === 0x64 /* d */ || ch === 0x44 /* D */ || ch === 0x73 /* s */ || ch === 0x53 /* S */ || ch === 0x77 /* w */ || ch === 0x57 /* W */ ) } // UnicodePropertyValueExpression :: // UnicodePropertyName `=` UnicodePropertyValue // LoneUnicodePropertyNameOrValue pp$1$2.regexp_eatUnicodePropertyValueExpression = function(state) { var start = state.pos; // UnicodePropertyName `=` UnicodePropertyValue if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { var name = state.lastStringValue; if (this.regexp_eatUnicodePropertyValue(state)) { var value = state.lastStringValue; this.regexp_validateUnicodePropertyNameAndValue(state, name, value); return CharSetOk$1 } } state.pos = start; // LoneUnicodePropertyNameOrValue if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { var nameOrValue = state.lastStringValue; return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue) } return CharSetNone$1 }; pp$1$2.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { if (!hasOwn$2(state.unicodeProperties.nonBinary, name)) { state.raise("Invalid property name"); } if (!state.unicodeProperties.nonBinary[name].test(value)) { state.raise("Invalid property value"); } }; pp$1$2.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk$1 } if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString$1 } state.raise("Invalid property name"); }; // UnicodePropertyName :: // UnicodePropertyNameCharacters pp$1$2.regexp_eatUnicodePropertyName = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyNameCharacter$2(ch = state.current())) { state.lastStringValue += codePointToString$2(ch); state.advance(); } return state.lastStringValue !== "" }; function isUnicodePropertyNameCharacter$2(ch) { return isControlLetter$2(ch) || ch === 0x5F /* _ */ } // UnicodePropertyValue :: // UnicodePropertyValueCharacters pp$1$2.regexp_eatUnicodePropertyValue = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyValueCharacter$2(ch = state.current())) { state.lastStringValue += codePointToString$2(ch); state.advance(); } return state.lastStringValue !== "" }; function isUnicodePropertyValueCharacter$2(ch) { return isUnicodePropertyNameCharacter$2(ch) || isDecimalDigit$3(ch) } // LoneUnicodePropertyNameOrValue :: // UnicodePropertyValueCharacters pp$1$2.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { return this.regexp_eatUnicodePropertyValue(state) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass pp$1$2.regexp_eatCharacterClass = function(state) { if (state.eat(0x5B /* [ */)) { var negate = state.eat(0x5E /* ^ */); var result = this.regexp_classContents(state); if (!state.eat(0x5D /* ] */)) { state.raise("Unterminated character class"); } if (negate && result === CharSetString$1) { state.raise("Negated character class may contain strings"); } return true } return false }; // https://tc39.es/ecma262/#prod-ClassContents // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges pp$1$2.regexp_classContents = function(state) { if (state.current() === 0x5D /* ] */) { return CharSetOk$1 } if (state.switchV) { return this.regexp_classSetExpression(state) } this.regexp_nonEmptyClassRanges(state); return CharSetOk$1 }; // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash pp$1$2.regexp_nonEmptyClassRanges = function(state) { while (this.regexp_eatClassAtom(state)) { var left = state.lastIntValue; if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { var right = state.lastIntValue; if (state.switchU && (left === -1 || right === -1)) { state.raise("Invalid character class"); } if (left !== -1 && right !== -1 && left > right) { state.raise("Range out of order in character class"); } } } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash pp$1$2.regexp_eatClassAtom = function(state) { var start = state.pos; if (state.eat(0x5C /* \ */)) { if (this.regexp_eatClassEscape(state)) { return true } if (state.switchU) { // Make the same message as V8. var ch$1 = state.current(); if (ch$1 === 0x63 /* c */ || isOctalDigit$2(ch$1)) { state.raise("Invalid class escape"); } state.raise("Invalid escape"); } state.pos = start; } var ch = state.current(); if (ch !== 0x5D /* ] */) { state.lastIntValue = ch; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape pp$1$2.regexp_eatClassEscape = function(state) { var start = state.pos; if (state.eat(0x62 /* b */)) { state.lastIntValue = 0x08; /* */ return true } if (state.switchU && state.eat(0x2D /* - */)) { state.lastIntValue = 0x2D; /* - */ return true } if (!state.switchU && state.eat(0x63 /* c */)) { if (this.regexp_eatClassControlLetter(state)) { return true } state.pos = start; } return ( this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) ) }; // https://tc39.es/ecma262/#prod-ClassSetExpression // https://tc39.es/ecma262/#prod-ClassUnion // https://tc39.es/ecma262/#prod-ClassIntersection // https://tc39.es/ecma262/#prod-ClassSubtraction pp$1$2.regexp_classSetExpression = function(state) { var result = CharSetOk$1, subResult; if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) { if (subResult === CharSetString$1) { result = CharSetString$1; } // https://tc39.es/ecma262/#prod-ClassIntersection var start = state.pos; while (state.eatChars([0x26, 0x26] /* && */)) { if ( state.current() !== 0x26 /* & */ && (subResult = this.regexp_eatClassSetOperand(state)) ) { if (subResult !== CharSetString$1) { result = CharSetOk$1; } continue } state.raise("Invalid character in character class"); } if (start !== state.pos) { return result } // https://tc39.es/ecma262/#prod-ClassSubtraction while (state.eatChars([0x2D, 0x2D] /* -- */)) { if (this.regexp_eatClassSetOperand(state)) { continue } state.raise("Invalid character in character class"); } if (start !== state.pos) { return result } } else { state.raise("Invalid character in character class"); } // https://tc39.es/ecma262/#prod-ClassUnion for (;;) { if (this.regexp_eatClassSetRange(state)) { continue } subResult = this.regexp_eatClassSetOperand(state); if (!subResult) { return result } if (subResult === CharSetString$1) { result = CharSetString$1; } } }; // https://tc39.es/ecma262/#prod-ClassSetRange pp$1$2.regexp_eatClassSetRange = function(state) { var start = state.pos; if (this.regexp_eatClassSetCharacter(state)) { var left = state.lastIntValue; if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) { var right = state.lastIntValue; if (left !== -1 && right !== -1 && left > right) { state.raise("Range out of order in character class"); } return true } state.pos = start; } return false }; // https://tc39.es/ecma262/#prod-ClassSetOperand pp$1$2.regexp_eatClassSetOperand = function(state) { if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk$1 } return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state) }; // https://tc39.es/ecma262/#prod-NestedClass pp$1$2.regexp_eatNestedClass = function(state) { var start = state.pos; if (state.eat(0x5B /* [ */)) { var negate = state.eat(0x5E /* ^ */); var result = this.regexp_classContents(state); if (state.eat(0x5D /* ] */)) { if (negate && result === CharSetString$1) { state.raise("Negated character class may contain strings"); } return result } state.pos = start; } if (state.eat(0x5C /* \ */)) { var result$1 = this.regexp_eatCharacterClassEscape(state); if (result$1) { return result$1 } state.pos = start; } return null }; // https://tc39.es/ecma262/#prod-ClassStringDisjunction pp$1$2.regexp_eatClassStringDisjunction = function(state) { var start = state.pos; if (state.eatChars([0x5C, 0x71] /* \q */)) { if (state.eat(0x7B /* { */)) { var result = this.regexp_classStringDisjunctionContents(state); if (state.eat(0x7D /* } */)) { return result } } else { // Make the same message as V8. state.raise("Invalid escape"); } state.pos = start; } return null }; // https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents pp$1$2.regexp_classStringDisjunctionContents = function(state) { var result = this.regexp_classString(state); while (state.eat(0x7C /* | */)) { if (this.regexp_classString(state) === CharSetString$1) { result = CharSetString$1; } } return result }; // https://tc39.es/ecma262/#prod-ClassString // https://tc39.es/ecma262/#prod-NonEmptyClassString pp$1$2.regexp_classString = function(state) { var count = 0; while (this.regexp_eatClassSetCharacter(state)) { count++; } return count === 1 ? CharSetOk$1 : CharSetString$1 }; // https://tc39.es/ecma262/#prod-ClassSetCharacter pp$1$2.regexp_eatClassSetCharacter = function(state) { var start = state.pos; if (state.eat(0x5C /* \ */)) { if ( this.regexp_eatCharacterEscape(state) || this.regexp_eatClassSetReservedPunctuator(state) ) { return true } if (state.eat(0x62 /* b */)) { state.lastIntValue = 0x08; /* */ return true } state.pos = start; return false } var ch = state.current(); if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter$1(ch)) { return false } if (isClassSetSyntaxCharacter$1(ch)) { return false } state.advance(); state.lastIntValue = ch; return true }; // https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator function isClassSetReservedDoublePunctuatorCharacter$1(ch) { return ( ch === 0x21 /* ! */ || ch >= 0x23 /* # */ && ch <= 0x26 /* & */ || ch >= 0x2A /* * */ && ch <= 0x2C /* , */ || ch === 0x2E /* . */ || ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ || ch === 0x5E /* ^ */ || ch === 0x60 /* ` */ || ch === 0x7E /* ~ */ ) } // https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter function isClassSetSyntaxCharacter$1(ch) { return ( ch === 0x28 /* ( */ || ch === 0x29 /* ) */ || ch === 0x2D /* - */ || ch === 0x2F /* / */ || ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ || ch >= 0x7B /* { */ && ch <= 0x7D /* } */ ) } // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator pp$1$2.regexp_eatClassSetReservedPunctuator = function(state) { var ch = state.current(); if (isClassSetReservedPunctuator$1(ch)) { state.lastIntValue = ch; state.advance(); return true } return false }; // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator function isClassSetReservedPunctuator$1(ch) { return ( ch === 0x21 /* ! */ || ch === 0x23 /* # */ || ch === 0x25 /* % */ || ch === 0x26 /* & */ || ch === 0x2C /* , */ || ch === 0x2D /* - */ || ch >= 0x3A /* : */ && ch <= 0x3E /* > */ || ch === 0x40 /* @ */ || ch === 0x60 /* ` */ || ch === 0x7E /* ~ */ ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter pp$1$2.regexp_eatClassControlLetter = function(state) { var ch = state.current(); if (isDecimalDigit$3(ch) || ch === 0x5F /* _ */) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp$1$2.regexp_eatHexEscapeSequence = function(state) { var start = state.pos; if (state.eat(0x78 /* x */)) { if (this.regexp_eatFixedHexDigits(state, 2)) { return true } if (state.switchU) { state.raise("Invalid escape"); } state.pos = start; } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits pp$1$2.regexp_eatDecimalDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isDecimalDigit$3(ch = state.current())) { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); state.advance(); } return state.pos !== start }; function isDecimalDigit$3(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits pp$1$2.regexp_eatHexDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isHexDigit$3(ch = state.current())) { state.lastIntValue = 16 * state.lastIntValue + hexToInt$2(ch); state.advance(); } return state.pos !== start }; function isHexDigit$3(ch) { return ( (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) ) } function hexToInt$2(ch) { if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { return 10 + (ch - 0x41 /* A */) } if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { return 10 + (ch - 0x61 /* a */) } return ch - 0x30 /* 0 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence // Allows only 0-377(octal) i.e. 0-255(decimal). pp$1$2.regexp_eatLegacyOctalEscapeSequence = function(state) { if (this.regexp_eatOctalDigit(state)) { var n1 = state.lastIntValue; if (this.regexp_eatOctalDigit(state)) { var n2 = state.lastIntValue; if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; } else { state.lastIntValue = n1 * 8 + n2; } } else { state.lastIntValue = n1; } return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit pp$1$2.regexp_eatOctalDigit = function(state) { var ch = state.current(); if (isOctalDigit$2(ch)) { state.lastIntValue = ch - 0x30; /* 0 */ state.advance(); return true } state.lastIntValue = 0; return false }; function isOctalDigit$2(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp$1$2.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$3(ch)) { state.pos = start; return false } state.lastIntValue = 16 * state.lastIntValue + hexToInt$2(ch); state.advance(); } return true }; // Object type used to represent tokens. Note that normally, tokens // simply exist as properties on the parser object. This is only // used for the onToken callback and the external tokenizer. var Token$3 = 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$2(p, p.startLoc, p.endLoc); } if (p.options.ranges) { this.range = [p.start, p.end]; } }; // ## Tokenizer var pp$b = Parser$2.prototype; // Move to the next token pp$b.next = function(ignoreEscapeSequenceInKeyword) { if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } if (this.options.onToken) { this.options.onToken(new Token$3(this)); } this.lastTokEnd = this.end; this.lastTokStart = this.start; this.lastTokEndLoc = this.endLoc; this.lastTokStartLoc = this.startLoc; this.nextToken(); }; pp$b.getToken = function() { this.next(); return new Token$3(this) }; // If we're in an ES6 environment, make parsers iterable if (typeof Symbol !== "undefined") { pp$b[Symbol.iterator] = function() { var this$1$1 = this; return { next: function () { var token = this$1$1.getToken(); return { done: token.type === types$1$2.eof, value: token } } } }; } // Toggle strict mode. Re-reads the next number or string to please // pedantic tests (`"use strict"; 010;` should fail). // Read a single token, updating the parser object's token-related // properties. pp$b.nextToken = function() { var curContext = this.curContext(); if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } this.start = this.pos; if (this.options.locations) { this.startLoc = this.curPosition(); } if (this.pos >= this.input.length) { return this.finishToken(types$1$2.eof) } if (curContext.override) { return curContext.override(this) } else { this.readToken(this.fullCharCodeAtPos()); } }; pp$b.readToken = function(code) { // Identifier or keyword. '\uXXXX' sequences are allowed in // identifiers, so '\' also dispatches to that. if (isIdentifierStart$2(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) { return this.readWord() } return this.getTokenFromCode(code) }; pp$b.fullCharCodeAtPos = function() { var code = this.input.charCodeAt(this.pos); if (code <= 0xd7ff || code >= 0xdc00) { return code } var next = this.input.charCodeAt(this.pos + 1); return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 }; pp$b.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) { for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak$2(this.input, pos, this.pos)) > -1;) { ++this.curLine; pos = this.lineStart = nextBreak; } } if (this.options.onComment) { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition()); } }; pp$b.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$2(ch)) { ch = this.input.charCodeAt(++this.pos); } if (this.options.onComment) { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition()); } }; // Called at the start of the parse and after every token. Skips // whitespace and comments, and. pp$b.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$2.test(String.fromCharCode(ch))) { ++this.pos; } else { break loop } } } }; // Called at the end of every token. Sets `end`, `val`, and // maintains `context` and `exprAllowed`, and skips the space after // the token, so that the next one's `start` will point at the // right position. pp$b.finishToken = function(type, val) { this.end = this.pos; if (this.options.locations) { this.endLoc = this.curPosition(); } var prevType = this.type; this.type = type; this.value = val; this.updateContext(prevType); }; // ### Token reading // This is the function that is called to fetch the next token. It // is somewhat obscure, because it works in character codes rather // than characters, and because operator parsing has been inlined // into it. // // All in the name of speed. // pp$b.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$1$2.ellipsis) } else { ++this.pos; return this.finishToken(types$1$2.dot) } }; pp$b.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$1$2.assign, 2) } return this.finishOp(types$1$2.slash, 1) }; pp$b.readToken_mult_modulo_exp = function(code) { // '%*' var next = this.input.charCodeAt(this.pos + 1); var size = 1; var tokentype = code === 42 ? types$1$2.star : types$1$2.modulo; // exponentiation operator ** and **= if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { ++size; tokentype = types$1$2.starstar; next = this.input.charCodeAt(this.pos + 2); } if (next === 61) { return this.finishOp(types$1$2.assign, size + 1) } return this.finishOp(tokentype, size) }; pp$b.readToken_pipe_amp = function(code) { // '|&' var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (this.options.ecmaVersion >= 12) { var next2 = this.input.charCodeAt(this.pos + 2); if (next2 === 61) { return this.finishOp(types$1$2.assign, 3) } } return this.finishOp(code === 124 ? types$1$2.logicalOR : types$1$2.logicalAND, 2) } if (next === 61) { return this.finishOp(types$1$2.assign, 2) } return this.finishOp(code === 124 ? types$1$2.bitwiseOR : types$1$2.bitwiseAND, 1) }; pp$b.readToken_caret = function() { // '^' var next = this.input.charCodeAt(this.pos + 1); if (next === 61) { return this.finishOp(types$1$2.assign, 2) } return this.finishOp(types$1$2.bitwiseXOR, 1) }; pp$b.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$2.test(this.input.slice(this.lastTokEnd, this.pos)))) { // A `-->` line comment this.skipLineComment(3); this.skipSpace(); return this.nextToken() } return this.finishOp(types$1$2.incDec, 2) } if (next === 61) { return this.finishOp(types$1$2.assign, 2) } return this.finishOp(types$1$2.plusMin, 1) }; pp$b.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$1$2.assign, size + 1) } return this.finishOp(types$1$2.bitShift, size) } if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) { // ` regexps set = set.map((s, si, set) => s.map(this.parse, this)); this.debug(this.pattern, set); // filter out everything that didn't compile properly. set = set.filter(s => s.indexOf(false) === -1); this.debug(this.pattern, set); this.set = set; } parseNegate () { if (this.options.nonegate) return const pattern = this.pattern; let negate = false; let negateOffset = 0; for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) { negate = !negate; negateOffset++; } if (negateOffset) this.pattern = pattern.substr(negateOffset); this.negate = negate; } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. matchOne (file, pattern, partial) { var options = this.options; this.debug('matchOne', { 'this': this, file: file, pattern: pattern }); this.debug('matchOne', file.length, pattern.length); for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length ; (fi < fl) && (pi < pl) ; fi++, pi++) { this.debug('matchOne loop'); var p = pattern[pi]; var f = file[fi]; this.debug(pattern, p, f); // should be impossible. // some invalid regexp stuff in the set. /* istanbul ignore if */ if (p === false) return false if (p === GLOBSTAR$2$1) { this.debug('GLOBSTAR', [pattern, p, f]); // "**" // a/**/b/**/c would match the following: // a/b/x/y/z/c // a/x/y/z/b/c // a/b/x/b/x/c // a/b/c // To do this, take the rest of the pattern after // the **, and see if it would match the file remainder. // If so, return success. // If not, the ** "swallows" a segment, and try again. // This is recursively awful. // // a/**/b/**/c matching a/b/x/y/z/c // - a matches a // - doublestar // - matchOne(b/x/y/z/c, b/**/c) // - b matches b // - doublestar // - matchOne(x/y/z/c, c) -> no // - matchOne(y/z/c, c) -> no // - matchOne(z/c, c) -> no // - matchOne(c, c) yes, hit var fr = fi; var pr = pi + 1; if (pr === pl) { this.debug('** at the end'); // a ** at the end will just swallow the rest. // We have found a match. // however, it will not swallow /.x, unless // options.dot is set. // . and .. are *never* matched by **, for explosively // exponential reasons. for (; fi < fl; fi++) { if (file[fi] === '.' || file[fi] === '..' || (!options.dot && file[fi].charAt(0) === '.')) return false } return true } // ok, let's see if we can swallow whatever we can. while (fr < fl) { var swallowee = file[fr]; this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); // XXX remove this slice. Just pass the start index. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { this.debug('globstar found match!', fr, fl, swallowee); // found a match. return true } else { // can't swallow "." or ".." ever. // can only swallow ".foo" when explicitly asked. if (swallowee === '.' || swallowee === '..' || (!options.dot && swallowee.charAt(0) === '.')) { this.debug('dot detected!', file, fr, pattern, pr); break } // ** swallows a segment, and continue. this.debug('globstar swallow a segment, and continue'); fr++; } } // no match was found. // However, in partial mode, we can't say this is necessarily over. // If there's more *pattern* left, then /* istanbul ignore if */ if (partial) { // ran out of file this.debug('\n>>> no match, partial?', file, fr, pattern, pr); if (fr === fl) return true } return false } // something other than ** // non-magic patterns just have to match exactly // patterns with magic have been turned into regexps. var hit; if (typeof p === 'string') { hit = f === p; this.debug('string match', p, f, hit); } else { hit = f.match(p); this.debug('pattern match', p, f, hit); } if (!hit) return false } // Note: ending in / means that we'll get a final "" // at the end of the pattern. This can only match a // corresponding "" at the end of the file. // If the file ends in /, then it can only match a // a pattern that ends in /, unless the pattern just // doesn't have any more for it. But, a/b/ should *not* // match "a/b/*", even though "" matches against the // [^/]*? pattern, except in partial mode, where it might // simply not be reached yet. // However, a/b/ should still satisfy a/* // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. // an exact hit! return true } else if (fi === fl) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial } else /* istanbul ignore else */ if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ return (fi === fl - 1) && (file[fi] === '') } // should be unreachable. /* istanbul ignore next */ throw new Error('wtf?') } braceExpand () { return braceExpand$1(this.pattern, this.options) } parse (pattern, isSub) { assertValidPattern$1(pattern); const options = this.options; // shortcuts if (pattern === '**') { if (!options.noglobstar) return GLOBSTAR$2$1 else pattern = '*'; } if (pattern === '') return '' let re = ''; let hasMagic = !!options.nocase; let escaping = false; // ? => one single character const patternListStack = []; const negativeLists = []; let stateChar; let inClass = false; let reClassStart = -1; let classStart = -1; let cs; let pl; let sp; // . and .. never match anything that doesn't start with ., // even when options.dot is set. const patternStart = pattern.charAt(0) === '.' ? '' // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)'; const clearStateChar = () => { if (stateChar) { // we had some state-tracking character // that wasn't consumed by this pass. switch (stateChar) { case '*': re += star$1; hasMagic = true; break case '?': re += qmark$1; hasMagic = true; break default: re += '\\' + stateChar; break } this.debug('clearStateChar %j %j', stateChar, re); stateChar = false; } }; for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) { this.debug('%s\t%s %s %j', pattern, i, re, c); // skip over any that are escaped. if (escaping) { /* istanbul ignore next - completely not allowed, even escaped. */ if (c === '/') { return false } if (reSpecials$1[c]) { re += '\\'; } re += c; escaping = false; continue } switch (c) { /* istanbul ignore next */ case '/': { // Should already be path-split by now. return false } case '\\': clearStateChar(); escaping = true; continue // the various stateChar values // for the "extglob" stuff. case '?': case '*': case '+': case '@': case '!': this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); // all of those are literals inside a class, except that // the glob [!a] means [^a] in regexp if (inClass) { this.debug(' in class'); if (c === '!' && i === classStart + 1) c = '^'; re += c; continue } // if we already have a stateChar, then it means // that there was something like ** or +? in there. // Handle the stateChar, then proceed with this one. this.debug('call clearStateChar %j', stateChar); clearStateChar(); stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing. // just clear the statechar *now*, rather than even diving into // the patternList stuff. if (options.noext) clearStateChar(); continue case '(': if (inClass) { re += '('; continue } if (!stateChar) { re += '\\('; continue } patternListStack.push({ type: stateChar, start: i - 1, reStart: re.length, open: plTypes$1[stateChar].open, close: plTypes$1[stateChar].close }); // negation is (?:(?!js)[^/]*) re += stateChar === '!' ? '(?:(?!(?:' : '(?:'; this.debug('plType %j %j', stateChar, re); stateChar = false; continue case ')': if (inClass || !patternListStack.length) { re += '\\)'; continue } clearStateChar(); hasMagic = true; pl = patternListStack.pop(); // negation is (?:(?!js)[^/]*) // The others are (?:) re += pl.close; if (pl.type === '!') { negativeLists.push(pl); } pl.reEnd = re.length; continue case '|': if (inClass || !patternListStack.length) { re += '\\|'; continue } clearStateChar(); re += '|'; continue // these are mostly the same in regexp and glob case '[': // swallow any state-tracking char before the [ clearStateChar(); if (inClass) { re += '\\' + c; continue } inClass = true; classStart = i; reClassStart = re.length; re += c; continue case ']': // a right bracket shall lose its special // meaning and represent itself in // a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 if (i === classStart + 1 || !inClass) { re += '\\' + c; continue } // handle the case where we left a class open. // "[z-a]" is valid, equivalent to "\[z-a\]" // split where the last [ was, make sure we don't have // an invalid re. if so, re-walk the contents of the // would-be class to re-translate any characters that // were passed through as-is // TODO: It would probably be faster to determine this // without a try/catch and a new RegExp, but it's tricky // to do safely. For now, this is safe and works. cs = pattern.substring(classStart + 1, i); // finish up the class. hasMagic = true; inClass = false; re += c; continue default: // swallow any state char that wasn't consumed clearStateChar(); if (reSpecials$1[c] && !(c === '^' && inClass)) { re += '\\'; } re += c; break } // switch } // for // handle the case where we left a class open. // "[abc" is valid, equivalent to "\[abc" if (inClass) { // split where the last [ was, and escape it // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is cs = pattern.substr(classStart + 1); sp = this.parse(cs, SUBPARSE$1); re = re.substr(0, reClassStart) + '\\[' + sp[0]; hasMagic = hasMagic || sp[1]; } // handle the case where we had a +( thing at the *end* // of the pattern. // each pattern list stack adds 3 chars, and we need to go through // and escape any | chars that were passed through as-is for the regexp. // Go through and escape them, taking care not to double-escape any // | chars that were already escaped. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { let tail; tail = re.slice(pl.reStart + pl.open.length); this.debug('setting tail', re, pl); // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => { /* istanbul ignore else - should already be done */ if (!$2) { // the | isn't already escaped, so escape it. $2 = '\\'; } // need to escape all those slashes *again*, without escaping the // one that we need for escaping the | character. As it works out, // escaping an even number of slashes can be done by simply repeating // it exactly after itself. That's why this trick works. // // I am sorry that you have to see this. return $1 + $1 + $2 + '|' }); this.debug('tail=%j\n %s', tail, tail, pl, re); const t = pl.type === '*' ? star$1 : pl.type === '?' ? qmark$1 : '\\' + pl.type; hasMagic = true; re = re.slice(0, pl.reStart) + t + '\\(' + tail; } // handle trailing things that only matter at the very end. clearStateChar(); if (escaping) { // trailing \\ re += '\\\\'; } // only need to apply the nodot start if the re starts with // something that could conceivably capture a dot const addPatternStart = addPatternStartSet$1[re.charAt(0)]; // Hack to work around lack of negative lookbehind in JS // A pattern like: *.!(x).!(y|z) needs to ensure that a name // like 'a.xyz.yz' doesn't match. So, the first negative // lookahead, has to look ALL the way ahead, to the end of // the pattern. for (let n = negativeLists.length - 1; n > -1; n--) { const nl = negativeLists[n]; const nlBefore = re.slice(0, nl.reStart); const nlFirst = re.slice(nl.reStart, nl.reEnd - 8); let nlAfter = re.slice(nl.reEnd); const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter; // Handle nested stuff like *(*.js|!(*.json)), where open parens // mean that we should *not* include the ) in the bit that is considered // "after" the negated section. const openParensBefore = nlBefore.split('(').length - 1; let cleanAfter = nlAfter; for (let i = 0; i < openParensBefore; i++) { cleanAfter = cleanAfter.replace(/\)[+*?]?/, ''); } nlAfter = cleanAfter; const dollar = nlAfter === '' && isSub !== SUBPARSE$1 ? '$' : ''; re = nlBefore + nlFirst + nlAfter + dollar + nlLast; } // if the re is not "" at this point, then we need to make sure // it doesn't match against an empty path part. // Otherwise a/* will match a/, which it should not. if (re !== '' && hasMagic) { re = '(?=.)' + re; } if (addPatternStart) { re = patternStart + re; } // parsing just a piece of a larger pattern. if (isSub === SUBPARSE$1) { return [re, hasMagic] } // skip the regexp for non-magical patterns // unescape anything in it, though, so that it'll be // an exact match against a file etc. if (!hasMagic) { return globUnescape$1(pattern) } const flags = options.nocase ? 'i' : ''; try { return Object.assign(new RegExp('^' + re + '$', flags), { _glob: pattern, _src: re, }) } catch (er) /* istanbul ignore next - should be impossible */ { // If it was an invalid regular expression, then it can't match // anything. This trick looks for a character after the end of // the string, which is of course impossible, except in multi-line // mode, but it's not a /m regex. return new RegExp('$.') } } makeRe () { if (this.regexp || this.regexp === false) return this.regexp // at this point, this.set is a 2d array of partial // pattern strings, or "**". // // It's better to use .match(). This function shouldn't // be used, really, but it's pretty convenient sometimes, // when you just want to work with a regex. const set = this.set; if (!set.length) { this.regexp = false; return this.regexp } const options = this.options; const twoStar = options.noglobstar ? star$1 : options.dot ? twoStarDot$1 : twoStarNoDot$1; const flags = options.nocase ? 'i' : ''; // coalesce globstars and regexpify non-globstar patterns // if it's the only item, then we just do one twoStar // if it's the first, and there are more, prepend (\/|twoStar\/)? to next // if it's the last, append (\/twoStar|) to previous // if it's in the middle, append (\/|\/twoStar\/) to previous // then filter out GLOBSTAR symbols let re = set.map(pattern => { pattern = pattern.map(p => typeof p === 'string' ? regExpEscape$1(p) : p === GLOBSTAR$2$1 ? GLOBSTAR$2$1 : p._src ).reduce((set, p) => { if (!(set[set.length - 1] === GLOBSTAR$2$1 && p === GLOBSTAR$2$1)) { set.push(p); } return set }, []); pattern.forEach((p, i) => { if (p !== GLOBSTAR$2$1 || pattern[i-1] === GLOBSTAR$2$1) { return } if (i === 0) { if (pattern.length > 1) { pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1]; } else { pattern[i] = twoStar; } } else if (i === pattern.length - 1) { pattern[i-1] += '(?:\\\/|' + twoStar + ')?'; } else { pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1]; pattern[i+1] = GLOBSTAR$2$1; } }); return pattern.filter(p => p !== GLOBSTAR$2$1).join('/') }).join('|'); // must match entire pattern // ending in a * or ** will make it less strict. re = '^(?:' + re + ')$'; // can match anything, as long as it's not this. if (this.negate) re = '^(?!' + re + ').*$'; try { this.regexp = new RegExp(re, flags); } catch (ex) /* istanbul ignore next - should be impossible */ { this.regexp = false; } return this.regexp } match (f, partial = this.partial) { this.debug('match', f, this.pattern); // short-circuit in the case of busted things. // comments, etc. if (this.comment) return false if (this.empty) return f === '' if (f === '/' && partial) return true const options = this.options; // windows: need to use /, not \ if (path$j$1.sep !== '/') { f = f.split(path$j$1.sep).join('/'); } // treat the test path as a set of pathparts. f = f.split(slashSplit$1); this.debug(this.pattern, 'split', f); // just ONE of the pattern sets in this.set needs to match // in order for it to be valid. If negating, then just one // match means that we have failed. // Either way, return on the first hit. const set = this.set; this.debug(this.pattern, 'set', set); // Find the basename of the path by looking for the last non-empty segment let filename; for (let i = f.length - 1; i >= 0; i--) { filename = f[i]; if (filename) break } for (let i = 0; i < set.length; i++) { const pattern = set[i]; let file = f; if (options.matchBase && pattern.length === 1) { file = [filename]; } const hit = this.matchOne(file, pattern, partial); if (hit) { if (options.flipNegate) return true return !this.negate } } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.flipNegate) return false return this.negate } static defaults (def) { return minimatch$1$1.defaults(def).Minimatch } }; minimatch$1$1.Minimatch = Minimatch$1$1; var inherits$1 = {exports: {}}; var inherits_browser$1 = {exports: {}}; var hasRequiredInherits_browser$1; function requireInherits_browser$1 () { if (hasRequiredInherits_browser$1) return inherits_browser$1.exports; hasRequiredInherits_browser$1 = 1; if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module inherits_browser$1.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); } }; } else { // old school shim for old browsers inherits_browser$1.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } }; } return inherits_browser$1.exports; } try { var util$2$1 = require$2('util'); /* istanbul ignore next */ if (typeof util$2$1.inherits !== 'function') throw ''; inherits$1.exports = util$2$1.inherits; } catch (e) { /* istanbul ignore next */ inherits$1.exports = requireInherits_browser$1(); } var inheritsExports$1 = inherits$1.exports; var common$c$1 = {}; common$c$1.setopts = setopts$1; common$c$1.ownProp = ownProp$1; common$c$1.makeAbs = makeAbs$1; common$c$1.finish = finish$1; common$c$1.mark = mark$1; common$c$1.isIgnored = isIgnored$1; common$c$1.childrenIgnored = childrenIgnored$1; function ownProp$1 (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } var fs$i$1 = require$$0__default__default; var path$i$1 = require$$0$4; var minimatch$2 = minimatch_1$1; var isAbsolute$1 = require$$0$4.isAbsolute; var Minimatch$2 = minimatch$2.Minimatch; function alphasort$1 (a, b) { return a.localeCompare(b, 'en') } function setupIgnores$1 (self, options) { self.ignore = options.ignore || []; if (!Array.isArray(self.ignore)) self.ignore = [self.ignore]; if (self.ignore.length) { self.ignore = self.ignore.map(ignoreMap$1); } } // ignore patterns are always in dot:true mode. function ignoreMap$1 (pattern) { var gmatcher = null; if (pattern.slice(-3) === '/**') { var gpattern = pattern.replace(/(\/\*\*)+$/, ''); gmatcher = new Minimatch$2(gpattern, { dot: true }); } return { matcher: new Minimatch$2(pattern, { dot: true }), gmatcher: gmatcher } } function setopts$1 (self, pattern, options) { if (!options) options = {}; // base-matching: just use globstar for that. if (options.matchBase && -1 === pattern.indexOf("/")) { if (options.noglobstar) { throw new Error("base matching requires globstar") } pattern = "**/" + pattern; } self.silent = !!options.silent; self.pattern = pattern; self.strict = options.strict !== false; self.realpath = !!options.realpath; self.realpathCache = options.realpathCache || Object.create(null); self.follow = !!options.follow; self.dot = !!options.dot; self.mark = !!options.mark; self.nodir = !!options.nodir; if (self.nodir) self.mark = true; self.sync = !!options.sync; self.nounique = !!options.nounique; self.nonull = !!options.nonull; self.nosort = !!options.nosort; self.nocase = !!options.nocase; self.stat = !!options.stat; self.noprocess = !!options.noprocess; self.absolute = !!options.absolute; self.fs = options.fs || fs$i$1; self.maxLength = options.maxLength || Infinity; self.cache = options.cache || Object.create(null); self.statCache = options.statCache || Object.create(null); self.symlinks = options.symlinks || Object.create(null); setupIgnores$1(self, options); self.changedCwd = false; var cwd = process.cwd(); if (!ownProp$1(options, "cwd")) self.cwd = path$i$1.resolve(cwd); else { self.cwd = path$i$1.resolve(options.cwd); self.changedCwd = self.cwd !== cwd; } self.root = options.root || path$i$1.resolve(self.cwd, "/"); self.root = path$i$1.resolve(self.root); // TODO: is an absolute `cwd` supposed to be resolved against `root`? // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') self.cwdAbs = isAbsolute$1(self.cwd) ? self.cwd : makeAbs$1(self, self.cwd); self.nomount = !!options.nomount; if (process.platform === "win32") { self.root = self.root.replace(/\\/g, "/"); self.cwd = self.cwd.replace(/\\/g, "/"); self.cwdAbs = self.cwdAbs.replace(/\\/g, "/"); } // disable comments and negation in Minimatch. // Note that they are not supported in Glob itself anyway. options.nonegate = true; options.nocomment = true; // always treat \ in patterns as escapes, not path separators options.allowWindowsEscape = true; self.minimatch = new Minimatch$2(pattern, options); self.options = self.minimatch.options; } function finish$1 (self) { var nou = self.nounique; var all = nou ? [] : Object.create(null); for (var i = 0, l = self.matches.length; i < l; i ++) { var matches = self.matches[i]; if (!matches || Object.keys(matches).length === 0) { if (self.nonull) { // do like the shell, and spit out the literal glob var literal = self.minimatch.globSet[i]; if (nou) all.push(literal); else all[literal] = true; } } else { // had matches var m = Object.keys(matches); if (nou) all.push.apply(all, m); else m.forEach(function (m) { all[m] = true; }); } } if (!nou) all = Object.keys(all); if (!self.nosort) all = all.sort(alphasort$1); // at *some* point we statted all of these if (self.mark) { for (var i = 0; i < all.length; i++) { all[i] = self._mark(all[i]); } if (self.nodir) { all = all.filter(function (e) { var notDir = !(/\/$/.test(e)); var c = self.cache[e] || self.cache[makeAbs$1(self, e)]; if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c); return notDir }); } } if (self.ignore.length) all = all.filter(function(m) { return !isIgnored$1(self, m) }); self.found = all; } function mark$1 (self, p) { var abs = makeAbs$1(self, p); var c = self.cache[abs]; var m = p; if (c) { var isDir = c === 'DIR' || Array.isArray(c); var slash = p.slice(-1) === '/'; if (isDir && !slash) m += '/'; else if (!isDir && slash) m = m.slice(0, -1); if (m !== p) { var mabs = makeAbs$1(self, m); self.statCache[mabs] = self.statCache[abs]; self.cache[mabs] = self.cache[abs]; } } return m } // lotta situps... function makeAbs$1 (self, f) { var abs = f; if (f.charAt(0) === '/') { abs = path$i$1.join(self.root, f); } else if (isAbsolute$1(f) || f === '') { abs = f; } else if (self.changedCwd) { abs = path$i$1.resolve(self.cwd, f); } else { abs = path$i$1.resolve(f); } if (process.platform === 'win32') abs = abs.replace(/\\/g, '/'); return abs } // Return true, if pattern ends with globstar '**', for the accompanying parent directory. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents function isIgnored$1 (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) }) } function childrenIgnored$1 (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return !!(item.gmatcher && item.gmatcher.match(path)) }) } var sync$9$1; var hasRequiredSync$1; function requireSync$1 () { if (hasRequiredSync$1) return sync$9$1; hasRequiredSync$1 = 1; sync$9$1 = globSync; globSync.GlobSync = GlobSync; var rp = fs_realpath$1; var minimatch = minimatch_1$1; requireGlob$1().Glob; var path = require$$0$4; var assert = require$$5; var isAbsolute = require$$0$4.isAbsolute; var common = common$c$1; var setopts = common.setopts; var ownProp = common.ownProp; var childrenIgnored = common.childrenIgnored; var isIgnored = common.isIgnored; function globSync (pattern, options) { if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') return new GlobSync(pattern, options).found } function GlobSync (pattern, options) { if (!pattern) throw new Error('must provide pattern') if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') if (!(this instanceof GlobSync)) return new GlobSync(pattern, options) setopts(this, pattern, options); if (this.noprocess) return this var n = this.minimatch.set.length; this.matches = new Array(n); for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false); } this._finish(); } GlobSync.prototype._finish = function () { assert.ok(this instanceof GlobSync); if (this.realpath) { var self = this; this.matches.forEach(function (matchset, index) { var set = self.matches[index] = Object.create(null); for (var p in matchset) { try { p = self._makeAbs(p); var real = rp.realpathSync(p, self.realpathCache); set[real] = true; } catch (er) { if (er.syscall === 'stat') set[self._makeAbs(p)] = true; else throw er } } }); } common.finish(this); }; GlobSync.prototype._process = function (pattern, index, inGlobStar) { assert.ok(this instanceof GlobSync); // Get the first [n] parts of pattern that are all strings. var n = 0; while (typeof pattern[n] === 'string') { n ++; } // now n is the index of the first one that is *not* a string. // See if there's anything else var prefix; switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index); return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null; break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/'); break } var remain = pattern.slice(n); // get the list of entries. var read; if (prefix === null) read = '.'; else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) { return typeof p === 'string' ? p : '[*]' }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix; read = prefix; } else read = prefix; var abs = this._makeAbs(read); //if ignored, skip processing if (childrenIgnored(this, read)) return var isGlobStar = remain[0] === minimatch.GLOBSTAR; if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar); else this._processReaddir(prefix, read, abs, remain, index, inGlobStar); }; GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar); // if the abs isn't a dir, then nothing can match! if (!entries) return // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0]; var negate = !!this.minimatch.negate; var rawGlob = pn._glob; var dotOk = this.dot || rawGlob.charAt(0) === '.'; var matchedEntries = []; for (var i = 0; i < entries.length; i++) { var e = entries[i]; if (e.charAt(0) !== '.' || dotOk) { var m; if (negate && !prefix) { m = !e.match(pn); } else { m = e.match(pn); } if (m) matchedEntries.push(e); } } var len = matchedEntries.length; // If there are no matched entries, then nothing matches. if (len === 0) return // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; if (prefix) { if (prefix.slice(-1) !== '/') e = prefix + '/' + e; else e = prefix + e; } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e); } this._emitMatch(index, e); } // This was the last one, and no stats were needed return } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift(); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; var newPattern; if (prefix) newPattern = [prefix, e]; else newPattern = [e]; this._process(newPattern.concat(remain), index, inGlobStar); } }; GlobSync.prototype._emitMatch = function (index, e) { if (isIgnored(this, e)) return var abs = this._makeAbs(e); if (this.mark) e = this._mark(e); if (this.absolute) { e = abs; } if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs]; if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true; if (this.stat) this._stat(e); }; GlobSync.prototype._readdirInGlobStar = function (abs) { // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false) var entries; var lstat; try { lstat = this.fs.lstatSync(abs); } catch (er) { if (er.code === 'ENOENT') { // lstat failed, doesn't exist return null } } var isSym = lstat && lstat.isSymbolicLink(); this.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE'; else entries = this._readdir(abs, false); return entries }; GlobSync.prototype._readdir = function (abs, inGlobStar) { if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs) if (ownProp(this.cache, abs)) { var c = this.cache[abs]; if (!c || c === 'FILE') return null if (Array.isArray(c)) return c } try { return this._readdirEntries(abs, this.fs.readdirSync(abs)) } catch (er) { this._readdirError(abs, er); return null } }; GlobSync.prototype._readdirEntries = function (abs, entries) { // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i]; if (abs === '/') e = abs + e; else e = abs + '/' + e; this.cache[e] = true; } } this.cache[abs] = entries; // mark and cache dir-ness return entries }; GlobSync.prototype._readdirError = function (f, er) { // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f); this.cache[abs] = 'FILE'; if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd); error.path = this.cwd; error.code = er.code; throw error } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false; break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false; if (this.strict) throw er if (!this.silent) console.error('glob error', er); break } }; GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar); // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1); var gspref = prefix ? [ prefix ] : []; var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false); var len = entries.length; var isSym = this.symlinks[abs]; // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return for (var i = 0; i < len; i++) { var e = entries[i]; if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar); this._process(instead, index, true); var below = gspref.concat(entries[i], remain); this._process(below, index, true); } }; GlobSync.prototype._processSimple = function (prefix, index) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var exists = this._stat(prefix); if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results if (!exists) return if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix); if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix); } else { prefix = path.resolve(this.root, prefix); if (trail) prefix += '/'; } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match this._emitMatch(index, prefix); }; // Returns either 'DIR', 'FILE', or false GlobSync.prototype._stat = function (f) { var abs = this._makeAbs(f); var needDir = f.slice(-1) === '/'; if (f.length > this.maxLength) return false if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs]; if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return c if (needDir && c === 'FILE') return false // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var stat = this.statCache[abs]; if (!stat) { var lstat; try { lstat = this.fs.lstatSync(abs); } catch (er) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false; return false } } if (lstat && lstat.isSymbolicLink()) { try { stat = this.fs.statSync(abs); } catch (er) { stat = lstat; } } else { stat = lstat; } } this.statCache[abs] = stat; var c = true; if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE'; this.cache[abs] = this.cache[abs] || c; if (needDir && c === 'FILE') return false return c }; GlobSync.prototype._mark = function (p) { return common.mark(this, p) }; GlobSync.prototype._makeAbs = function (f) { return common.makeAbs(this, f) }; return sync$9$1; } // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. // This makes sure that own properties are retained, so that // decorations and such are not lost along the way. var wrappy_1$1 = wrappy$2$1; function wrappy$2$1 (fn, cb) { if (fn && cb) return wrappy$2$1(fn)(cb) if (typeof fn !== 'function') throw new TypeError('need wrapper function') Object.keys(fn).forEach(function (k) { wrapper[k] = fn[k]; }); return wrapper function wrapper() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } var ret = fn.apply(this, args); var cb = args[args.length-1]; if (typeof ret === 'function' && ret !== cb) { Object.keys(cb).forEach(function (k) { ret[k] = cb[k]; }); } return ret } } var once$2$1 = {exports: {}}; var wrappy$1$1 = wrappy_1$1; once$2$1.exports = wrappy$1$1(once$1$1); once$2$1.exports.strict = wrappy$1$1(onceStrict$1); once$1$1.proto = once$1$1(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once$1$1(this) }, configurable: true }); Object.defineProperty(Function.prototype, 'onceStrict', { value: function () { return onceStrict$1(this) }, configurable: true }); }); function once$1$1 (fn) { var f = function () { if (f.called) return f.value f.called = true; return f.value = fn.apply(this, arguments) }; f.called = false; return f } function onceStrict$1 (fn) { var f = function () { if (f.called) throw new Error(f.onceError) f.called = true; return f.value = fn.apply(this, arguments) }; var name = fn.name || 'Function wrapped with `once`'; f.onceError = name + " shouldn't be called more than once"; f.called = false; return f } var onceExports$1 = once$2$1.exports; var wrappy$3 = wrappy_1$1; var reqs$1 = Object.create(null); var once$3 = onceExports$1; var inflight_1$1 = wrappy$3(inflight$1); function inflight$1 (key, cb) { if (reqs$1[key]) { reqs$1[key].push(cb); return null } else { reqs$1[key] = [cb]; return makeres$1(key) } } function makeres$1 (key) { return once$3(function RES () { var cbs = reqs$1[key]; var len = cbs.length; var args = slice$1$1(arguments); // XXX It's somewhat ambiguous whether a new callback added in this // pass should be queued for later execution if something in the // list of callbacks throws, or if it should just be discarded. // However, it's such an edge case that it hardly matters, and either // choice is likely as surprising as the other. // As it happens, we do go ahead and schedule it for later execution. try { for (var i = 0; i < len; i++) { cbs[i].apply(null, args); } } finally { if (cbs.length > len) { // added more in the interim. // de-zalgo, just in case, but don't call again. cbs.splice(0, len); process.nextTick(function () { RES.apply(null, args); }); } else { delete reqs$1[key]; } } }) } function slice$1$1 (args) { var length = args.length; var array = []; for (var i = 0; i < length; i++) array[i] = args[i]; return array } var glob_1$1; var hasRequiredGlob$1; function requireGlob$1 () { if (hasRequiredGlob$1) return glob_1$1; hasRequiredGlob$1 = 1; // Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. glob_1$1 = glob; var rp = fs_realpath$1; var minimatch = minimatch_1$1; var inherits = inheritsExports$1; var EE = require$$0$5.EventEmitter; var path = require$$0$4; var assert = require$$5; var isAbsolute = require$$0$4.isAbsolute; var globSync = requireSync$1(); var common = common$c$1; var setopts = common.setopts; var ownProp = common.ownProp; var inflight = inflight_1$1; var childrenIgnored = common.childrenIgnored; var isIgnored = common.isIgnored; var once = onceExports$1; function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {}; if (!options) options = {}; if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return globSync(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = globSync; var GlobSync = glob.GlobSync = globSync.GlobSync; // old api surface glob.glob = glob; function extend (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin } glob.hasMagic = function (pattern, options_) { var options = extend({}, options_); options.noprocess = true; var g = new Glob(pattern, options); var set = g.minimatch.set; if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false }; glob.Glob = Glob; inherits(Glob, EE); function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options; options = null; } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options); this._didRealPath = false; // process each pattern in the minimatch set var n = this.minimatch.set.length; // The matches are stored as {: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n); if (typeof cb === 'function') { cb = once(cb); this.on('error', cb); this.on('end', function (matches) { cb(null, matches); }); } var self = this; this._processing = 0; this._emitQueue = []; this._processQueue = []; this.paused = false; if (this.noprocess) return this if (n === 0) return done() var sync = true; for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done); } sync = false; function done () { --self._processing; if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish(); }); } else { self._finish(); } } } } Glob.prototype._finish = function () { assert(this instanceof Glob); if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.finish(this); this.emit('end', this.found); }; Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true; var n = this.matches.length; if (n === 0) return this._finish() var self = this; for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next); function next () { if (--n === 0) self._finish(); } }; Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index]; if (!matchset) return cb() var found = Object.keys(matchset); var self = this; var n = found.length; if (n === 0) return cb() var set = this.matches[index] = Object.create(null); found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p); rp.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true; else if (er.syscall === 'stat') set[p] = true; else self.emit('error', er); // srsly wtf right here if (--n === 0) { self.matches[index] = set; cb(); } }); }); }; Glob.prototype._mark = function (p) { return common.mark(this, p) }; Glob.prototype._makeAbs = function (f) { return common.makeAbs(this, f) }; Glob.prototype.abort = function () { this.aborted = true; this.emit('abort'); }; Glob.prototype.pause = function () { if (!this.paused) { this.paused = true; this.emit('pause'); } }; Glob.prototype.resume = function () { if (this.paused) { this.emit('resume'); this.paused = false; if (this._emitQueue.length) { var eq = this._emitQueue.slice(0); this._emitQueue.length = 0; for (var i = 0; i < eq.length; i ++) { var e = eq[i]; this._emitMatch(e[0], e[1]); } } if (this._processQueue.length) { var pq = this._processQueue.slice(0); this._processQueue.length = 0; for (var i = 0; i < pq.length; i ++) { var p = pq[i]; this._processing--; this._process(p[0], p[1], p[2], p[3]); } } } }; Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert(this instanceof Glob); assert(typeof cb === 'function'); if (this.aborted) return this._processing++; if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]); return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0; while (typeof pattern[n] === 'string') { n ++; } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix; switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb); return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null; break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/'); break } var remain = pattern.slice(n); // get the list of entries. var read; if (prefix === null) read = '.'; else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) { return typeof p === 'string' ? p : '[*]' }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix; read = prefix; } else read = prefix; var abs = this._makeAbs(read); //if ignored, skip _processing if (childrenIgnored(this, read)) return cb() var isGlobStar = remain[0] === minimatch.GLOBSTAR; if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb); else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb); }; Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this; this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }); }; Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0]; var negate = !!this.minimatch.negate; var rawGlob = pn._glob; var dotOk = this.dot || rawGlob.charAt(0) === '.'; var matchedEntries = []; for (var i = 0; i < entries.length; i++) { var e = entries[i]; if (e.charAt(0) !== '.' || dotOk) { var m; if (negate && !prefix) { m = !e.match(pn); } else { m = e.match(pn); } if (m) matchedEntries.push(e); } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length; // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; if (prefix) { if (prefix !== '/') e = prefix + '/' + e; else e = prefix + e; } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e); } this._emitMatch(index, e); } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift(); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; if (prefix) { if (prefix !== '/') e = prefix + '/' + e; else e = prefix + e; } this._process([e].concat(remain), index, inGlobStar, cb); } cb(); }; Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored(this, e)) return if (this.paused) { this._emitQueue.push([index, e]); return } var abs = isAbsolute(e) ? e : this._makeAbs(e); if (this.mark) e = this._mark(e); if (this.absolute) e = abs; if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs]; if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true; var st = this.statCache[abs]; if (st) this.emit('stat', e, st); this.emit('match', e); }; Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs; var self = this; var lstatcb = inflight(lstatkey, lstatcb_); if (lstatcb) self.fs.lstat(abs, lstatcb); function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink(); self.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE'; cb(); } else self._readdir(abs, false, cb); } }; Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb); if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs]; if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this; self.fs.readdir(abs, readdirCb(this, abs, cb)); }; function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb); else self._readdirEntries(abs, entries, cb); } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i]; if (abs === '/') e = abs + e; else e = abs + '/' + e; this.cache[e] = true; } } this.cache[abs] = entries; return cb(null, entries) }; Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f); this.cache[abs] = 'FILE'; if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd); error.path = this.cwd; error.code = er.code; this.emit('error', error); this.abort(); } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false; break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false; if (this.strict) { this.emit('error', er); // If the error is handled, then we abort // if not, we threw out of here this.abort(); } if (!this.silent) console.error('glob error', er); break } return cb() }; Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this; this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb); }); }; Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1); var gspref = prefix ? [ prefix ] : []; var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb); var isSym = this.symlinks[abs]; var len = entries.length; // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i]; if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar); this._process(instead, index, true, cb); var below = gspref.concat(entries[i], remain); this._process(below, index, true, cb); } cb(); }; Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this; this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb); }); }; Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix); if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix); } else { prefix = path.resolve(this.root, prefix); if (trail) prefix += '/'; } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match this._emitMatch(index, prefix); cb(); }; // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f); var needDir = f.slice(-1) === '/'; if (f.length > this.maxLength) return cb() if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs]; if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var stat = this.statCache[abs]; if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE'; if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this; var statcb = inflight('stat\0' + abs, lstatcb_); if (statcb) self.fs.lstat(abs, statcb); function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return self.fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb); else self._stat2(f, abs, er, stat, cb); }) } else { self._stat2(f, abs, er, lstat, cb); } } }; Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false; return cb() } var needDir = f.slice(-1) === '/'; this.statCache[abs] = stat; if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true; if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE'; this.cache[abs] = this.cache[abs] || c; if (needDir && c === 'FILE') return cb() return cb(null, c, stat) }; return glob_1$1; } var globExports = requireGlob$1(); var glob$1 = /*@__PURE__*/getDefaultExportFromCjs$2(globExports); const comma$1 = ','.charCodeAt(0); const semicolon$2 = ';'.charCodeAt(0); const chars$1$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; const intToChar$3 = new Uint8Array(64); // 64 possible chars. const charToInt$3 = new Uint8Array(128); // z is 122 in ASCII for (let i = 0; i < chars$1$1.length; i++) { const c = chars$1$1.charCodeAt(i); intToChar$3[i] = c; charToInt$3[c] = i; } // Provide a fallback for older environments. const td$1 = typeof TextDecoder !== 'undefined' ? /* #__PURE__ */ new TextDecoder() : typeof Buffer !== 'undefined' ? { decode(buf) { const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); return out.toString(); }, } : { decode(buf) { let out = ''; for (let i = 0; i < buf.length; i++) { out += String.fromCharCode(buf[i]); } return out; }, }; function decode(mappings) { const state = new Int32Array(5); const decoded = []; let index = 0; do { const semi = indexOf(mappings, index); const line = []; let sorted = true; let lastCol = 0; state[0] = 0; for (let i = index; i < semi; i++) { let seg; i = decodeInteger(mappings, i, state, 0); // genColumn const col = state[0]; if (col < lastCol) sorted = false; lastCol = col; if (hasMoreVlq(mappings, i, semi)) { i = decodeInteger(mappings, i, state, 1); // sourcesIndex i = decodeInteger(mappings, i, state, 2); // sourceLine i = decodeInteger(mappings, i, state, 3); // sourceColumn if (hasMoreVlq(mappings, i, semi)) { i = decodeInteger(mappings, i, state, 4); // namesIndex seg = [col, state[1], state[2], state[3], state[4]]; } else { seg = [col, state[1], state[2], state[3]]; } } else { seg = [col]; } line.push(seg); } if (!sorted) sort(line); decoded.push(line); index = semi + 1; } while (index <= mappings.length); return decoded; } function indexOf(mappings, index) { const idx = mappings.indexOf(';', index); return idx === -1 ? mappings.length : idx; } function decodeInteger(mappings, pos, state, j) { let value = 0; let shift = 0; let integer = 0; do { const c = mappings.charCodeAt(pos++); integer = charToInt$3[c]; value |= (integer & 31) << shift; shift += 5; } while (integer & 32); const shouldNegate = value & 1; value >>>= 1; if (shouldNegate) { value = -0x80000000 | -value; } state[j] += value; return pos; } function hasMoreVlq(mappings, i, length) { if (i >= length) return false; return mappings.charCodeAt(i) !== comma$1; } function sort(line) { line.sort(sortComparator$1); } function sortComparator$1(a, b) { return a[0] - b[0]; } function encode$1(decoded) { const state = new Int32Array(5); const bufLength = 1024 * 16; const subLength = bufLength - 36; const buf = new Uint8Array(bufLength); const sub = buf.subarray(0, subLength); let pos = 0; let out = ''; for (let i = 0; i < decoded.length; i++) { const line = decoded[i]; if (i > 0) { if (pos === bufLength) { out += td$1.decode(buf); pos = 0; } buf[pos++] = semicolon$2; } if (line.length === 0) continue; state[0] = 0; for (let j = 0; j < line.length; j++) { const segment = line[j]; // We can push up to 5 ints, each int can take at most 7 chars, and we // may push a comma. if (pos > subLength) { out += td$1.decode(sub); buf.copyWithin(0, subLength, pos); pos -= subLength; } if (j > 0) buf[pos++] = comma$1; pos = encodeInteger$1(buf, pos, state, segment, 0); // genColumn if (segment.length === 1) continue; pos = encodeInteger$1(buf, pos, state, segment, 1); // sourcesIndex pos = encodeInteger$1(buf, pos, state, segment, 2); // sourceLine pos = encodeInteger$1(buf, pos, state, segment, 3); // sourceColumn if (segment.length === 4) continue; pos = encodeInteger$1(buf, pos, state, segment, 4); // namesIndex } } return out + td$1.decode(buf.subarray(0, pos)); } function encodeInteger$1(buf, pos, state, segment, j) { const next = segment[j]; let num = next - state[j]; state[j] = next; num = num < 0 ? (-num << 1) | 1 : num << 1; do { let clamped = num & 0b011111; num >>>= 5; if (num > 0) clamped |= 0b100000; buf[pos++] = intToChar$3[clamped]; } while (num > 0); return pos; } let BitSet$1 = class BitSet { constructor(arg) { this.bits = arg instanceof BitSet ? arg.bits.slice() : []; } add(n) { this.bits[n >> 5] |= 1 << (n & 31); } has(n) { return !!(this.bits[n >> 5] & (1 << (n & 31))); } }; let Chunk$1 = class Chunk { constructor(start, end, content) { this.start = start; this.end = end; this.original = content; this.intro = ''; this.outro = ''; this.content = content; this.storeName = false; this.edited = false; { this.previous = null; this.next = null; } } appendLeft(content) { this.outro += content; } appendRight(content) { this.intro = this.intro + content; } clone() { const chunk = new Chunk(this.start, this.end, this.original); chunk.intro = this.intro; chunk.outro = this.outro; chunk.content = this.content; chunk.storeName = this.storeName; chunk.edited = this.edited; return chunk; } contains(index) { return this.start < index && index < this.end; } eachNext(fn) { let chunk = this; while (chunk) { fn(chunk); chunk = chunk.next; } } eachPrevious(fn) { let chunk = this; while (chunk) { fn(chunk); chunk = chunk.previous; } } edit(content, storeName, contentOnly) { this.content = content; if (!contentOnly) { this.intro = ''; this.outro = ''; } this.storeName = storeName; this.edited = true; return this; } prependLeft(content) { this.outro = content + this.outro; } prependRight(content) { this.intro = content + this.intro; } split(index) { const sliceIndex = index - this.start; const originalBefore = this.original.slice(0, sliceIndex); const originalAfter = this.original.slice(sliceIndex); this.original = originalBefore; const newChunk = new Chunk(index, this.end, originalAfter); newChunk.outro = this.outro; this.outro = ''; this.end = index; if (this.edited) { // TODO is this block necessary?... newChunk.edit('', false); this.content = ''; } else { this.content = originalBefore; } newChunk.next = this.next; if (newChunk.next) newChunk.next.previous = newChunk; newChunk.previous = this; this.next = newChunk; return newChunk; } toString() { return this.intro + this.content + this.outro; } trimEnd(rx) { this.outro = this.outro.replace(rx, ''); if (this.outro.length) return true; const trimmed = this.content.replace(rx, ''); if (trimmed.length) { if (trimmed !== this.content) { this.split(this.start + trimmed.length).edit('', undefined, true); } return true; } else { this.edit('', undefined, true); this.intro = this.intro.replace(rx, ''); if (this.intro.length) return true; } } trimStart(rx) { this.intro = this.intro.replace(rx, ''); if (this.intro.length) return true; const trimmed = this.content.replace(rx, ''); if (trimmed.length) { if (trimmed !== this.content) { this.split(this.end - trimmed.length); this.edit('', undefined, true); } return true; } else { this.edit('', undefined, true); this.outro = this.outro.replace(rx, ''); if (this.outro.length) return true; } } }; function getBtoa$1 () { if (typeof window !== 'undefined' && typeof window.btoa === 'function') { return (str) => window.btoa(unescape(encodeURIComponent(str))); } else if (typeof Buffer === 'function') { return (str) => Buffer.from(str, 'utf-8').toString('base64'); } else { return () => { throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); }; } } const btoa$2 = /*#__PURE__*/ getBtoa$1(); let SourceMap$2 = class SourceMap { constructor(properties) { this.version = 3; this.file = properties.file; this.sources = properties.sources; this.sourcesContent = properties.sourcesContent; this.names = properties.names; this.mappings = encode$1(properties.mappings); } toString() { return JSON.stringify(this); } toUrl() { return 'data:application/json;charset=utf-8;base64,' + btoa$2(this.toString()); } }; function guessIndent$1(code) { const lines = code.split('\n'); const tabbed = lines.filter((line) => /^\t+/.test(line)); const spaced = lines.filter((line) => /^ {2,}/.test(line)); if (tabbed.length === 0 && spaced.length === 0) { return null; } // More lines tabbed than spaced? Assume tabs, and // default to tabs in the case of a tie (or nothing // to go on) if (tabbed.length >= spaced.length) { return '\t'; } // Otherwise, we need to guess the multiple const min = spaced.reduce((previous, current) => { const numSpaces = /^ +/.exec(current)[0].length; return Math.min(numSpaces, previous); }, Infinity); return new Array(min + 1).join(' '); } function getRelativePath$1(from, to) { const fromParts = from.split(/[/\\]/); const toParts = to.split(/[/\\]/); fromParts.pop(); // get dirname while (fromParts[0] === toParts[0]) { fromParts.shift(); toParts.shift(); } if (fromParts.length) { let i = fromParts.length; while (i--) fromParts[i] = '..'; } return fromParts.concat(toParts).join('/'); } const toString$3 = Object.prototype.toString; function isObject$3(thing) { return toString$3.call(thing) === '[object Object]'; } function getLocator$1(source) { const originalLines = source.split('\n'); const lineOffsets = []; for (let i = 0, pos = 0; i < originalLines.length; i++) { lineOffsets.push(pos); pos += originalLines[i].length + 1; } return function locate(index) { let i = 0; let j = lineOffsets.length; while (i < j) { const m = (i + j) >> 1; if (index < lineOffsets[m]) { j = m; } else { i = m + 1; } } const line = i - 1; const column = index - lineOffsets[line]; return { line, column }; }; } let Mappings$1 = class Mappings { constructor(hires) { this.hires = hires; this.generatedCodeLine = 0; this.generatedCodeColumn = 0; this.raw = []; this.rawSegments = this.raw[this.generatedCodeLine] = []; this.pending = null; } addEdit(sourceIndex, content, loc, nameIndex) { if (content.length) { const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; if (nameIndex >= 0) { segment.push(nameIndex); } this.rawSegments.push(segment); } else if (this.pending) { this.rawSegments.push(this.pending); } this.advance(content); this.pending = null; } addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { let originalCharIndex = chunk.start; let first = true; while (originalCharIndex < chunk.end) { if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]); } if (original[originalCharIndex] === '\n') { loc.line += 1; loc.column = 0; this.generatedCodeLine += 1; this.raw[this.generatedCodeLine] = this.rawSegments = []; this.generatedCodeColumn = 0; first = true; } else { loc.column += 1; this.generatedCodeColumn += 1; first = false; } originalCharIndex += 1; } this.pending = null; } advance(str) { if (!str) return; const lines = str.split('\n'); if (lines.length > 1) { for (let i = 0; i < lines.length - 1; i++) { this.generatedCodeLine++; this.raw[this.generatedCodeLine] = this.rawSegments = []; } this.generatedCodeColumn = 0; } this.generatedCodeColumn += lines[lines.length - 1].length; } }; const n$2 = '\n'; const warned$1 = { insertLeft: false, insertRight: false, storeName: false, }; let MagicString$1 = class MagicString { constructor(string, options = {}) { const chunk = new Chunk$1(0, string.length, string); Object.defineProperties(this, { original: { writable: true, value: string }, outro: { writable: true, value: '' }, intro: { writable: true, value: '' }, firstChunk: { writable: true, value: chunk }, lastChunk: { writable: true, value: chunk }, lastSearchedChunk: { writable: true, value: chunk }, byStart: { writable: true, value: {} }, byEnd: { writable: true, value: {} }, filename: { writable: true, value: options.filename }, indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, sourcemapLocations: { writable: true, value: new BitSet$1() }, storedNames: { writable: true, value: {} }, indentStr: { writable: true, value: undefined }, }); this.byStart[0] = chunk; this.byEnd[string.length] = chunk; } addSourcemapLocation(char) { this.sourcemapLocations.add(char); } append(content) { if (typeof content !== 'string') throw new TypeError('outro content must be a string'); this.outro += content; return this; } appendLeft(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byEnd[index]; if (chunk) { chunk.appendLeft(content); } else { this.intro += content; } return this; } appendRight(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byStart[index]; if (chunk) { chunk.appendRight(content); } else { this.outro += content; } return this; } clone() { const cloned = new MagicString(this.original, { filename: this.filename }); let originalChunk = this.firstChunk; let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); while (originalChunk) { cloned.byStart[clonedChunk.start] = clonedChunk; cloned.byEnd[clonedChunk.end] = clonedChunk; const nextOriginalChunk = originalChunk.next; const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); if (nextClonedChunk) { clonedChunk.next = nextClonedChunk; nextClonedChunk.previous = clonedChunk; clonedChunk = nextClonedChunk; } originalChunk = nextOriginalChunk; } cloned.lastChunk = clonedChunk; if (this.indentExclusionRanges) { cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); } cloned.sourcemapLocations = new BitSet$1(this.sourcemapLocations); cloned.intro = this.intro; cloned.outro = this.outro; return cloned; } generateDecodedMap(options) { options = options || {}; const sourceIndex = 0; const names = Object.keys(this.storedNames); const mappings = new Mappings$1(options.hires); const locate = getLocator$1(this.original); if (this.intro) { mappings.advance(this.intro); } this.firstChunk.eachNext((chunk) => { const loc = locate(chunk.start); if (chunk.intro.length) mappings.advance(chunk.intro); if (chunk.edited) { mappings.addEdit( sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1 ); } else { mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); } if (chunk.outro.length) mappings.advance(chunk.outro); }); return { file: options.file ? options.file.split(/[/\\]/).pop() : null, sources: [options.source ? getRelativePath$1(options.file || '', options.source) : null], sourcesContent: options.includeContent ? [this.original] : [null], names, mappings: mappings.raw, }; } generateMap(options) { return new SourceMap$2(this.generateDecodedMap(options)); } _ensureindentStr() { if (this.indentStr === undefined) { this.indentStr = guessIndent$1(this.original); } } _getRawIndentString() { this._ensureindentStr(); return this.indentStr; } getIndentString() { this._ensureindentStr(); return this.indentStr === null ? '\t' : this.indentStr; } indent(indentStr, options) { const pattern = /^[^\r\n]/gm; if (isObject$3(indentStr)) { options = indentStr; indentStr = undefined; } if (indentStr === undefined) { this._ensureindentStr(); indentStr = this.indentStr || '\t'; } if (indentStr === '') return this; // noop options = options || {}; // Process exclusion ranges const isExcluded = {}; if (options.exclude) { const exclusions = typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; exclusions.forEach((exclusion) => { for (let i = exclusion[0]; i < exclusion[1]; i += 1) { isExcluded[i] = true; } }); } let shouldIndentNextCharacter = options.indentStart !== false; const replacer = (match) => { if (shouldIndentNextCharacter) return `${indentStr}${match}`; shouldIndentNextCharacter = true; return match; }; this.intro = this.intro.replace(pattern, replacer); let charIndex = 0; let chunk = this.firstChunk; while (chunk) { const end = chunk.end; if (chunk.edited) { if (!isExcluded[charIndex]) { chunk.content = chunk.content.replace(pattern, replacer); if (chunk.content.length) { shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; } } } else { charIndex = chunk.start; while (charIndex < end) { if (!isExcluded[charIndex]) { const char = this.original[charIndex]; if (char === '\n') { shouldIndentNextCharacter = true; } else if (char !== '\r' && shouldIndentNextCharacter) { shouldIndentNextCharacter = false; if (charIndex === chunk.start) { chunk.prependRight(indentStr); } else { this._splitChunk(chunk, charIndex); chunk = chunk.next; chunk.prependRight(indentStr); } } } charIndex += 1; } } charIndex = chunk.end; chunk = chunk.next; } this.outro = this.outro.replace(pattern, replacer); return this; } insert() { throw new Error( 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)' ); } insertLeft(index, content) { if (!warned$1.insertLeft) { console.warn( 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead' ); // eslint-disable-line no-console warned$1.insertLeft = true; } return this.appendLeft(index, content); } insertRight(index, content) { if (!warned$1.insertRight) { console.warn( 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead' ); // eslint-disable-line no-console warned$1.insertRight = true; } return this.prependRight(index, content); } move(start, end, index) { if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself'); this._split(start); this._split(end); this._split(index); const first = this.byStart[start]; const last = this.byEnd[end]; const oldLeft = first.previous; const oldRight = last.next; const newRight = this.byStart[index]; if (!newRight && last === this.lastChunk) return this; const newLeft = newRight ? newRight.previous : this.lastChunk; if (oldLeft) oldLeft.next = oldRight; if (oldRight) oldRight.previous = oldLeft; if (newLeft) newLeft.next = first; if (newRight) newRight.previous = last; if (!first.previous) this.firstChunk = last.next; if (!last.next) { this.lastChunk = first.previous; this.lastChunk.next = null; } first.previous = newLeft; last.next = newRight || null; if (!newLeft) this.firstChunk = first; if (!newRight) this.lastChunk = last; return this; } overwrite(start, end, content, options) { options = options || {}; return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); } update(start, end, content, options) { if (typeof content !== 'string') throw new TypeError('replacement content must be a string'); while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; if (end > this.original.length) throw new Error('end is out of bounds'); if (start === end) throw new Error( 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead' ); this._split(start); this._split(end); if (options === true) { if (!warned$1.storeName) { console.warn( 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string' ); // eslint-disable-line no-console warned$1.storeName = true; } options = { storeName: true }; } const storeName = options !== undefined ? options.storeName : false; const overwrite = options !== undefined ? options.overwrite : false; if (storeName) { const original = this.original.slice(start, end); Object.defineProperty(this.storedNames, original, { writable: true, value: true, enumerable: true, }); } const first = this.byStart[start]; const last = this.byEnd[end]; if (first) { let chunk = first; while (chunk !== last) { if (chunk.next !== this.byStart[chunk.end]) { throw new Error('Cannot overwrite across a split point'); } chunk = chunk.next; chunk.edit('', false); } first.edit(content, storeName, !overwrite); } else { // must be inserting at the end const newChunk = new Chunk$1(start, end, '').edit(content, storeName); // TODO last chunk in the array may not be the last chunk, if it's moved... last.next = newChunk; newChunk.previous = last; } return this; } prepend(content) { if (typeof content !== 'string') throw new TypeError('outro content must be a string'); this.intro = content + this.intro; return this; } prependLeft(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byEnd[index]; if (chunk) { chunk.prependLeft(content); } else { this.intro = content + this.intro; } return this; } prependRight(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byStart[index]; if (chunk) { chunk.prependRight(content); } else { this.outro = content + this.outro; } return this; } remove(start, end) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; if (start === end) return this; if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); if (start > end) throw new Error('end must be greater than start'); this._split(start); this._split(end); let chunk = this.byStart[start]; while (chunk) { chunk.intro = ''; chunk.outro = ''; chunk.edit(''); chunk = end > chunk.end ? this.byStart[chunk.end] : null; } return this; } lastChar() { if (this.outro.length) return this.outro[this.outro.length - 1]; let chunk = this.lastChunk; do { if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; if (chunk.content.length) return chunk.content[chunk.content.length - 1]; if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; } while ((chunk = chunk.previous)); if (this.intro.length) return this.intro[this.intro.length - 1]; return ''; } lastLine() { let lineIndex = this.outro.lastIndexOf(n$2); if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); let lineStr = this.outro; let chunk = this.lastChunk; do { if (chunk.outro.length > 0) { lineIndex = chunk.outro.lastIndexOf(n$2); if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; lineStr = chunk.outro + lineStr; } if (chunk.content.length > 0) { lineIndex = chunk.content.lastIndexOf(n$2); if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; lineStr = chunk.content + lineStr; } if (chunk.intro.length > 0) { lineIndex = chunk.intro.lastIndexOf(n$2); if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; lineStr = chunk.intro + lineStr; } } while ((chunk = chunk.previous)); lineIndex = this.intro.lastIndexOf(n$2); if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; return this.intro + lineStr; } slice(start = 0, end = this.original.length) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; let result = ''; // find start chunk let chunk = this.firstChunk; while (chunk && (chunk.start > start || chunk.end <= start)) { // found end chunk before start if (chunk.start < end && chunk.end >= end) { return result; } chunk = chunk.next; } if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); const startChunk = chunk; while (chunk) { if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { result += chunk.intro; } const containsEnd = chunk.start < end && chunk.end >= end; if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); const sliceStart = startChunk === chunk ? start - chunk.start : 0; const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; result += chunk.content.slice(sliceStart, sliceEnd); if (chunk.outro && (!containsEnd || chunk.end === end)) { result += chunk.outro; } if (containsEnd) { break; } chunk = chunk.next; } return result; } // TODO deprecate this? not really very useful snip(start, end) { const clone = this.clone(); clone.remove(0, start); clone.remove(end, clone.original.length); return clone; } _split(index) { if (this.byStart[index] || this.byEnd[index]) return; let chunk = this.lastSearchedChunk; const searchForward = index > chunk.end; while (chunk) { if (chunk.contains(index)) return this._splitChunk(chunk, index); chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; } } _splitChunk(chunk, index) { if (chunk.edited && chunk.content.length) { // zero-length edited chunks are a special case (overlapping replacements) const loc = getLocator$1(this.original)(index); throw new Error( `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")` ); } const newChunk = chunk.split(index); this.byEnd[index] = chunk; this.byStart[index] = newChunk; this.byEnd[newChunk.end] = newChunk; if (chunk === this.lastChunk) this.lastChunk = newChunk; this.lastSearchedChunk = chunk; return true; } toString() { let str = this.intro; let chunk = this.firstChunk; while (chunk) { str += chunk.toString(); chunk = chunk.next; } return str + this.outro; } isEmpty() { let chunk = this.firstChunk; do { if ( (chunk.intro.length && chunk.intro.trim()) || (chunk.content.length && chunk.content.trim()) || (chunk.outro.length && chunk.outro.trim()) ) return false; } while ((chunk = chunk.next)); return true; } length() { let chunk = this.firstChunk; let length = 0; do { length += chunk.intro.length + chunk.content.length + chunk.outro.length; } while ((chunk = chunk.next)); return length; } trimLines() { return this.trim('[\\r\\n]'); } trim(charType) { return this.trimStart(charType).trimEnd(charType); } trimEndAborted(charType) { const rx = new RegExp((charType || '\\s') + '+$'); this.outro = this.outro.replace(rx, ''); if (this.outro.length) return true; let chunk = this.lastChunk; do { const end = chunk.end; const aborted = chunk.trimEnd(rx); // if chunk was trimmed, we have a new lastChunk if (chunk.end !== end) { if (this.lastChunk === chunk) { this.lastChunk = chunk.next; } this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) return true; chunk = chunk.previous; } while (chunk); return false; } trimEnd(charType) { this.trimEndAborted(charType); return this; } trimStartAborted(charType) { const rx = new RegExp('^' + (charType || '\\s') + '+'); this.intro = this.intro.replace(rx, ''); if (this.intro.length) return true; let chunk = this.firstChunk; do { const end = chunk.end; const aborted = chunk.trimStart(rx); if (chunk.end !== end) { // special case... if (chunk === this.lastChunk) this.lastChunk = chunk.next; this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) return true; chunk = chunk.next; } while (chunk); return false; } trimStart(charType) { this.trimStartAborted(charType); return this; } hasChanged() { return this.original !== this.toString(); } _replaceRegexp(searchValue, replacement) { function getReplacement(match, str) { if (typeof replacement === 'string') { return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter if (i === '$') return '$'; if (i === '&') return match[0]; const num = +i; if (num < match.length) return match[+i]; return `$${i}`; }); } else { return replacement(...match, match.index, str, match.groups); } } function matchAll(re, str) { let match; const matches = []; while ((match = re.exec(str))) { matches.push(match); } return matches; } if (searchValue.global) { const matches = matchAll(searchValue, this.original); matches.forEach((match) => { if (match.index != null) this.overwrite( match.index, match.index + match[0].length, getReplacement(match, this.original) ); }); } else { const match = this.original.match(searchValue); if (match && match.index != null) this.overwrite( match.index, match.index + match[0].length, getReplacement(match, this.original) ); } return this; } _replaceString(string, replacement) { const { original } = this; const index = original.indexOf(string); if (index !== -1) { this.overwrite(index, index + string.length, replacement); } return this; } replace(searchValue, replacement) { if (typeof searchValue === 'string') { return this._replaceString(searchValue, replacement); } return this._replaceRegexp(searchValue, replacement); } _replaceAllString(string, replacement) { const { original } = this; const stringLength = string.length; for ( let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength) ) { this.overwrite(index, index + stringLength, replacement); } return this; } replaceAll(searchValue, replacement) { if (typeof searchValue === 'string') { return this._replaceAllString(searchValue, replacement); } if (!searchValue.global) { throw new TypeError( 'MagicString.prototype.replaceAll called with a non-global RegExp argument' ); } return this._replaceRegexp(searchValue, replacement); } }; function isReference(node, parent) { if (node.type === 'MemberExpression') { return !node.computed && isReference(node.object, node); } if (node.type === 'Identifier') { if (!parent) return true; switch (parent.type) { // disregard `bar` in `foo.bar` case 'MemberExpression': return parent.computed || node === parent.object; // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}` case 'MethodDefinition': return parent.computed; // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}` case 'FieldDefinition': return parent.computed || node === parent.value; // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }` case 'Property': return parent.computed || node === parent.value; // disregard the `bar` in `export { foo as bar }` or // the foo in `import { foo as bar }` case 'ExportSpecifier': case 'ImportSpecifier': return node === parent.local; // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}` case 'LabeledStatement': case 'BreakStatement': case 'ContinueStatement': return false; default: return true; } } return false; } var version$3$1 = "24.1.0"; var peerDependencies$1 = { rollup: "^2.68.0||^3.0.0" }; function tryParse(parse, code, id) { try { return parse(code, { allowReturnOutsideFunction: true }); } catch (err) { err.message += ` in ${id}`; throw err; } } const firstpassGlobal = /\b(?:require|module|exports|global)\b/; const firstpassNoGlobal = /\b(?:require|module|exports)\b/; function hasCjsKeywords(code, ignoreGlobal) { const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal; return firstpass.test(code); } /* eslint-disable no-underscore-dangle */ function analyzeTopLevelStatements(parse, code, id) { const ast = tryParse(parse, code, id); let isEsModule = false; let hasDefaultExport = false; let hasNamedExports = false; for (const node of ast.body) { switch (node.type) { case 'ExportDefaultDeclaration': isEsModule = true; hasDefaultExport = true; break; case 'ExportNamedDeclaration': isEsModule = true; if (node.declaration) { hasNamedExports = true; } else { for (const specifier of node.specifiers) { if (specifier.exported.name === 'default') { hasDefaultExport = true; } else { hasNamedExports = true; } } } break; case 'ExportAllDeclaration': isEsModule = true; if (node.exported && node.exported.name === 'default') { hasDefaultExport = true; } else { hasNamedExports = true; } break; case 'ImportDeclaration': isEsModule = true; break; } } return { isEsModule, hasDefaultExport, hasNamedExports, ast }; } /* eslint-disable import/prefer-default-export */ function deconflict(scopes, globals, identifier) { let i = 1; let deconflicted = makeLegalIdentifier(identifier); const hasConflicts = () => scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted); while (hasConflicts()) { deconflicted = makeLegalIdentifier(`${identifier}_${i}`); i += 1; } for (const scope of scopes) { scope.declarations[deconflicted] = true; } return deconflicted; } function getName(id) { const name = makeLegalIdentifier(basename$2(id, extname$1(id))); if (name !== 'index') { return name; } return makeLegalIdentifier(basename$2(dirname$2(id))); } function normalizePathSlashes(path) { return path.replace(/\\/g, '/'); } const getVirtualPathForDynamicRequirePath = (path, commonDir) => `/${normalizePathSlashes(relative$3(commonDir, path))}`; function capitalize(name) { return name[0].toUpperCase() + name.slice(1); } function getStrictRequiresFilter({ strictRequires }) { switch (strictRequires) { case true: return { strictRequiresFilter: () => true, detectCyclesAndConditional: false }; // eslint-disable-next-line no-undefined case undefined: case 'auto': case 'debug': case null: return { strictRequiresFilter: () => false, detectCyclesAndConditional: true }; case false: return { strictRequiresFilter: () => false, detectCyclesAndConditional: false }; default: if (typeof strictRequires === 'string' || Array.isArray(strictRequires)) { return { strictRequiresFilter: createFilter$1$1(strictRequires), detectCyclesAndConditional: false }; } throw new Error('Unexpected value for "strictRequires" option.'); } } function getPackageEntryPoint(dirPath) { let entryPoint = 'index.js'; try { if (existsSync(join$3(dirPath, 'package.json'))) { entryPoint = JSON.parse(readFileSync$1(join$3(dirPath, 'package.json'), { encoding: 'utf8' })).main || entryPoint; } } catch (ignored) { // ignored } return entryPoint; } function isDirectory(path) { try { if (statSync$2(path).isDirectory()) return true; } catch (ignored) { // Nothing to do here } return false; } function getDynamicRequireModules(patterns, dynamicRequireRoot) { const dynamicRequireModules = new Map(); const dirNames = new Set(); for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) { const isNegated = pattern.startsWith('!'); const modifyMap = (targetPath, resolvedPath) => isNegated ? dynamicRequireModules.delete(targetPath) : dynamicRequireModules.set(targetPath, resolvedPath); for (const path of glob$1.sync(isNegated ? pattern.substr(1) : pattern)) { const resolvedPath = resolve$5(path); const requirePath = normalizePathSlashes(resolvedPath); if (isDirectory(resolvedPath)) { dirNames.add(resolvedPath); const modulePath = resolve$5(join$3(resolvedPath, getPackageEntryPoint(path))); modifyMap(requirePath, modulePath); modifyMap(normalizePathSlashes(modulePath), modulePath); } else { dirNames.add(dirname$2(resolvedPath)); modifyMap(requirePath, resolvedPath); } } } return { commonDir: dirNames.size ? getCommonDir([...dirNames, dynamicRequireRoot]) : null, dynamicRequireModules }; } const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`; const COMMONJS_REQUIRE_EXPORT = 'commonjsRequire'; const CREATE_COMMONJS_REQUIRE_EXPORT = 'createCommonjsRequire'; function getDynamicModuleRegistry( isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ignoreDynamicRequires ) { if (!isDynamicRequireModulesEnabled) { return `export function ${COMMONJS_REQUIRE_EXPORT}(path) { ${FAILED_REQUIRE_ERROR} }`; } const dynamicModuleImports = [...dynamicRequireModules.values()] .map( (id, index) => `import ${ id.endsWith('.json') ? `json${index}` : `{ __require as require${index} }` } from ${JSON.stringify(id)};` ) .join('\n'); const dynamicModuleProps = [...dynamicRequireModules.keys()] .map( (id, index) => `\t\t${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${ id.endsWith('.json') ? `function () { return json${index}; }` : `require${index}` }` ) .join(',\n'); return `${dynamicModuleImports} var dynamicModules; function getDynamicModules() { return dynamicModules || (dynamicModules = { ${dynamicModuleProps} }); } export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) { function handleRequire(path) { var resolvedPath = commonjsResolve(path, originalModuleDir); if (resolvedPath !== null) { return getDynamicModules()[resolvedPath](); } ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR} } handleRequire.resolve = function (path) { var resolvedPath = commonjsResolve(path, originalModuleDir); if (resolvedPath !== null) { return resolvedPath; } return require.resolve(path); } return handleRequire; } function commonjsResolve (path, originalModuleDir) { var shouldTryNodeModules = isPossibleNodeModulesPath(path); path = normalize(path); var relPath; if (path[0] === '/') { originalModuleDir = ''; } var modules = getDynamicModules(); var checkedExtensions = ['', '.js', '.json']; while (true) { if (!shouldTryNodeModules) { relPath = normalize(originalModuleDir + '/' + path); } else { relPath = normalize(originalModuleDir + '/node_modules/' + path); } if (relPath.endsWith('/..')) { break; // Travelled too far up, avoid infinite loop } for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) { var resolvedPath = relPath + checkedExtensions[extensionIndex]; if (modules[resolvedPath]) { return resolvedPath; } } if (!shouldTryNodeModules) break; var nextDir = normalize(originalModuleDir + '/..'); if (nextDir === originalModuleDir) break; originalModuleDir = nextDir; } return null; } function isPossibleNodeModulesPath (modulePath) { var c0 = modulePath[0]; if (c0 === '/' || c0 === '\\\\') return false; var c1 = modulePath[1], c2 = modulePath[2]; if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) || (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false; if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false; return true; } function normalize (path) { path = path.replace(/\\\\/g, '/'); var parts = path.split('/'); var slashed = parts[0] === ''; for (var i = 1; i < parts.length; i++) { if (parts[i] === '.' || parts[i] === '') { parts.splice(i--, 1); } } for (var i = 1; i < parts.length; i++) { if (parts[i] !== '..') continue; if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') { parts.splice(--i, 2); i--; } } path = parts.join('/'); if (slashed && path[0] !== '/') path = '/' + path; else if (path.length === 0) path = '.'; return path; }`; } const isWrappedId = (id, suffix) => id.endsWith(suffix); const wrapId$1 = (id, suffix) => `\0${id}${suffix}`; const unwrapId$1 = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length); const PROXY_SUFFIX = '?commonjs-proxy'; const WRAPPED_SUFFIX = '?commonjs-wrapped'; const EXTERNAL_SUFFIX = '?commonjs-external'; const EXPORTS_SUFFIX = '?commonjs-exports'; const MODULE_SUFFIX = '?commonjs-module'; const ENTRY_SUFFIX = '?commonjs-entry'; const ES_IMPORT_SUFFIX = '?commonjs-es-import'; const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules'; const HELPERS_ID = '\0commonjsHelpers.js'; const IS_WRAPPED_COMMONJS = 'withRequireFunction'; // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers. // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled. // This could be improved by inspecting Rollup's "generatedCode" option const HELPERS$1 = ` export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; export function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } export function getDefaultExportFromNamespaceIfPresent (n) { return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; } export function getDefaultExportFromNamespaceIfNotNamed (n) { return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; } export function getAugmentedNamespace(n) { if (n.__esModule) return n; var f = n.default; if (typeof f == "function") { var a = function a () { if (this instanceof a) { var args = [null]; args.push.apply(args, arguments); var Ctor = Function.bind.apply(f, args); return new Ctor(); } return f.apply(this, arguments); }; a.prototype = f.prototype; } else a = {}; Object.defineProperty(a, '__esModule', {value: true}); Object.keys(n).forEach(function (k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, get: function () { return n[k]; } }); }); return a; } `; function getHelpersModule() { return HELPERS$1; } function getUnknownRequireProxy(id, requireReturnsDefault) { if (requireReturnsDefault === true || id.endsWith('.json')) { return `export { default } from ${JSON.stringify(id)};`; } const name = getName(id); const exported = requireReturnsDefault === 'auto' ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});` : requireReturnsDefault === 'preferred' ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});` : !requireReturnsDefault ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});` : `export default ${name};`; return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`; } async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) { const name = getName(id); const { meta: { commonjs: commonjsMeta } } = await loadModule({ id }); if (!commonjsMeta) { return getUnknownRequireProxy(id, requireReturnsDefault); } if (commonjsMeta.isCommonJS) { return `export { __moduleExports as default } from ${JSON.stringify(id)};`; } if (!requireReturnsDefault) { return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify( id )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`; } if ( requireReturnsDefault !== true && (requireReturnsDefault === 'namespace' || !commonjsMeta.hasDefaultExport || (requireReturnsDefault === 'auto' && commonjsMeta.hasNamedExports)) ) { return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`; } return `export { default } from ${JSON.stringify(id)};`; } function getEntryProxy(id, defaultIsModuleExports, getModuleInfo) { const { meta: { commonjs: commonjsMeta }, hasDefaultExport } = getModuleInfo(id); if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) { const stringifiedId = JSON.stringify(id); let code = `export * from ${stringifiedId};`; if (hasDefaultExport) { code += `export { default } from ${stringifiedId};`; } return code; } return getEsImportProxy(id, defaultIsModuleExports); } function getEsImportProxy(id, defaultIsModuleExports) { const name = getName(id); const exportsName = `${name}Exports`; const requireModule = `require${capitalize(name)}`; let code = `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\n` + `import { __require as ${requireModule} } from ${JSON.stringify(id)};\n` + `var ${exportsName} = ${requireModule}();\n` + `export { ${exportsName} as __moduleExports };`; if (defaultIsModuleExports === true) { code += `\nexport { ${exportsName} as default };`; } else { code += `export default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`; } return { code, syntheticNamedExports: '__moduleExports' }; } /* eslint-disable no-param-reassign, no-undefined */ function getCandidatesForExtension(resolved, extension) { return [resolved + extension, `${resolved}${sep$2}index${extension}`]; } function getCandidates(resolved, extensions) { return extensions.reduce( (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)), [resolved] ); } function resolveExtensions(importee, importer, extensions) { // not our problem if (importee[0] !== '.' || !importer) return undefined; const resolved = resolve$5(dirname$2(importer), importee); const candidates = getCandidates(resolved, extensions); for (let i = 0; i < candidates.length; i += 1) { try { const stats = statSync$2(candidates[i]); if (stats.isFile()) return { id: candidates[i] }; } catch (err) { /* noop */ } } return undefined; } function getResolveId(extensions, isPossibleCjsId) { const currentlyResolving = new Map(); return { /** * This is a Maps of importers to Sets of require sources being resolved at * the moment by resolveRequireSourcesAndUpdateMeta */ currentlyResolving, async resolveId(importee, importer, resolveOptions) { const customOptions = resolveOptions.custom; // All logic below is specific to ES imports. // Also, if we do not skip this logic for requires that are resolved while // transforming a commonjs file, it can easily lead to deadlocks. if ( customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire ) { return null; } const currentlyResolvingForParent = currentlyResolving.get(importer); if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) { this.warn({ code: 'THIS_RESOLVE_WITHOUT_OPTIONS', message: 'It appears a plugin has implemented a "resolveId" hook that uses "this.resolve" without forwarding the third "options" parameter of "resolveId". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.', url: 'https://rollupjs.org/guide/en/#resolveid' }); return null; } if (isWrappedId(importee, WRAPPED_SUFFIX)) { return unwrapId$1(importee, WRAPPED_SUFFIX); } if ( importee.endsWith(ENTRY_SUFFIX) || isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX) || isWrappedId(importee, PROXY_SUFFIX) || isWrappedId(importee, ES_IMPORT_SUFFIX) || isWrappedId(importee, EXTERNAL_SUFFIX) || importee.startsWith(HELPERS_ID) || importee === DYNAMIC_MODULES_ID ) { return importee; } if (importer) { if ( importer === DYNAMIC_MODULES_ID || // Proxies are only importing resolved ids, no need to resolve again isWrappedId(importer, PROXY_SUFFIX) || isWrappedId(importer, ES_IMPORT_SUFFIX) || importer.endsWith(ENTRY_SUFFIX) ) { return importee; } if (isWrappedId(importer, EXTERNAL_SUFFIX)) { // We need to return null for unresolved imports so that the proper warning is shown if ( !(await this.resolve( importee, importer, Object.assign({ skipSelf: true }, resolveOptions) )) ) { return null; } // For other external imports, we need to make sure they are handled as external return { id: importee, external: true }; } } if (importee.startsWith('\0')) { return null; } // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and // if that is the case, we need to add a proxy. const resolved = (await this.resolve( importee, importer, Object.assign({ skipSelf: true }, resolveOptions) )) || resolveExtensions(importee, importer, extensions); // Make sure that even if other plugins resolve again, we ignore our own proxies if ( !resolved || resolved.external || resolved.id.endsWith(ENTRY_SUFFIX) || isWrappedId(resolved.id, ES_IMPORT_SUFFIX) || !isPossibleCjsId(resolved.id) ) { return resolved; } const moduleInfo = await this.load(resolved); const { meta: { commonjs: commonjsMeta } } = moduleInfo; if (commonjsMeta) { const { isCommonJS } = commonjsMeta; if (isCommonJS) { if (resolveOptions.isEntry) { moduleInfo.moduleSideEffects = true; // We must not precede entry proxies with a `\0` as that will mess up relative external resolution return resolved.id + ENTRY_SUFFIX; } if (isCommonJS === IS_WRAPPED_COMMONJS) { return { id: wrapId$1(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } }; } } } return resolved; } }; } function getRequireResolver(extensions, detectCyclesAndConditional, currentlyResolving) { const knownCjsModuleTypes = Object.create(null); const requiredIds = Object.create(null); const unconditionallyRequiredIds = Object.create(null); const dependencies = Object.create(null); const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set()); const isCyclic = (id) => { const dependenciesToCheck = new Set(getDependencies(id)); for (const dependency of dependenciesToCheck) { if (dependency === id) { return true; } for (const childDependency of getDependencies(dependency)) { dependenciesToCheck.add(childDependency); } } return false; }; // Once a module is listed here, its type (wrapped or not) is fixed and may // not change for the rest of the current build, to not break already // transformed modules. const fullyAnalyzedModules = Object.create(null); const getTypeForFullyAnalyzedModule = (id) => { const knownType = knownCjsModuleTypes[id]; if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) { return knownType; } if (isCyclic(id)) { return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS); } return knownType; }; const setInitialParentType = (id, initialCommonJSType) => { // Fully analyzed modules may never change type if (fullyAnalyzedModules[id]) { return; } knownCjsModuleTypes[id] = initialCommonJSType; if ( detectCyclesAndConditional && knownCjsModuleTypes[id] === true && requiredIds[id] && !unconditionallyRequiredIds[id] ) { knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS; } }; const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => { const childId = resolved.id; requiredIds[childId] = true; if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) { unconditionallyRequiredIds[childId] = true; } getDependencies(parentId).add(childId); if (!isCyclic(childId)) { // This makes sure the current transform handler waits for all direct // dependencies to be loaded and transformed and therefore for all // transitive CommonJS dependencies to be loaded as well so that all // cycles have been found and knownCjsModuleTypes is reliable. await loadModule(resolved); } }; const getTypeForImportedModule = async (resolved, loadModule) => { if (resolved.id in knownCjsModuleTypes) { // This handles cyclic ES dependencies return knownCjsModuleTypes[resolved.id]; } const { meta: { commonjs } } = await loadModule(resolved); return (commonjs && commonjs.isCommonJS) || false; }; return { getWrappedIds: () => Object.keys(knownCjsModuleTypes).filter( (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS ), isRequiredId: (id) => requiredIds[id], async shouldTransformCachedModule({ id: parentId, resolvedSources, meta: { commonjs: parentMeta } }) { // We explicitly track ES modules to handle circular imports if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false; if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false; const parentRequires = parentMeta && parentMeta.requires; if (parentRequires) { setInitialParentType(parentId, parentMeta.initialCommonJSType); await Promise.all( parentRequires.map(({ resolved, isConditional }) => analyzeRequiredModule(parentId, resolved, isConditional, this.load) ) ); if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) { return true; } for (const { resolved: { id } } of parentRequires) { if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) { return true; } } // Now that we decided to go with the cached copy, neither the parent // module nor any of its children may change types anymore fullyAnalyzedModules[parentId] = true; for (const { resolved: { id } } of parentRequires) { fullyAnalyzedModules[id] = true; } } const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id)); return ( await Promise.all( Object.keys(resolvedSources) .map((source) => resolvedSources[source]) .filter(({ id, external }) => !(external || parentRequireSet.has(id))) .map(async (resolved) => { if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) { return ( (await getTypeForImportedModule( ( await this.load({ id: resolved.id }) ).meta.commonjs.resolved, this.load )) !== IS_WRAPPED_COMMONJS ); } return (await getTypeForImportedModule(resolved, this.load)) === IS_WRAPPED_COMMONJS; }) ) ).some((shouldTransform) => shouldTransform); }, /* eslint-disable no-param-reassign */ resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (parentId, isParentCommonJS, parentMeta, sources) => { parentMeta.initialCommonJSType = isParentCommonJS; parentMeta.requires = []; parentMeta.isRequiredCommonJS = Object.create(null); setInitialParentType(parentId, isParentCommonJS); const currentlyResolvingForParent = currentlyResolving.get(parentId) || new Set(); currentlyResolving.set(parentId, currentlyResolvingForParent); const requireTargets = await Promise.all( sources.map(async ({ source, isConditional }) => { // Never analyze or proxy internal modules if (source.startsWith('\0')) { return { id: source, allowProxy: false }; } currentlyResolvingForParent.add(source); const resolved = (await rollupContext.resolve(source, parentId, { custom: { 'node-resolve': { isRequire: true } } })) || resolveExtensions(source, parentId, extensions); currentlyResolvingForParent.delete(source); if (!resolved) { return { id: wrapId$1(source, EXTERNAL_SUFFIX), allowProxy: false }; } const childId = resolved.id; if (resolved.external) { return { id: wrapId$1(childId, EXTERNAL_SUFFIX), allowProxy: false }; } parentMeta.requires.push({ resolved, isConditional }); await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load); return { id: childId, allowProxy: true }; }) ); parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId); fullyAnalyzedModules[parentId] = true; return requireTargets.map(({ id: dependencyId, allowProxy }, index) => { // eslint-disable-next-line no-multi-assign const isCommonJS = (parentMeta.isRequiredCommonJS[dependencyId] = getTypeForFullyAnalyzedModule(dependencyId)); fullyAnalyzedModules[dependencyId] = true; return { source: sources[index].source, id: allowProxy ? isCommonJS === IS_WRAPPED_COMMONJS ? wrapId$1(dependencyId, WRAPPED_SUFFIX) : wrapId$1(dependencyId, PROXY_SUFFIX) : dependencyId, isCommonJS }; }); }, isCurrentlyResolving(source, parentId) { const currentlyResolvingForParent = currentlyResolving.get(parentId); return currentlyResolvingForParent && currentlyResolvingForParent.has(source); } }; } function validateVersion(actualVersion, peerDependencyVersion, name) { const versionRegexp = /\^(\d+\.\d+\.\d+)/g; let minMajor = Infinity; let minMinor = Infinity; let minPatch = Infinity; let foundVersion; // eslint-disable-next-line no-cond-assign while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) { const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number); if (foundMajor < minMajor) { minMajor = foundMajor; minMinor = foundMinor; minPatch = foundPatch; } } if (!actualVersion) { throw new Error( `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.` ); } const [major, minor, patch] = actualVersion.split('.').map(Number); if ( major < minMajor || (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch))) ) { throw new Error( `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.` ); } } const operators = { '==': (x) => equals(x.left, x.right, false), '!=': (x) => not(operators['=='](x)), '===': (x) => equals(x.left, x.right, true), '!==': (x) => not(operators['==='](x)), '!': (x) => isFalsy(x.argument), '&&': (x) => isTruthy(x.left) && isTruthy(x.right), '||': (x) => isTruthy(x.left) || isTruthy(x.right) }; function not(value) { return value === null ? value : !value; } function equals(a, b, strict) { if (a.type !== b.type) return null; // eslint-disable-next-line eqeqeq if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value; return null; } function isTruthy(node) { if (!node) return false; if (node.type === 'Literal') return !!node.value; if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression); if (node.operator in operators) return operators[node.operator](node); return null; } function isFalsy(node) { return not(isTruthy(node)); } function getKeypath(node) { const parts = []; while (node.type === 'MemberExpression') { if (node.computed) return null; parts.unshift(node.property.name); // eslint-disable-next-line no-param-reassign node = node.object; } if (node.type !== 'Identifier') return null; const { name } = node; parts.unshift(name); return { name, keypath: parts.join('.') }; } const KEY_COMPILED_ESM = '__esModule'; function getDefineCompiledEsmType(node) { const definedPropertyWithExports = getDefinePropertyCallName(node, 'exports'); const definedProperty = definedPropertyWithExports || getDefinePropertyCallName(node, 'module.exports'); if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) { return isTruthy(definedProperty.value) ? definedPropertyWithExports ? 'exports' : 'module' : false; } return false; } function getDefinePropertyCallName(node, targetName) { const { callee: { object, property } } = node; if (!object || object.type !== 'Identifier' || object.name !== 'Object') return; if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return; if (node.arguments.length !== 3) return; const targetNames = targetName.split('.'); const [target, key, value] = node.arguments; if (targetNames.length === 1) { if (target.type !== 'Identifier' || target.name !== targetNames[0]) { return; } } if (targetNames.length === 2) { if ( target.type !== 'MemberExpression' || target.object.name !== targetNames[0] || target.property.name !== targetNames[1] ) { return; } } if (value.type !== 'ObjectExpression' || !value.properties) return; const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value'); if (!valueProperty || !valueProperty.value) return; // eslint-disable-next-line consistent-return return { key: key.value, value: valueProperty.value }; } function isShorthandProperty(parent) { return parent && parent.type === 'Property' && parent.shorthand; } function wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges) { const args = []; const passedArgs = []; if (uses.module) { args.push('module'); passedArgs.push(moduleName); } if (uses.exports) { args.push('exports'); passedArgs.push(uses.module ? `${moduleName}.exports` : exportsName); } magicString .trim() .indent('\t', { exclude: indentExclusionRanges }) .prepend(`(function (${args.join(', ')}) {\n`) // For some reason, this line is only indented correctly when using a // require-wrapper if we have this leading space .append(` \n} (${passedArgs.join(', ')}));`); } function rewriteExportsAndGetExportsBlock( magicString, moduleName, exportsName, exportedExportsName, wrapped, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsAssignmentsByName, topLevelAssignments, defineCompiledEsmExpressions, deconflictedExportNames, code, HELPERS_NAME, exportMode, defaultIsModuleExports, usesRequireWrapper, requireName ) { const exports = []; const exportDeclarations = []; if (usesRequireWrapper) { getExportsWhenUsingRequireWrapper( magicString, wrapped, exportMode, exports, moduleExportsAssignments, exportsAssignmentsByName, moduleName, exportsName, requireName, defineCompiledEsmExpressions ); } else if (exportMode === 'replace') { getExportsForReplacedModuleExports( magicString, exports, exportDeclarations, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsName, defaultIsModuleExports, HELPERS_NAME ); } else { if (exportMode === 'module') { exportDeclarations.push(`var ${exportedExportsName} = ${moduleName}.exports`); exports.push(`${exportedExportsName} as __moduleExports`); } else { exports.push(`${exportsName} as __moduleExports`); } if (wrapped) { exportDeclarations.push( getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) ); } else { getExports( magicString, exports, exportDeclarations, moduleExportsAssignments, exportsAssignmentsByName, deconflictedExportNames, topLevelAssignments, moduleName, exportsName, exportedExportsName, defineCompiledEsmExpressions, HELPERS_NAME, defaultIsModuleExports, exportMode ); } } if (exports.length) { exportDeclarations.push(`export { ${exports.join(', ')} }`); } return `\n\n${exportDeclarations.join(';\n')};`; } function getExportsWhenUsingRequireWrapper( magicString, wrapped, exportMode, exports, moduleExportsAssignments, exportsAssignmentsByName, moduleName, exportsName, requireName, defineCompiledEsmExpressions ) { exports.push(`${requireName} as __require`); if (wrapped) return; if (exportMode === 'replace') { rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName); } else { rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, `${moduleName}.exports`); // Collect and rewrite named exports for (const [exportName, { nodes }] of exportsAssignmentsByName) { for (const { node, type } of nodes) { magicString.overwrite( node.start, node.left.end, `${ exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName }.${exportName}` ); } } replaceDefineCompiledEsmExpressionsAndGetIfRestorable( defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName ); } } function getExportsForReplacedModuleExports( magicString, exports, exportDeclarations, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsName, defaultIsModuleExports, HELPERS_NAME ) { for (const { left } of moduleExportsAssignments) { magicString.overwrite(left.start, left.end, exportsName); } magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var '); exports.push(`${exportsName} as __moduleExports`); exportDeclarations.push( getDefaultExportDeclaration(exportsName, defaultIsModuleExports, HELPERS_NAME) ); } function getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) { return `export default ${ defaultIsModuleExports === true ? exportedExportsName : defaultIsModuleExports === false ? `${exportedExportsName}.default` : `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportedExportsName})` }`; } function getExports( magicString, exports, exportDeclarations, moduleExportsAssignments, exportsAssignmentsByName, deconflictedExportNames, topLevelAssignments, moduleName, exportsName, exportedExportsName, defineCompiledEsmExpressions, HELPERS_NAME, defaultIsModuleExports, exportMode ) { let deconflictedDefaultExportName; // Collect and rewrite module.exports assignments for (const { left } of moduleExportsAssignments) { magicString.overwrite(left.start, left.end, `${moduleName}.exports`); } // Collect and rewrite named exports for (const [exportName, { nodes }] of exportsAssignmentsByName) { const deconflicted = deconflictedExportNames[exportName]; let needsDeclaration = true; for (const { node, type } of nodes) { let replacement = `${deconflicted} = ${ exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName }.${exportName}`; if (needsDeclaration && topLevelAssignments.has(node)) { replacement = `var ${replacement}`; needsDeclaration = false; } magicString.overwrite(node.start, node.left.end, replacement); } if (needsDeclaration) { magicString.prepend(`var ${deconflicted};\n`); } if (exportName === 'default') { deconflictedDefaultExportName = deconflicted; } else { exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`); } } const isRestorableCompiledEsm = replaceDefineCompiledEsmExpressionsAndGetIfRestorable( defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName ); if ( defaultIsModuleExports === false || (defaultIsModuleExports === 'auto' && isRestorableCompiledEsm && moduleExportsAssignments.length === 0) ) { // If there is no deconflictedDefaultExportName, then we use the namespace as // fallback because there can be no "default" property on the namespace exports.push(`${deconflictedDefaultExportName || exportedExportsName} as default`); } else if ( defaultIsModuleExports === true || (!isRestorableCompiledEsm && moduleExportsAssignments.length === 0) ) { exports.push(`${exportedExportsName} as default`); } else { exportDeclarations.push( getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) ); } } function rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName) { for (const { left } of moduleExportsAssignments) { magicString.overwrite(left.start, left.end, exportsName); } } function replaceDefineCompiledEsmExpressionsAndGetIfRestorable( defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName ) { let isRestorableCompiledEsm = false; for (const { node, type } of defineCompiledEsmExpressions) { isRestorableCompiledEsm = true; const moduleExportsExpression = node.type === 'CallExpression' ? node.arguments[0] : node.left.object; magicString.overwrite( moduleExportsExpression.start, moduleExportsExpression.end, exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName ); } return isRestorableCompiledEsm; } function isRequireExpression(node, scope) { if (!node) return false; if (node.type !== 'CallExpression') return false; // Weird case of `require()` or `module.require()` without arguments if (node.arguments.length === 0) return false; return isRequire(node.callee, scope); } function isRequire(node, scope) { return ( (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) || (node.type === 'MemberExpression' && isModuleRequire(node, scope)) ); } function isModuleRequire({ object, property }, scope) { return ( object.type === 'Identifier' && object.name === 'module' && property.type === 'Identifier' && property.name === 'require' && !scope.contains('module') ); } function hasDynamicArguments(node) { return ( node.arguments.length > 1 || (node.arguments[0].type !== 'Literal' && (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0)) ); } const reservedMethod = { resolve: true, cache: true, main: true }; function isNodeRequirePropertyAccess(parent) { return parent && parent.property && reservedMethod[parent.property.name]; } function getRequireStringArg(node) { return node.arguments[0].type === 'Literal' ? node.arguments[0].value : node.arguments[0].quasis[0].value.cooked; } function getRequireHandlers() { const requireExpressions = []; function addRequireExpression( sourceId, node, scope, usesReturnValue, isInsideTryBlock, isInsideConditional, toBeRemoved ) { requireExpressions.push({ sourceId, node, scope, usesReturnValue, isInsideTryBlock, isInsideConditional, toBeRemoved }); } async function rewriteRequireExpressionsAndGetImportBlock( magicString, topLevelDeclarations, reassignedNames, helpersName, dynamicRequireName, moduleName, exportsName, id, exportMode, resolveRequireSourcesAndUpdateMeta, needsRequireWrapper, isEsModule, isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, commonjsMeta ) { const imports = []; imports.push(`import * as ${helpersName} from "${HELPERS_ID}"`); if (dynamicRequireName) { imports.push( `import { ${ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}"` ); } if (exportMode === 'module') { imports.push( `import { __module as ${moduleName} } from ${JSON.stringify(wrapId$1(id, MODULE_SUFFIX))}`, `var ${exportsName} = ${moduleName}.exports` ); } else if (exportMode === 'exports') { imports.push( `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId$1(id, EXPORTS_SUFFIX))}` ); } const requiresBySource = collectSources(requireExpressions); const requireTargets = await resolveRequireSourcesAndUpdateMeta( id, needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule, commonjsMeta, Object.keys(requiresBySource).map((source) => { return { source, isConditional: requiresBySource[source].every((require) => require.isInsideConditional) }; }) ); processRequireExpressions( imports, requireTargets, requiresBySource, getIgnoreTryCatchRequireStatementMode, magicString ); return imports.length ? `${imports.join(';\n')};\n\n` : ''; } return { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock }; } function collectSources(requireExpressions) { const requiresBySource = Object.create(null); for (const requireExpression of requireExpressions) { const { sourceId } = requireExpression; if (!requiresBySource[sourceId]) { requiresBySource[sourceId] = []; } const requires = requiresBySource[sourceId]; requires.push(requireExpression); } return requiresBySource; } function processRequireExpressions( imports, requireTargets, requiresBySource, getIgnoreTryCatchRequireStatementMode, magicString ) { const generateRequireName = getGenerateRequireName(); for (const { source, id: resolvedId, isCommonJS } of requireTargets) { const requires = requiresBySource[source]; const name = generateRequireName(requires); let usesRequired = false; let needsImport = false; for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) { const { canConvertRequire, shouldRemoveRequire } = isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX) ? getIgnoreTryCatchRequireStatementMode(source) : { canConvertRequire: true, shouldRemoveRequire: false }; if (shouldRemoveRequire) { if (usesReturnValue) { magicString.overwrite(node.start, node.end, 'undefined'); } else { magicString.remove(toBeRemoved.start, toBeRemoved.end); } } else if (canConvertRequire) { needsImport = true; if (isCommonJS === IS_WRAPPED_COMMONJS) { magicString.overwrite(node.start, node.end, `${name}()`); } else if (usesReturnValue) { usesRequired = true; magicString.overwrite(node.start, node.end, name); } else { magicString.remove(toBeRemoved.start, toBeRemoved.end); } } } if (needsImport) { if (isCommonJS === IS_WRAPPED_COMMONJS) { imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)}`); } else { imports.push(`import ${usesRequired ? `${name} from ` : ''}${JSON.stringify(resolvedId)}`); } } } } function getGenerateRequireName() { let uid = 0; return (requires) => { let name; const hasNameConflict = ({ scope }) => scope.contains(name); do { name = `require$$${uid}`; uid += 1; } while (requires.some(hasNameConflict)); return name; }; } /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */ const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/; const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/; // There are three different types of CommonJS modules, described by their // "exportMode": // - exports: Only assignments to (module.)exports properties // - replace: A single assignment to module.exports itself // - module: Anything else // Special cases: // - usesRequireWrapper // - isWrapped async function transformCommonjs( parse, code, id, isEsModule, ignoreGlobal, ignoreRequire, ignoreDynamicRequires, getIgnoreTryCatchRequireStatementMode, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, astCache, defaultIsModuleExports, needsRequireWrapper, resolveRequireSourcesAndUpdateMeta, isRequired, checkDynamicRequire, commonjsMeta ) { const ast = astCache || tryParse(parse, code, id); const magicString = new MagicString$1(code); const uses = { module: false, exports: false, global: false, require: false }; const virtualDynamicRequirePath = isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname$2(id), commonDir); let scope = attachScopes(ast, 'scope'); let lexicalDepth = 0; let programDepth = 0; let currentTryBlockEnd = null; let shouldWrap = false; const globals = new Set(); // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require // or contains nested requires, those should be handled as function calls unless there is an // unconditional require elsewhere. let currentConditionalNodeEnd = null; const conditionalNodes = new Set(); const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers(); // See which names are assigned to. This is necessary to prevent // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`, // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh) const reassignedNames = new Set(); const topLevelDeclarations = []; const skippedNodes = new Set(); const moduleAccessScopes = new Set([scope]); const exportsAccessScopes = new Set([scope]); const moduleExportsAssignments = []; let firstTopLevelModuleExportsAssignment = null; const exportsAssignmentsByName = new Map(); const topLevelAssignments = new Set(); const topLevelDefineCompiledEsmExpressions = []; const replacedGlobal = []; const replacedDynamicRequires = []; const importedVariables = new Set(); const indentExclusionRanges = []; walk$4(ast, { enter(node, parent) { if (skippedNodes.has(node)) { this.skip(); return; } if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) { currentTryBlockEnd = null; } if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) { currentConditionalNodeEnd = null; } if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) { currentConditionalNodeEnd = node.end; } programDepth += 1; if (node.scope) ({ scope } = node); if (functionType.test(node.type)) lexicalDepth += 1; if (sourceMap) { magicString.addSourcemapLocation(node.start); magicString.addSourcemapLocation(node.end); } // eslint-disable-next-line default-case switch (node.type) { case 'AssignmentExpression': if (node.left.type === 'MemberExpression') { const flattened = getKeypath(node.left); if (!flattened || scope.contains(flattened.name)) return; const exportsPatternMatch = exportsPattern.exec(flattened.keypath); if (!exportsPatternMatch || flattened.keypath === 'exports') return; const [, exportName] = exportsPatternMatch; uses[flattened.name] = true; // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` – if (flattened.keypath === 'module.exports') { moduleExportsAssignments.push(node); if (programDepth > 3) { moduleAccessScopes.add(scope); } else if (!firstTopLevelModuleExportsAssignment) { firstTopLevelModuleExportsAssignment = node; } } else if (exportName === KEY_COMPILED_ESM) { if (programDepth > 3) { shouldWrap = true; } else { // The "type" is either "module" or "exports" to discern // assignments to module.exports vs exports if needed topLevelDefineCompiledEsmExpressions.push({ node, type: flattened.name }); } } else { const exportsAssignments = exportsAssignmentsByName.get(exportName) || { nodes: [], scopes: new Set() }; exportsAssignments.nodes.push({ node, type: flattened.name }); exportsAssignments.scopes.add(scope); exportsAccessScopes.add(scope); exportsAssignmentsByName.set(exportName, exportsAssignments); if (programDepth <= 3) { topLevelAssignments.add(node); } } skippedNodes.add(node.left); } else { for (const name of extractAssignedNames(node.left)) { reassignedNames.add(name); } } return; case 'CallExpression': { const defineCompiledEsmType = getDefineCompiledEsmType(node); if (defineCompiledEsmType) { if (programDepth === 3 && parent.type === 'ExpressionStatement') { // skip special handling for [module.]exports until we know we render this skippedNodes.add(node.arguments[0]); topLevelDefineCompiledEsmExpressions.push({ node, type: defineCompiledEsmType }); } else { shouldWrap = true; } return; } // Transform require.resolve if ( isDynamicRequireModulesEnabled && node.callee.object && isRequire(node.callee.object, scope) && node.callee.property.name === 'resolve' ) { checkDynamicRequire(node.start); uses.require = true; const requireNode = node.callee.object; replacedDynamicRequires.push(requireNode); skippedNodes.add(node.callee); return; } if (!isRequireExpression(node, scope)) { const keypath = getKeypath(node.callee); if (keypath && importedVariables.has(keypath.name)) { // Heuristic to deoptimize requires after a required function has been called currentConditionalNodeEnd = Infinity; } return; } skippedNodes.add(node.callee); uses.require = true; if (hasDynamicArguments(node)) { if (isDynamicRequireModulesEnabled) { checkDynamicRequire(node.start); } if (!ignoreDynamicRequires) { replacedDynamicRequires.push(node.callee); } return; } const requireStringArg = getRequireStringArg(node); if (!ignoreRequire(requireStringArg)) { const usesReturnValue = parent.type !== 'ExpressionStatement'; const toBeRemoved = parent.type === 'ExpressionStatement' && (!currentConditionalNodeEnd || // We should completely remove requires directly in a try-catch // so that Rollup can remove up the try-catch (currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd)) ? parent : node; addRequireExpression( requireStringArg, node, scope, usesReturnValue, currentTryBlockEnd !== null, currentConditionalNodeEnd !== null, toBeRemoved ); if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') { for (const name of extractAssignedNames(parent.id)) { importedVariables.add(name); } } } return; } case 'ConditionalExpression': case 'IfStatement': // skip dead branches if (isFalsy(node.test)) { skippedNodes.add(node.consequent); } else if (isTruthy(node.test)) { if (node.alternate) { skippedNodes.add(node.alternate); } } else { conditionalNodes.add(node.consequent); if (node.alternate) { conditionalNodes.add(node.alternate); } } return; case 'ArrowFunctionExpression': case 'FunctionDeclaration': case 'FunctionExpression': // requires in functions should be conditional unless it is an IIFE if ( currentConditionalNodeEnd === null && !(parent.type === 'CallExpression' && parent.callee === node) ) { currentConditionalNodeEnd = node.end; } return; case 'Identifier': { const { name } = node; if (!isReference(node, parent) || scope.contains(name)) return; switch (name) { case 'require': uses.require = true; if (isNodeRequirePropertyAccess(parent)) { return; } if (!ignoreDynamicRequires) { if (isShorthandProperty(parent)) { magicString.prependRight(node.start, 'require: '); } replacedDynamicRequires.push(node); } return; case 'module': case 'exports': shouldWrap = true; uses[name] = true; return; case 'global': uses.global = true; if (!ignoreGlobal) { replacedGlobal.push(node); } return; case 'define': magicString.overwrite(node.start, node.end, 'undefined', { storeName: true }); return; default: globals.add(name); return; } } case 'LogicalExpression': // skip dead branches if (node.operator === '&&') { if (isFalsy(node.left)) { skippedNodes.add(node.right); } else if (!isTruthy(node.left)) { conditionalNodes.add(node.right); } } else if (node.operator === '||') { if (isTruthy(node.left)) { skippedNodes.add(node.right); } else if (!isFalsy(node.left)) { conditionalNodes.add(node.right); } } return; case 'MemberExpression': if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) { uses.require = true; replacedDynamicRequires.push(node); skippedNodes.add(node.object); skippedNodes.add(node.property); } return; case 'ReturnStatement': // if top-level return, we need to wrap it if (lexicalDepth === 0) { shouldWrap = true; } return; case 'ThisExpression': // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal` if (lexicalDepth === 0) { uses.global = true; if (!ignoreGlobal) { replacedGlobal.push(node); } } return; case 'TryStatement': if (currentTryBlockEnd === null) { currentTryBlockEnd = node.block.end; } if (currentConditionalNodeEnd === null) { currentConditionalNodeEnd = node.end; } return; case 'UnaryExpression': // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151) if (node.operator === 'typeof') { const flattened = getKeypath(node.argument); if (!flattened) return; if (scope.contains(flattened.name)) return; if ( !isEsModule && (flattened.keypath === 'module.exports' || flattened.keypath === 'module' || flattened.keypath === 'exports') ) { magicString.overwrite(node.start, node.end, `'object'`, { storeName: false }); } } return; case 'VariableDeclaration': if (!scope.parent) { topLevelDeclarations.push(node); } return; case 'TemplateElement': if (node.value.raw.includes('\n')) { indentExclusionRanges.push([node.start, node.end]); } } }, leave(node) { programDepth -= 1; if (node.scope) scope = scope.parent; if (functionType.test(node.type)) lexicalDepth -= 1; } }); const nameBase = getName(id); const exportsName = deconflict([...exportsAccessScopes], globals, nameBase); const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`); const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`); const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`); const helpersName = deconflict([scope], globals, 'commonjsHelpers'); const dynamicRequireName = replacedDynamicRequires.length > 0 && deconflict( [scope], globals, isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT ); const deconflictedExportNames = Object.create(null); for (const [exportName, { scopes }] of exportsAssignmentsByName) { deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName); } for (const node of replacedGlobal) { magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, { storeName: true }); } for (const node of replacedDynamicRequires) { magicString.overwrite( node.start, node.end, isDynamicRequireModulesEnabled ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})` : dynamicRequireName, { contentOnly: true, storeName: true } ); } // We cannot wrap ES/mixed modules shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0)); if ( !( shouldWrap || isRequired || needsRequireWrapper || uses.module || uses.exports || uses.require || topLevelDefineCompiledEsmExpressions.length > 0 ) && (ignoreGlobal || !uses.global) ) { return { meta: { commonjs: { isCommonJS: false } } }; } let leadingComment = ''; if (code.startsWith('/*')) { const commentEnd = code.indexOf('*/', 2) + 2; leadingComment = `${code.slice(0, commentEnd)}\n`; magicString.remove(0, commentEnd).trim(); } const exportMode = isEsModule ? 'none' : shouldWrap ? uses.module ? 'module' : 'exports' : firstTopLevelModuleExportsAssignment ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0 ? 'replace' : 'module' : moduleExportsAssignments.length === 0 ? 'exports' : 'module'; const exportedExportsName = exportMode === 'module' ? deconflict([], globals, `${nameBase}Exports`) : exportsName; const importBlock = await rewriteRequireExpressionsAndGetImportBlock( magicString, topLevelDeclarations, reassignedNames, helpersName, dynamicRequireName, moduleName, exportsName, id, exportMode, resolveRequireSourcesAndUpdateMeta, needsRequireWrapper, isEsModule, isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, commonjsMeta ); const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS; const exportBlock = isEsModule ? '' : rewriteExportsAndGetExportsBlock( magicString, moduleName, exportsName, exportedExportsName, shouldWrap, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsAssignmentsByName, topLevelAssignments, topLevelDefineCompiledEsmExpressions, deconflictedExportNames, code, helpersName, exportMode, defaultIsModuleExports, usesRequireWrapper, requireName ); if (shouldWrap) { wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges); } if (usesRequireWrapper) { magicString.trim().indent('\t', { exclude: indentExclusionRanges }); const exported = exportMode === 'module' ? `${moduleName}.exports` : exportsName; magicString.prepend( `var ${isRequiredName}; function ${requireName} () { \tif (${isRequiredName}) return ${exported}; \t${isRequiredName} = 1; ` ).append(` \treturn ${exported}; }`); if (exportMode === 'replace') { magicString.prepend(`var ${exportsName};\n`); } } magicString .trim() .prepend(leadingComment + importBlock) .append(exportBlock); return { code: magicString.toString(), map: sourceMap ? magicString.generateMap() : null, syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports', meta: { commonjs: commonjsMeta } }; } const PLUGIN_NAME = 'commonjs'; function commonjs(options = {}) { const { ignoreGlobal, ignoreDynamicRequires, requireReturnsDefault: requireReturnsDefaultOption, defaultIsModuleExports: defaultIsModuleExportsOption, esmExternals } = options; const extensions = options.extensions || ['.js']; const filter = createFilter$1$1(options.include, options.exclude); const isPossibleCjsId = (id) => { const extName = extname$1(id); return extName === '.cjs' || (extensions.includes(extName) && filter(id)); }; const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options); const getRequireReturnsDefault = typeof requireReturnsDefaultOption === 'function' ? requireReturnsDefaultOption : () => requireReturnsDefaultOption; let esmExternalIds; const isEsmExternal = typeof esmExternals === 'function' ? esmExternals : Array.isArray(esmExternals) ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id)) : () => esmExternals; const getDefaultIsModuleExports = typeof defaultIsModuleExportsOption === 'function' ? defaultIsModuleExportsOption : () => typeof defaultIsModuleExportsOption === 'boolean' ? defaultIsModuleExportsOption : 'auto'; const dynamicRequireRoot = typeof options.dynamicRequireRoot === 'string' ? resolve$5(options.dynamicRequireRoot) : process.cwd(); const { commonDir, dynamicRequireModules } = getDynamicRequireModules( options.dynamicRequireTargets, dynamicRequireRoot ); const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0; const ignoreRequire = typeof options.ignore === 'function' ? options.ignore : Array.isArray(options.ignore) ? (id) => options.ignore.includes(id) : () => false; const getIgnoreTryCatchRequireStatementMode = (id) => { const mode = typeof options.ignoreTryCatch === 'function' ? options.ignoreTryCatch(id) : Array.isArray(options.ignoreTryCatch) ? options.ignoreTryCatch.includes(id) : typeof options.ignoreTryCatch !== 'undefined' ? options.ignoreTryCatch : true; return { canConvertRequire: mode !== 'remove' && mode !== true, shouldRemoveRequire: mode === 'remove' }; }; const { currentlyResolving, resolveId } = getResolveId(extensions, isPossibleCjsId); const sourceMap = options.sourceMap !== false; // Initialized in buildStart let requireResolver; function transformAndCheckExports(code, id) { const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements( this.parse, code, id ); const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {}; if (hasDefaultExport) { commonjsMeta.hasDefaultExport = true; } if (hasNamedExports) { commonjsMeta.hasNamedExports = true; } if ( !dynamicRequireModules.has(normalizePathSlashes(id)) && (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) || (isEsModule && !options.transformMixedEsModules)) ) { commonjsMeta.isCommonJS = false; return { meta: { commonjs: commonjsMeta } }; } const needsRequireWrapper = !isEsModule && (dynamicRequireModules.has(normalizePathSlashes(id)) || strictRequiresFilter(id)); const checkDynamicRequire = (position) => { if (id.indexOf(dynamicRequireRoot) !== 0) { this.error( { code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT', id, dynamicRequireRoot, message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname$2( id )}" or one of its parent directories.` }, position ); } }; return transformCommonjs( this.parse, code, id, isEsModule, ignoreGlobal || isEsModule, ignoreRequire, ignoreDynamicRequires && !isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ast, getDefaultIsModuleExports(id), needsRequireWrapper, requireResolver.resolveRequireSourcesAndUpdateMeta(this), requireResolver.isRequiredId(id), checkDynamicRequire, commonjsMeta ); } return { name: PLUGIN_NAME, version: version$3$1, options(rawOptions) { // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver // do not prevent our plugin from resolving entry points ot proxies. const plugins = Array.isArray(rawOptions.plugins) ? [...rawOptions.plugins] : rawOptions.plugins ? [rawOptions.plugins] : []; plugins.unshift({ name: 'commonjs--resolver', resolveId }); return { ...rawOptions, plugins }; }, buildStart({ plugins }) { validateVersion(this.meta.rollupVersion, peerDependencies$1.rollup, 'rollup'); const nodeResolve = plugins.find(({ name }) => name === 'node-resolve'); if (nodeResolve) { validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve'); } if (options.namedExports != null) { this.warn( 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.' ); } requireResolver = getRequireResolver( extensions, detectCyclesAndConditional, currentlyResolving ); }, buildEnd() { if (options.strictRequires === 'debug') { const wrappedIds = requireResolver.getWrappedIds(); if (wrappedIds.length) { this.warn({ code: 'WRAPPED_IDS', ids: wrappedIds, message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds .map((id) => `\t${JSON.stringify(relative$3(process.cwd(), id))}`) .join(',\n')}\n]` }); } else { this.warn({ code: 'WRAPPED_IDS', ids: wrappedIds, message: 'The commonjs plugin did not wrap any files.' }); } } }, load(id) { if (id === HELPERS_ID) { return getHelpersModule(); } if (isWrappedId(id, MODULE_SUFFIX)) { const name = getName(unwrapId$1(id, MODULE_SUFFIX)); return { code: `var ${name} = {exports: {}}; export {${name} as __module}`, meta: { commonjs: { isCommonJS: false } } }; } if (isWrappedId(id, EXPORTS_SUFFIX)) { const name = getName(unwrapId$1(id, EXPORTS_SUFFIX)); return { code: `var ${name} = {}; export {${name} as __exports}`, meta: { commonjs: { isCommonJS: false } } }; } if (isWrappedId(id, EXTERNAL_SUFFIX)) { const actualId = unwrapId$1(id, EXTERNAL_SUFFIX); return getUnknownRequireProxy( actualId, isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true ); } // entry suffix is just appended to not mess up relative external resolution if (id.endsWith(ENTRY_SUFFIX)) { const acutalId = id.slice(0, -ENTRY_SUFFIX.length); return getEntryProxy(acutalId, getDefaultIsModuleExports(acutalId), this.getModuleInfo); } if (isWrappedId(id, ES_IMPORT_SUFFIX)) { const actualId = unwrapId$1(id, ES_IMPORT_SUFFIX); return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId)); } if (id === DYNAMIC_MODULES_ID) { return getDynamicModuleRegistry( isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ignoreDynamicRequires ); } if (isWrappedId(id, PROXY_SUFFIX)) { const actualId = unwrapId$1(id, PROXY_SUFFIX); return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load); } return null; }, shouldTransformCachedModule(...args) { return requireResolver.shouldTransformCachedModule.call(this, ...args); }, transform(code, id) { if (!isPossibleCjsId(id)) return null; try { return transformAndCheckExports.call(this, code, id); } catch (err) { return this.error(err, err.loc); } } }; } // Matches the scheme of a URL, eg "http://" const schemeRegex = /^[\w+.-]+:\/\//; /** * Matches the parts of a URL: * 1. Scheme, including ":", guaranteed. * 2. User/password, including "@", optional. * 3. Host, guaranteed. * 4. Port, including ":", optional. * 5. Path, including "/", optional. * 6. Query, including "?", optional. * 7. Hash, including "#", optional. */ const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; /** * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). * * 1. Host, optional. * 2. Path, which may include "/", guaranteed. * 3. Query, including "?", optional. * 4. Hash, including "#", optional. */ const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; var UrlType$2; (function (UrlType) { UrlType[UrlType["Empty"] = 1] = "Empty"; UrlType[UrlType["Hash"] = 2] = "Hash"; UrlType[UrlType["Query"] = 3] = "Query"; UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; UrlType[UrlType["Absolute"] = 7] = "Absolute"; })(UrlType$2 || (UrlType$2 = {})); function isAbsoluteUrl(input) { return schemeRegex.test(input); } function isSchemeRelativeUrl(input) { return input.startsWith('//'); } function isAbsolutePath(input) { return input.startsWith('/'); } function isFileUrl(input) { return input.startsWith('file:'); } function isRelative(input) { return /^[.?#]/.test(input); } function parseAbsoluteUrl(input) { const match = urlRegex.exec(input); return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); } function parseFileUrl(input) { const match = fileRegex.exec(input); const path = match[2]; return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); } function makeUrl(scheme, user, host, port, path, query, hash) { return { scheme, user, host, port, path, query, hash, type: UrlType$2.Absolute, }; } function parseUrl$2(input) { if (isSchemeRelativeUrl(input)) { const url = parseAbsoluteUrl('http:' + input); url.scheme = ''; url.type = UrlType$2.SchemeRelative; return url; } if (isAbsolutePath(input)) { const url = parseAbsoluteUrl('http://foo.com' + input); url.scheme = ''; url.host = ''; url.type = UrlType$2.AbsolutePath; return url; } if (isFileUrl(input)) return parseFileUrl(input); if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input); const url = parseAbsoluteUrl('http://foo.com/' + input); url.scheme = ''; url.host = ''; url.type = input ? input.startsWith('?') ? UrlType$2.Query : input.startsWith('#') ? UrlType$2.Hash : UrlType$2.RelativePath : UrlType$2.Empty; return url; } function stripPathFilename(path) { // If a path ends with a parent directory "..", then it's a relative path with excess parent // paths. It's not a file, so we can't strip it. if (path.endsWith('/..')) return path; const index = path.lastIndexOf('/'); return path.slice(0, index + 1); } function mergePaths(url, base) { normalizePath$4(base, base.type); // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative // path). if (url.path === '/') { url.path = base.path; } else { // Resolution happens relative to the base path's directory, not the file. url.path = stripPathFilename(base.path) + url.path; } } /** * The path can have empty directories "//", unneeded parents "foo/..", or current directory * "foo/.". We need to normalize to a standard representation. */ function normalizePath$4(url, type) { const rel = type <= UrlType$2.RelativePath; const pieces = url.path.split('/'); // We need to preserve the first piece always, so that we output a leading slash. The item at // pieces[0] is an empty string. let pointer = 1; // Positive is the number of real directories we've output, used for popping a parent directory. // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". let positive = 0; // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a // real directory, we won't need to append, unless the other conditions happen again. let addTrailingSlash = false; for (let i = 1; i < pieces.length; i++) { const piece = pieces[i]; // An empty directory, could be a trailing slash, or just a double "//" in the path. if (!piece) { addTrailingSlash = true; continue; } // If we encounter a real directory, then we don't need to append anymore. addTrailingSlash = false; // A current directory, which we can always drop. if (piece === '.') continue; // A parent directory, we need to see if there are any real directories we can pop. Else, we // have an excess of parents, and we'll need to keep the "..". if (piece === '..') { if (positive) { addTrailingSlash = true; positive--; pointer--; } else if (rel) { // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute // URL, protocol relative URL, or an absolute path, we don't need to keep excess. pieces[pointer++] = piece; } continue; } // We've encountered a real directory. Move it to the next insertion pointer, which accounts for // any popped or dropped directories. pieces[pointer++] = piece; positive++; } let path = ''; for (let i = 1; i < pointer; i++) { path += '/' + pieces[i]; } if (!path || (addTrailingSlash && !path.endsWith('/..'))) { path += '/'; } url.path = path; } /** * Attempts to resolve `input` URL/path relative to `base`. */ function resolve$2(input, base) { if (!input && !base) return ''; const url = parseUrl$2(input); let inputType = url.type; if (base && inputType !== UrlType$2.Absolute) { const baseUrl = parseUrl$2(base); const baseType = baseUrl.type; switch (inputType) { case UrlType$2.Empty: url.hash = baseUrl.hash; // fall through case UrlType$2.Hash: url.query = baseUrl.query; // fall through case UrlType$2.Query: case UrlType$2.RelativePath: mergePaths(url, baseUrl); // fall through case UrlType$2.AbsolutePath: // The host, user, and port are joined, you can't copy one without the others. url.user = baseUrl.user; url.host = baseUrl.host; url.port = baseUrl.port; // fall through case UrlType$2.SchemeRelative: // The input doesn't have a schema at least, so we need to copy at least that over. url.scheme = baseUrl.scheme; } if (baseType > inputType) inputType = baseType; } normalizePath$4(url, inputType); const queryHash = url.query + url.hash; switch (inputType) { // This is impossible, because of the empty checks at the start of the function. // case UrlType.Empty: case UrlType$2.Hash: case UrlType$2.Query: return queryHash; case UrlType$2.RelativePath: { // The first char is always a "/", and we need it to be relative. const path = url.path.slice(1); if (!path) return queryHash || '.'; if (isRelative(base || input) && !isRelative(path)) { // If base started with a leading ".", or there is no base and input started with a ".", // then we need to ensure that the relative path starts with a ".". We don't know if // relative starts with a "..", though, so check before prepending. return './' + path + queryHash; } return path + queryHash; } case UrlType$2.AbsolutePath: return url.path + queryHash; default: return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; } } function resolve$1(input, base) { // The base is always treated as a directory, if it's not empty. // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 if (base && !base.endsWith('/')) base += '/'; return resolve$2(input, base); } /** * Removes everything after the last "/", but leaves the slash. */ function stripFilename(path) { if (!path) return ''; const index = path.lastIndexOf('/'); return path.slice(0, index + 1); } const COLUMN$1 = 0; const SOURCES_INDEX$1 = 1; const SOURCE_LINE$1 = 2; const SOURCE_COLUMN$1 = 3; const NAMES_INDEX$1 = 4; function maybeSort(mappings, owned) { const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); if (unsortedIndex === mappings.length) return mappings; // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If // not, we do not want to modify the consumer's input array. if (!owned) mappings = mappings.slice(); for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { mappings[i] = sortSegments(mappings[i], owned); } return mappings; } function nextUnsortedSegmentLine(mappings, start) { for (let i = start; i < mappings.length; i++) { if (!isSorted(mappings[i])) return i; } return mappings.length; } function isSorted(line) { for (let j = 1; j < line.length; j++) { if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) { return false; } } return true; } function sortSegments(line, owned) { if (!owned) line = line.slice(); return line.sort(sortComparator); } function sortComparator(a, b) { return a[COLUMN$1] - b[COLUMN$1]; } let found = false; /** * A binary search implementation that returns the index if a match is found. * If no match is found, then the left-index (the index associated with the item that comes just * before the desired index) is returned. To maintain proper sort order, a splice would happen at * the next index: * * ```js * const array = [1, 3]; * const needle = 2; * const index = binarySearch(array, needle, (item, needle) => item - needle); * * assert.equal(index, 0); * array.splice(index + 1, 0, needle); * assert.deepEqual(array, [1, 2, 3]); * ``` */ function binarySearch(haystack, needle, low, high) { while (low <= high) { const mid = low + ((high - low) >> 1); const cmp = haystack[mid][COLUMN$1] - needle; if (cmp === 0) { found = true; return mid; } if (cmp < 0) { low = mid + 1; } else { high = mid - 1; } } found = false; return low - 1; } function upperBound(haystack, needle, index) { for (let i = index + 1; i < haystack.length; index = i++) { if (haystack[i][COLUMN$1] !== needle) break; } return index; } function lowerBound(haystack, needle, index) { for (let i = index - 1; i >= 0; index = i--) { if (haystack[i][COLUMN$1] !== needle) break; } return index; } function memoizedState() { return { lastKey: -1, lastNeedle: -1, lastIndex: -1, }; } /** * This overly complicated beast is just to record the last tested line/column and the resulting * index, allowing us to skip a few tests if mappings are monotonically increasing. */ function memoizedBinarySearch(haystack, needle, state, key) { const { lastKey, lastNeedle, lastIndex } = state; let low = 0; let high = haystack.length - 1; if (key === lastKey) { if (needle === lastNeedle) { found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle; return lastIndex; } if (needle >= lastNeedle) { // lastIndex may be -1 if the previous needle was not found. low = lastIndex === -1 ? 0 : lastIndex; } else { high = lastIndex; } } state.lastKey = key; state.lastNeedle = needle; return (state.lastIndex = binarySearch(haystack, needle, low, high)); } const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; const LEAST_UPPER_BOUND = -1; const GREATEST_LOWER_BOUND = 1; /** * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. */ let decodedMappings; /** * A low-level API to find the segment associated with a generated line/column (think, from a * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. */ let traceSegment; /** * A higher-level API to find the source/line/column associated with a generated line/column * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in * `source-map` library. */ let originalPositionFor$1; class TraceMap { constructor(map, mapUrl) { const isString = typeof map === 'string'; if (!isString && map._decodedMemo) return map; const parsed = (isString ? JSON.parse(map) : map); const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; this.version = version; this.file = file; this.names = names; this.sourceRoot = sourceRoot; this.sources = sources; this.sourcesContent = sourcesContent; const from = resolve$1(sourceRoot || '', stripFilename(mapUrl)); this.resolvedSources = sources.map((s) => resolve$1(s || '', from)); const { mappings } = parsed; if (typeof mappings === 'string') { this._encoded = mappings; this._decoded = undefined; } else { this._encoded = undefined; this._decoded = maybeSort(mappings, isString); } this._decodedMemo = memoizedState(); this._bySources = undefined; this._bySourceMemos = undefined; } } (() => { decodedMappings = (map) => { return (map._decoded || (map._decoded = decode(map._encoded))); }; traceSegment = (map, line, column) => { const decoded = decodedMappings(map); // It's common for parent source maps to have pointers to lines that have no // mapping (like a "//# sourceMappingURL=") at the end of the child file. if (line >= decoded.length) return null; const segments = decoded[line]; const index = traceSegmentInternal(segments, map._decodedMemo, line, column, GREATEST_LOWER_BOUND); return index === -1 ? null : segments[index]; }; originalPositionFor$1 = (map, { line, column, bias }) => { line--; if (line < 0) throw new Error(LINE_GTR_ZERO); if (column < 0) throw new Error(COL_GTR_EQ_ZERO); const decoded = decodedMappings(map); // It's common for parent source maps to have pointers to lines that have no // mapping (like a "//# sourceMappingURL=") at the end of the child file. if (line >= decoded.length) return OMapping(null, null, null, null); const segments = decoded[line]; const index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); if (index === -1) return OMapping(null, null, null, null); const segment = segments[index]; if (segment.length === 1) return OMapping(null, null, null, null); const { names, resolvedSources } = map; return OMapping(resolvedSources[segment[SOURCES_INDEX$1]], segment[SOURCE_LINE$1] + 1, segment[SOURCE_COLUMN$1], segment.length === 5 ? names[segment[NAMES_INDEX$1]] : null); }; })(); function OMapping(source, line, column, name) { return { source, line, column, name }; } function traceSegmentInternal(segments, memo, line, column, bias) { let index = memoizedBinarySearch(segments, column, memo, line); if (found) { index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); } else if (bias === LEAST_UPPER_BOUND) index++; if (index === -1 || index === segments.length) return -1; return index; } /** * Gets the index associated with `key` in the backing array, if it is already present. */ let get$1; /** * Puts `key` into the backing array, if it is not already present. Returns * the index of the `key` in the backing array. */ let put$1; /** * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the * index of the `key` in the backing array. * * This is designed to allow synchronizing a second array with the contents of the backing array, * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, * and there are never duplicates. */ let SetArray$1 = class SetArray { constructor() { this._indexes = { __proto__: null }; this.array = []; } }; (() => { get$1 = (strarr, key) => strarr._indexes[key]; put$1 = (strarr, key) => { // The key may or may not be present. If it is present, it's a number. const index = get$1(strarr, key); if (index !== undefined) return index; const { array, _indexes: indexes } = strarr; return (indexes[key] = array.push(key) - 1); }; })(); const COLUMN$2 = 0; const SOURCES_INDEX$2 = 1; const SOURCE_LINE$2 = 2; const SOURCE_COLUMN$2 = 3; const NAMES_INDEX$2 = 4; const NO_NAME$1 = -1; /** * Same as `addSegment`, but will only add the segment if it generates useful information in the * resulting map. This only works correctly if segments are added **in order**, meaning you should * not add a segment with a lower generated line/column than one that came before. */ let maybeAddSegment$1; /** * Adds/removes the content of the source file to the source map. */ let setSourceContent; /** * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects * a sourcemap, or to JSON.stringify. */ let toDecodedMap$1; /** * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects * a sourcemap, or to JSON.stringify. */ let toEncodedMap$1; // This split declaration is only so that terser can elminiate the static initialization block. let addSegmentInternal$1; /** * Provides the state to generate a sourcemap. */ let GenMapping$1 = class GenMapping { constructor({ file, sourceRoot } = {}) { this._names = new SetArray$1(); this._sources = new SetArray$1(); this._sourcesContent = []; this._mappings = []; this.file = file; this.sourceRoot = sourceRoot; } }; (() => { maybeAddSegment$1 = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { return addSegmentInternal$1(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); }; setSourceContent = (map, source, content) => { const { _sources: sources, _sourcesContent: sourcesContent } = map; sourcesContent[put$1(sources, source)] = content; }; toDecodedMap$1 = (map) => { const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; removeEmptyFinalLines$1(mappings); return { version: 3, file: file || undefined, names: names.array, sourceRoot: sourceRoot || undefined, sources: sources.array, sourcesContent, mappings, }; }; toEncodedMap$1 = (map) => { const decoded = toDecodedMap$1(map); return Object.assign(Object.assign({}, decoded), { mappings: encode$1(decoded.mappings) }); }; // Internal helpers addSegmentInternal$1 = (skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; const line = getLine$1(mappings, genLine); const index = getColumnIndex$1(line, genColumn); if (!source) { if (skipable && skipSourceless$1(line, index)) return; return insert$1(line, index, [genColumn]); } const sourcesIndex = put$1(sources, source); const namesIndex = name ? put$1(names, name) : NO_NAME$1; if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null; if (skipable && skipSource$1(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { return; } return insert$1(line, index, name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] : [genColumn, sourcesIndex, sourceLine, sourceColumn]); }; })(); function getLine$1(mappings, index) { for (let i = mappings.length; i <= index; i++) { mappings[i] = []; } return mappings[index]; } function getColumnIndex$1(line, genColumn) { let index = line.length; for (let i = index - 1; i >= 0; index = i--) { const current = line[i]; if (genColumn >= current[COLUMN$2]) break; } return index; } function insert$1(array, index, value) { for (let i = array.length; i > index; i--) { array[i] = array[i - 1]; } array[index] = value; } function removeEmptyFinalLines$1(mappings) { const { length } = mappings; let len = length; for (let i = len - 1; i >= 0; len = i, i--) { if (mappings[i].length > 0) break; } if (len < length) mappings.length = len; } function skipSourceless$1(line, index) { // The start of a line is already sourceless, so adding a sourceless segment to the beginning // doesn't generate any useful information. if (index === 0) return true; const prev = line[index - 1]; // If the previous segment is also sourceless, then adding another sourceless segment doesn't // genrate any new information. Else, this segment will end the source/named segment and point to // a sourceless position, which is useful. return prev.length === 1; } function skipSource$1(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { // A source/named segment at the start of a line gives position at that genColumn if (index === 0) return false; const prev = line[index - 1]; // If the previous segment is sourceless, then we're transitioning to a source. if (prev.length === 1) return false; // If the previous segment maps to the exact same source position, then this segment doesn't // provide any new position information. return (sourcesIndex === prev[SOURCES_INDEX$2] && sourceLine === prev[SOURCE_LINE$2] && sourceColumn === prev[SOURCE_COLUMN$2] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX$2] : NO_NAME$1)); } const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null); const EMPTY_SOURCES = []; function SegmentObject(source, line, column, name, content) { return { source, line, column, name, content }; } function Source(map, sources, source, content) { return { map, sources, source, content, }; } /** * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes * (which may themselves be SourceMapTrees). */ function MapSource(map, sources) { return Source(map, sources, '', null); } /** * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive * segment tracing ends at the `OriginalSource`. */ function OriginalSource(source, content) { return Source(null, EMPTY_SOURCES, source, content); } /** * traceMappings is only called on the root level SourceMapTree, and begins the process of * resolving each mapping in terms of the original source files. */ function traceMappings(tree) { // TODO: Eventually support sourceRoot, which has to be removed because the sources are already // fully resolved. We'll need to make sources relative to the sourceRoot before adding them. const gen = new GenMapping$1({ file: tree.map.file }); const { sources: rootSources, map } = tree; const rootNames = map.names; const rootMappings = decodedMappings(map); for (let i = 0; i < rootMappings.length; i++) { const segments = rootMappings[i]; for (let j = 0; j < segments.length; j++) { const segment = segments[j]; const genCol = segment[0]; let traced = SOURCELESS_MAPPING; // 1-length segments only move the current generated column, there's no source information // to gather from it. if (segment.length !== 1) { const source = rootSources[segment[1]]; traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a // respective segment into an original source. if (traced == null) continue; } const { column, line, name, content, source } = traced; maybeAddSegment$1(gen, i, genCol, source, line, column, name); if (source && content != null) setSourceContent(gen, source, content); } } return gen; } /** * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own * child SourceMapTrees, until we find the original source map. */ function originalPositionFor(source, line, column, name) { if (!source.map) { return SegmentObject(source.source, line, column, name, source.content); } const segment = traceSegment(source.map, line, column); // If we couldn't find a segment, then this doesn't exist in the sourcemap. if (segment == null) return null; // 1-length segments only move the current generated column, there's no source information // to gather from it. if (segment.length === 1) return SOURCELESS_MAPPING; return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); } function asArray(value) { if (Array.isArray(value)) return value; return [value]; } /** * Recursively builds a tree structure out of sourcemap files, with each node * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of * `OriginalSource`s and `SourceMapTree`s. * * Every sourcemap is composed of a collection of source files and mappings * into locations of those source files. When we generate a `SourceMapTree` for * the sourcemap, we attempt to load each source file's own sourcemap. If it * does not have an associated sourcemap, it is considered an original, * unmodified source file. */ function buildSourceMapTree(input, loader) { const maps = asArray(input).map((m) => new TraceMap(m, '')); const map = maps.pop(); for (let i = 0; i < maps.length; i++) { if (maps[i].sources.length > 1) { throw new Error(`Transformation map ${i} must have exactly one source file.\n` + 'Did you specify these with the most recent transformation maps first?'); } } let tree = build$2(map, loader, '', 0); for (let i = maps.length - 1; i >= 0; i--) { tree = MapSource(maps[i], [tree]); } return tree; } function build$2(map, loader, importer, importerDepth) { const { resolvedSources, sourcesContent } = map; const depth = importerDepth + 1; const children = resolvedSources.map((sourceFile, i) => { // The loading context gives the loader more information about why this file is being loaded // (eg, from which importer). It also allows the loader to override the location of the loaded // sourcemap/original source, or to override the content in the sourcesContent field if it's // an unmodified source file. const ctx = { importer, depth, source: sourceFile || '', content: undefined, }; // Use the provided loader callback to retrieve the file's sourcemap. // TODO: We should eventually support async loading of sourcemap files. const sourceMap = loader(ctx.source, ctx); const { source, content } = ctx; // If there is a sourcemap, then we need to recurse into it to load its source files. if (sourceMap) return build$2(new TraceMap(sourceMap, source), loader, source, depth); // Else, it's an an unmodified source file. // The contents of this unmodified source file can be overridden via the loader context, // allowing it to be explicitly null or a string. If it remains undefined, we fall back to // the importing sourcemap's `sourcesContent` field. const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; return OriginalSource(source, sourceContent); }); return MapSource(map, children); } /** * A SourceMap v3 compatible sourcemap, which only includes fields that were * provided to it. */ let SourceMap$1 = class SourceMap { constructor(map, options) { const out = options.decodedMappings ? toDecodedMap$1(map) : toEncodedMap$1(map); this.version = out.version; // SourceMap spec says this should be first. this.file = out.file; this.mappings = out.mappings; this.names = out.names; this.sourceRoot = out.sourceRoot; this.sources = out.sources; if (!options.excludeContent) { this.sourcesContent = out.sourcesContent; } } toString() { return JSON.stringify(this); } }; /** * Traces through all the mappings in the root sourcemap, through the sources * (and their sourcemaps), all the way back to the original source location. * * `loader` will be called every time we encounter a source file. If it returns * a sourcemap, we will recurse into that sourcemap to continue the trace. If * it returns a falsey value, that source file is treated as an original, * unmodified source file. * * Pass `excludeContent` to exclude any self-containing source file content * from the output sourcemap. * * Pass `decodedMappings` to receive a SourceMap with decoded (instead of * VLQ encoded) mappings. */ function remapping(input, loader, options) { const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; const tree = buildSourceMapTree(input, loader); return new SourceMap$1(traceMappings(tree), opts); } var src$2$1 = {exports: {}}; var browser$2$1 = {exports: {}}; /** * Helpers. */ var ms$1$1; var hasRequiredMs$1$1; function requireMs$1$1 () { if (hasRequiredMs$1$1) return ms$1$1; hasRequiredMs$1$1 = 1; var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ ms$1$1 = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + 'd'; } if (msAbs >= h) { return Math.round(ms / h) + 'h'; } if (msAbs >= m) { return Math.round(ms / m) + 'm'; } if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, 'day'); } if (msAbs >= h) { return plural(ms, msAbs, h, 'hour'); } if (msAbs >= m) { return plural(ms, msAbs, m, 'minute'); } if (msAbs >= s) { return plural(ms, msAbs, s, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } return ms$1$1; } var common$b$1; var hasRequiredCommon$2; function requireCommon$2 () { if (hasRequiredCommon$2) return common$b$1; hasRequiredCommon$2 = 1; /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = requireMs$1$1(); createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; let i; const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); const len = split.length; for (i = 0; i < len; i++) { if (!split[i]) { // ignore empty strings continue; } namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } let i; let len; for (i = 0, len = createDebug.skips.length; i < len; i++) { if (createDebug.skips[i].test(name)) { return false; } } for (i = 0, len = createDebug.names.length; i < len; i++) { if (createDebug.names[i].test(name)) { return true; } } return false; } /** * Convert regexp to namespace * * @param {RegExp} regxep * @return {String} namespace * @api private */ function toNamespace(regexp) { return regexp.toString() .substring(2, regexp.toString().length - 2) .replace(/\.\*\?$/, '*'); } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } common$b$1 = setup; return common$b$1; } /* eslint-env browser */ var hasRequiredBrowser$1$1; function requireBrowser$1$1 () { if (hasRequiredBrowser$1$1) return browser$2$1.exports; hasRequiredBrowser$1$1 = 1; (function (module, exports) { /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = requireCommon$2()(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; } (browser$2$1, browser$2$1.exports)); return browser$2$1.exports; } var node$1$1 = {exports: {}}; /** * Module dependencies. */ var hasRequiredNode$1$1; function requireNode$1$1 () { if (hasRequiredNode$1$1) return node$1$1.exports; hasRequiredNode$1$1 = 1; (function (module, exports) { const tty = require$$0$3__default; const util = require$$0$6; /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.destroy = util.deprecate( () => {}, 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' ); /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = require$2('supports-color'); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.format()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util.format(...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = requireCommon$2()(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; } (node$1$1, node$1$1.exports)); return node$1$1.exports; } /** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { src$2$1.exports = requireBrowser$1$1(); } else { src$2$1.exports = requireNode$1$1(); } var srcExports$1$1 = src$2$1.exports; var debug$g$1 = /*@__PURE__*/getDefaultExportFromCjs$2(srcExports$1$1); // eslint-disable-next-line @typescript-eslint/consistent-type-imports let pnp$2; if (process.versions.pnp) { try { pnp$2 = createRequire$1(import.meta.url)('pnpapi'); } catch { } } function invalidatePackageData(packageCache, pkgPath) { const pkgDir = path$o$1.dirname(pkgPath); packageCache.forEach((pkg, cacheKey) => { if (pkg.dir === pkgDir) { packageCache.delete(cacheKey); } }); } function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) { if (pnp$2) { const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks); if (packageCache?.has(cacheKey)) return packageCache.get(cacheKey); try { const pkg = pnp$2.resolveToUnqualified(pkgName, basedir, { considerBuiltins: false, }); if (!pkg) return null; const pkgData = loadPackageData(path$o$1.join(pkg, 'package.json')); packageCache?.set(cacheKey, pkgData); return pkgData; } catch { return null; } } const originalBasedir = basedir; while (basedir) { if (packageCache) { const cached = getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks); if (cached) return cached; } const pkg = path$o$1.join(basedir, 'node_modules', pkgName, 'package.json'); try { if (fs$l__default.existsSync(pkg)) { const pkgPath = preserveSymlinks ? pkg : safeRealpathSync(pkg); const pkgData = loadPackageData(pkgPath); if (packageCache) { setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks); } return pkgData; } } catch { } const nextBasedir = path$o$1.dirname(basedir); if (nextBasedir === basedir) break; basedir = nextBasedir; } return null; } function findNearestPackageData(basedir, packageCache) { const originalBasedir = basedir; while (basedir) { if (packageCache) { const cached = getFnpdCache(packageCache, basedir, originalBasedir); if (cached) return cached; } const pkgPath = path$o$1.join(basedir, 'package.json'); try { if (fs$l__default.statSync(pkgPath, { throwIfNoEntry: false })?.isFile()) { const pkgData = loadPackageData(pkgPath); if (packageCache) { setFnpdCache(packageCache, pkgData, basedir, originalBasedir); } return pkgData; } } catch { } const nextBasedir = path$o$1.dirname(basedir); if (nextBasedir === basedir) break; basedir = nextBasedir; } return null; } // Finds the nearest package.json with a `name` field function findNearestMainPackageData(basedir, packageCache) { const nearestPackage = findNearestPackageData(basedir, packageCache); return (nearestPackage && (nearestPackage.data.name ? nearestPackage : findNearestMainPackageData(path$o$1.dirname(nearestPackage.dir), packageCache))); } function loadPackageData(pkgPath) { const data = JSON.parse(fs$l__default.readFileSync(pkgPath, 'utf-8')); const pkgDir = path$o$1.dirname(pkgPath); const { sideEffects } = data; let hasSideEffects; if (typeof sideEffects === 'boolean') { hasSideEffects = () => sideEffects; } else if (Array.isArray(sideEffects)) { const finalPackageSideEffects = sideEffects.map((sideEffect) => { /* * The array accepts simple glob patterns to the relevant files... Patterns like *.css, which do not include a /, will be treated like **\/*.css. * https://webpack.js.org/guides/tree-shaking/ * https://github.com/vitejs/vite/pull/11807 */ if (sideEffect.includes('/')) { return sideEffect; } return `**/${sideEffect}`; }); hasSideEffects = createFilter$3(finalPackageSideEffects, null, { resolve: pkgDir, }); } else { hasSideEffects = () => true; } const pkg = { dir: pkgDir, data, hasSideEffects, webResolvedImports: {}, nodeResolvedImports: {}, setResolvedCache(key, entry, targetWeb) { if (targetWeb) { pkg.webResolvedImports[key] = entry; } else { pkg.nodeResolvedImports[key] = entry; } }, getResolvedCache(key, targetWeb) { if (targetWeb) { return pkg.webResolvedImports[key]; } else { return pkg.nodeResolvedImports[key]; } }, }; return pkg; } function watchPackageDataPlugin(packageCache) { // a list of files to watch before the plugin is ready const watchQueue = new Set(); const watchedDirs = new Set(); const watchFileStub = (id) => { watchQueue.add(id); }; let watchFile = watchFileStub; const setPackageData = packageCache.set.bind(packageCache); packageCache.set = (id, pkg) => { if (!isInNodeModules(pkg.dir) && !watchedDirs.has(pkg.dir)) { watchedDirs.add(pkg.dir); watchFile(path$o$1.join(pkg.dir, 'package.json')); } return setPackageData(id, pkg); }; return { name: 'vite:watch-package-data', buildStart() { watchFile = this.addWatchFile.bind(this); watchQueue.forEach(watchFile); watchQueue.clear(); }, buildEnd() { watchFile = watchFileStub; }, watchChange(id) { if (id.endsWith('/package.json')) { invalidatePackageData(packageCache, path$o$1.normalize(id)); } }, handleHotUpdate({ file }) { if (file.endsWith('/package.json')) { invalidatePackageData(packageCache, path$o$1.normalize(file)); } }, }; } /** * Get cached `resolvePackageData` value based on `basedir`. When one is found, * and we've already traversed some directories between `basedir` and `originalBasedir`, * we cache the value for those in-between directories as well. * * This makes it so the fs is only read once for a shared `basedir`. */ function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) { const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks); const pkgData = packageCache.get(cacheKey); if (pkgData) { traverseBetweenDirs(originalBasedir, basedir, (dir) => { packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData); }); return pkgData; } } function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) { packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData); traverseBetweenDirs(originalBasedir, basedir, (dir) => { packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData); }); } // package cache key for `resolvePackageData` function getRpdCacheKey(pkgName, basedir, preserveSymlinks) { return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`; } /** * Get cached `findNearestPackageData` value based on `basedir`. When one is found, * and we've already traversed some directories between `basedir` and `originalBasedir`, * we cache the value for those in-between directories as well. * * This makes it so the fs is only read once for a shared `basedir`. */ function getFnpdCache(packageCache, basedir, originalBasedir) { const cacheKey = getFnpdCacheKey(basedir); const pkgData = packageCache.get(cacheKey); if (pkgData) { traverseBetweenDirs(originalBasedir, basedir, (dir) => { packageCache.set(getFnpdCacheKey(dir), pkgData); }); return pkgData; } } function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) { packageCache.set(getFnpdCacheKey(basedir), pkgData); traverseBetweenDirs(originalBasedir, basedir, (dir) => { packageCache.set(getFnpdCacheKey(dir), pkgData); }); } // package cache key for `findNearestPackageData` function getFnpdCacheKey(basedir) { return `fnpd_${basedir}`; } /** * Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir. * @param longerDir Longer dir path, e.g. `/User/foo/bar/baz` * @param shorterDir Shorter dir path, e.g. `/User/foo` */ function traverseBetweenDirs(longerDir, shorterDir, cb) { while (longerDir !== shorterDir) { cb(longerDir); longerDir = path$o$1.dirname(longerDir); } } const createFilter$3 = createFilter$1$1; const windowsSlashRE$1 = /\\/g; function slash$1$1(p) { return p.replace(windowsSlashRE$1, '/'); } /** * Prepend `/@id/` and replace null byte so the id is URL-safe. * This is prepended to resolved ids that are not valid browser * import specifiers by the importAnalysis plugin. */ function wrapId(id) { return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace('\0', NULL_BYTE_PLACEHOLDER); } /** * Undo {@link wrapId}'s `/@id/` and null byte replacements. */ function unwrapId(id) { return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, '\0') : id; } const replaceSlashOrColonRE = /[/:]/g; const replaceDotRE = /\./g; const replaceNestedIdRE = /(\s*>\s*)/g; const replaceHashRE = /#/g; const flattenId = (id) => id .replace(replaceSlashOrColonRE, '_') .replace(replaceDotRE, '__') .replace(replaceNestedIdRE, '___') .replace(replaceHashRE, '____'); const normalizeId = (id) => id.replace(replaceNestedIdRE, ' > '); //TODO: revisit later to see if the edge case that "compiling using node v12 code to be run in node v16 in the server" is what we intend to support. const builtins$3 = new Set([ ...builtinModules$1, 'assert/strict', 'diagnostics_channel', 'dns/promises', 'fs/promises', 'path/posix', 'path/win32', 'readline/promises', 'stream/consumers', 'stream/promises', 'stream/web', 'timers/promises', 'util/types', 'wasi', ]); const NODE_BUILTIN_NAMESPACE = 'node:'; function isBuiltin(id) { return builtins$3.has(id.startsWith(NODE_BUILTIN_NAMESPACE) ? id.slice(NODE_BUILTIN_NAMESPACE.length) : id); } function isInNodeModules(id) { return id.includes('node_modules'); } function moduleListContains(moduleList, id) { return moduleList?.some((m) => m === id || id.startsWith(m + '/')); } function isOptimizable(id, optimizeDeps) { const { extensions } = optimizeDeps; return (OPTIMIZABLE_ENTRY_RE.test(id) || (extensions?.some((ext) => id.endsWith(ext)) ?? false)); } const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/; const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//; // TODO: use import() const _require$3$1 = createRequire$1(import.meta.url); // set in bin/vite.js const filter$2 = process.env.VITE_DEBUG_FILTER; const DEBUG$2 = process.env.DEBUG; function createDebugger$1(namespace, options = {}) { const log = debug$g$1(namespace); const { onlyWhenFocused } = options; let enabled = log.enabled; if (enabled && onlyWhenFocused) { const ns = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace; enabled = !!DEBUG$2?.includes(ns); } if (enabled) { return (...args) => { if (!filter$2 || args.some((a) => a?.includes?.(filter$2))) { log(...args); } }; } } function testCaseInsensitiveFS$1() { if (!CLIENT_ENTRY$1.endsWith('client.mjs')) { throw new Error(`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`); } if (!fs$l__default.existsSync(CLIENT_ENTRY$1)) { throw new Error('cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: ' + CLIENT_ENTRY$1); } return fs$l__default.existsSync(CLIENT_ENTRY$1.replace('client.mjs', 'cLiEnT.mjs')); } function isUrl(path) { try { new URL$3(path); return true; } catch { return false; } } const isCaseInsensitiveFS = testCaseInsensitiveFS$1(); const isWindows$4$1 = os$3$1.platform() === 'win32'; const VOLUME_RE = /^[A-Z]:/i; function normalizePath$3$1(id) { return path$o$1.posix.normalize(isWindows$4$1 ? slash$1$1(id) : id); } function fsPathFromId(id) { const fsPath = normalizePath$3$1(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id); return fsPath[0] === '/' || fsPath.match(VOLUME_RE) ? fsPath : `/${fsPath}`; } function fsPathFromUrl(url) { return fsPathFromId(cleanUrl$1(url)); } /** * Check if dir is a parent of file * * Warning: parameters are not validated, only works with normalized absolute paths * * @param dir - normalized absolute path * @param file - normalized absolute path * @returns true if dir is a parent of file */ function isParentDirectory(dir, file) { if (dir[dir.length - 1] !== '/') { dir = `${dir}/`; } return (file.startsWith(dir) || (isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase()))); } const queryRE = /\?.*$/s; const postfixRE$1 = /[?#].*$/s; function cleanUrl$1(url) { return url.replace(postfixRE$1, ''); } const externalRE = /^(https?:)?\/\//; const isExternalUrl = (url) => externalRE.test(url); const dataUrlRE = /^\s*data:/i; const isDataUrl = (url) => dataUrlRE.test(url); const virtualModuleRE = /^virtual-module:.*/; const virtualModulePrefix = 'virtual-module:'; const knownJsSrcRE = /\.(?:[jt]sx?|m[jt]s|vue|marko|svelte|astro|imba)(?:$|\?)/; const isJSRequest = (url) => { url = cleanUrl$1(url); if (knownJsSrcRE.test(url)) { return true; } if (!path$o$1.extname(url) && url[url.length - 1] !== '/') { return true; } return false; }; const knownTsRE = /\.(?:ts|mts|cts|tsx)(?:$|\?)/; const isTsRequest = (url) => knownTsRE.test(url); const importQueryRE = /(\?|&)import=?(?:&|$)/; const directRequestRE$1 = /(\?|&)direct=?(?:&|$)/; const internalPrefixes = [ FS_PREFIX, VALID_ID_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, ]; const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`); const trailingSeparatorRE = /[?&]$/; const isImportRequest = (url) => importQueryRE.test(url); const isInternalRequest = (url) => InternalPrefixRE.test(url); function removeImportQuery(url) { return url.replace(importQueryRE, '$1').replace(trailingSeparatorRE, ''); } function removeDirectQuery(url) { return url.replace(directRequestRE$1, '$1').replace(trailingSeparatorRE, ''); } const replacePercentageRE = /%/g; function injectQuery(url, queryToInject) { // encode percents for consistent behavior with pathToFileURL // see #2614 for details const resolvedUrl = new URL$3(url.replace(replacePercentageRE, '%25'), 'relative:///'); const { search, hash } = resolvedUrl; let pathname = cleanUrl$1(url); pathname = isWindows$4$1 ? slash$1$1(pathname) : pathname; return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash ?? ''}`; } const timestampRE = /\bt=\d{13}&?\b/; function removeTimestampQuery(url) { return url.replace(timestampRE, '').replace(trailingSeparatorRE, ''); } async function asyncReplace(input, re, replacer) { let match; let remaining = input; let rewritten = ''; while ((match = re.exec(remaining))) { rewritten += remaining.slice(0, match.index); rewritten += await replacer(match); remaining = remaining.slice(match.index + match[0].length); } rewritten += remaining; return rewritten; } function timeFrom(start, subtract = 0) { const time = performance$1.now() - start - subtract; const timeString = (time.toFixed(2) + `ms`).padEnd(5, ' '); if (time < 10) { return colors$1$1.green(timeString); } else if (time < 50) { return colors$1$1.yellow(timeString); } else { return colors$1$1.red(timeString); } } /** * pretty url for logging. */ function prettifyUrl(url, root) { url = removeTimestampQuery(url); const isAbsoluteFile = url.startsWith(root); if (isAbsoluteFile || url.startsWith(FS_PREFIX)) { const file = path$o$1.relative(root, isAbsoluteFile ? url : fsPathFromId(url)); return colors$1$1.dim(file); } else { return colors$1$1.dim(url); } } function isObject$2$1(value) { return Object.prototype.toString.call(value) === '[object Object]'; } function isDefined(value) { return value != null; } function tryStatSync$1(file) { try { return fs$l__default.statSync(file, { throwIfNoEntry: false }); } catch { // Ignore errors } } function lookupFile(dir, fileNames) { while (dir) { for (const fileName of fileNames) { const fullPath = path$o$1.join(dir, fileName); if (tryStatSync$1(fullPath)?.isFile()) return fullPath; } const parentDir = path$o$1.dirname(dir); if (parentDir === dir) return; dir = parentDir; } } const splitRE = /\r?\n/; const range = 2; function pad$1(source, n = 2) { const lines = source.split(splitRE); return lines.map((l) => ` `.repeat(n) + l).join(`\n`); } function posToNumber(source, pos) { if (typeof pos === 'number') return pos; const lines = source.split(splitRE); const { line, column } = pos; let start = 0; for (let i = 0; i < line - 1 && i < lines.length; i++) { start += lines[i].length + 1; } return start + column; } function numberToPos(source, offset) { if (typeof offset !== 'number') return offset; if (offset > source.length) { throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`); } const lines = source.split(splitRE); let counted = 0; let line = 0; let column = 0; for (; line < lines.length; line++) { const lineLength = lines[line].length + 1; if (counted + lineLength >= offset) { column = offset - counted + 1; break; } counted += lineLength; } return { line: line + 1, column }; } function generateCodeFrame(source, start = 0, end) { start = posToNumber(source, start); end = end || start; const lines = source.split(splitRE); let count = 0; const res = []; for (let i = 0; i < lines.length; i++) { count += lines[i].length + 1; if (count >= start) { for (let j = i - range; j <= i + range || end > count; j++) { if (j < 0 || j >= lines.length) continue; const line = j + 1; res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`); const lineLength = lines[j].length; if (j === i) { // push underline const pad = Math.max(start - (count - lineLength) + 1, 0); const length = Math.max(1, end > count ? lineLength - pad : end - start); res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length)); } else if (j > i) { if (end > count) { const length = Math.max(Math.min(end - count, lineLength), 1); res.push(` | ` + '^'.repeat(length)); } count += lineLength + 1; } } break; } } return res.join('\n'); } function isFileReadable(filename) { try { // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist if (!fs$l__default.statSync(filename, { throwIfNoEntry: false })) { return false; } // Check if current process has read permission to the file fs$l__default.accessSync(filename, fs$l__default.constants.R_OK); return true; } catch { return false; } } const splitFirstDirRE = /(.+?)[\\/](.+)/; /** * Delete every file and subdirectory. **The given directory must exist.** * Pass an optional `skip` array to preserve files under the root directory. */ function emptyDir(dir, skip) { const skipInDir = []; let nested = null; if (skip?.length) { for (const file of skip) { if (path$o$1.dirname(file) !== '.') { const matched = file.match(splitFirstDirRE); if (matched) { nested ?? (nested = new Map()); const [, nestedDir, skipPath] = matched; let nestedSkip = nested.get(nestedDir); if (!nestedSkip) { nestedSkip = []; nested.set(nestedDir, nestedSkip); } if (!nestedSkip.includes(skipPath)) { nestedSkip.push(skipPath); } } } else { skipInDir.push(file); } } } for (const file of fs$l__default.readdirSync(dir)) { if (skipInDir.includes(file)) { continue; } if (nested?.has(file)) { emptyDir(path$o$1.resolve(dir, file), nested.get(file)); } else { fs$l__default.rmSync(path$o$1.resolve(dir, file), { recursive: true, force: true }); } } } function copyDir(srcDir, destDir) { fs$l__default.mkdirSync(destDir, { recursive: true }); for (const file of fs$l__default.readdirSync(srcDir)) { const srcFile = path$o$1.resolve(srcDir, file); if (srcFile === destDir) { continue; } const destFile = path$o$1.resolve(destDir, file); const stat = fs$l__default.statSync(srcFile); if (stat.isDirectory()) { copyDir(srcFile, destFile); } else { fs$l__default.copyFileSync(srcFile, destFile); } } } // `fs.realpathSync.native` resolves differently in Windows network drive, // causing file read errors. skip for now. // https://github.com/nodejs/node/issues/37737 let safeRealpathSync = isWindows$4$1 ? windowsSafeRealPathSync$1 : fs$l__default.realpathSync.native; // Based on https://github.com/larrybahr/windows-network-drive // MIT License, Copyright (c) 2017 Larry Bahr const windowsNetworkMap$1 = new Map(); function windowsMappedRealpathSync(path) { const realPath = fs$l__default.realpathSync.native(path); if (realPath.startsWith('\\\\')) { for (const [network, volume] of windowsNetworkMap$1) { if (realPath.startsWith(network)) return realPath.replace(network, volume); } } return realPath; } const parseNetUseRE$1 = /^(\w+)? +(\w:) +([^ ]+)\s/; let firstSafeRealPathSyncRun$1 = false; function windowsSafeRealPathSync$1(path) { if (!firstSafeRealPathSyncRun$1) { optimizeSafeRealPathSync$1(); firstSafeRealPathSyncRun$1 = true; } return fs$l__default.realpathSync(path); } function optimizeSafeRealPathSync$1() { // Skip if using Node <16.18 due to MAX_PATH issue: https://github.com/vitejs/vite/issues/12931 const nodeVersion = process.versions.node.split('.').map(Number); if (nodeVersion[0] < 16 || (nodeVersion[0] === 16 && nodeVersion[1] < 18)) { safeRealpathSync = fs$l__default.realpathSync; return; } exec('net use', (error, stdout) => { if (error) return; const lines = stdout.split('\n'); // OK Y: \\NETWORKA\Foo Microsoft Windows Network // OK Z: \\NETWORKA\Bar Microsoft Windows Network for (const line of lines) { const m = line.match(parseNetUseRE$1); if (m) windowsNetworkMap$1.set(m[3], m[2]); } if (windowsNetworkMap$1.size === 0) { safeRealpathSync = fs$l__default.realpathSync.native; } else { safeRealpathSync = windowsMappedRealpathSync; } }); } function ensureWatchedFile$1(watcher, file, root) { if (file && // only need to watch if out of root !file.startsWith(root + '/') && // some rollup plugins use null bytes for private resolved Ids !file.includes('\0') && fs$l__default.existsSync(file)) { // resolve file to normalized system path watcher.add(path$o$1.resolve(file)); } } const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g; const imageSetUrlRE = /^(?:[\w\-]+\(.*?\)|'.*?'|".*?"|\S*)/; function reduceSrcset(ret) { return ret.reduce((prev, { url, descriptor }, index) => { descriptor ?? (descriptor = ''); return (prev += url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`); }, ''); } function splitSrcSetDescriptor(srcs) { return splitSrcSet(srcs) .map((s) => { const src = s.replace(escapedSpaceCharacters, ' ').trim(); const [url] = imageSetUrlRE.exec(src) || ['']; return { url, descriptor: src?.slice(url.length).trim(), }; }) .filter(({ url }) => !!url); } function processSrcSet(srcs, replacer) { return Promise.all(splitSrcSetDescriptor(srcs).map(async ({ url, descriptor }) => ({ url: await replacer({ url, descriptor }), descriptor, }))).then((ret) => reduceSrcset(ret)); } function processSrcSetSync(srcs, replacer) { return reduceSrcset(splitSrcSetDescriptor(srcs).map(({ url, descriptor }) => ({ url: replacer({ url, descriptor }), descriptor, }))); } const cleanSrcSetRE = /(?:url|image|gradient|cross-fade)\([^)]*\)|"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'/g; function splitSrcSet(srcs) { const parts = []; // There could be a ',' inside of url(data:...), linear-gradient(...) or "data:..." const cleanedSrcs = srcs.replace(cleanSrcSetRE, blankReplacer); let startIndex = 0; let splitIndex; do { splitIndex = cleanedSrcs.indexOf(',', startIndex); parts.push(srcs.slice(startIndex, splitIndex !== -1 ? splitIndex : undefined)); startIndex = splitIndex + 1; } while (splitIndex !== -1); return parts; } const windowsDriveRE = /^[A-Z]:/; const replaceWindowsDriveRE = /^([A-Z]):\//; const linuxAbsolutePathRE = /^\/[^/]/; function escapeToLinuxLikePath(path) { if (windowsDriveRE.test(path)) { return path.replace(replaceWindowsDriveRE, '/windows/$1/'); } if (linuxAbsolutePathRE.test(path)) { return `/linux${path}`; } return path; } const revertWindowsDriveRE = /^\/windows\/([A-Z])\//; function unescapeToLinuxLikePath(path) { if (path.startsWith('/linux/')) { return path.slice('/linux'.length); } if (path.startsWith('/windows/')) { return path.replace(revertWindowsDriveRE, '$1:/'); } return path; } // based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221 const nullSourceMap = { names: [], sources: [], mappings: '', version: 3, }; function combineSourcemaps(filename, sourcemapList, excludeContent = true) { if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) { return { ...nullSourceMap }; } // hack for parse broken with normalized absolute paths on windows (C:/path/to/something). // escape them to linux like paths // also avoid mutation here to prevent breaking plugin's using cache to generate sourcemaps like vue (see #7442) sourcemapList = sourcemapList.map((sourcemap) => { const newSourcemaps = { ...sourcemap }; newSourcemaps.sources = sourcemap.sources.map((source) => source ? escapeToLinuxLikePath(source) : null); if (sourcemap.sourceRoot) { newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot); } return newSourcemaps; }); const escapedFilename = escapeToLinuxLikePath(filename); // We don't declare type here so we can convert/fake/map as RawSourceMap let map; //: SourceMap let mapIndex = 1; const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined; if (useArrayInterface) { map = remapping(sourcemapList, () => null, excludeContent); } else { map = remapping(sourcemapList[0], function loader(sourcefile) { if (sourcefile === escapedFilename && sourcemapList[mapIndex]) { return sourcemapList[mapIndex++]; } else { return null; } }, excludeContent); } if (!map.file) { delete map.file; } // unescape the previous hack map.sources = map.sources.map((source) => source ? unescapeToLinuxLikePath(source) : source); map.file = filename; return map; } function unique(arr) { return Array.from(new Set(arr)); } /** * Returns resolved localhost address when `dns.lookup` result differs from DNS * * `dns.lookup` result is same when defaultResultOrder is `verbatim`. * Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same. * For example, when IPv6 is not supported on that machine/network. */ async function getLocalhostAddressIfDiffersFromDNS() { const [nodeResult, dnsResult] = await Promise.all([ promises$1.lookup('localhost'), promises$1.lookup('localhost', { verbatim: true }), ]); const isSame = nodeResult.family === dnsResult.family && nodeResult.address === dnsResult.address; return isSame ? undefined : nodeResult.address; } function diffDnsOrderChange(oldUrls, newUrls) { return !(oldUrls === newUrls || (oldUrls && newUrls && arrayEqual(oldUrls.local, newUrls.local) && arrayEqual(oldUrls.network, newUrls.network))); } async function resolveHostname(optionsHost) { let host; if (optionsHost === undefined || optionsHost === false) { // Use a secure default host = 'localhost'; } else if (optionsHost === true) { // If passed --host in the CLI without arguments host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs) } else { host = optionsHost; } // Set host name to localhost when possible let name = host === undefined || wildcardHosts.has(host) ? 'localhost' : host; if (host === 'localhost') { // See #8647 for more details. const localhostAddr = await getLocalhostAddressIfDiffersFromDNS(); if (localhostAddr) { name = localhostAddr; } } return { host, name }; } async function resolveServerUrls(server, options, config) { const address = server.address(); const isAddressInfo = (x) => x?.address; if (!isAddressInfo(address)) { return { local: [], network: [] }; } const local = []; const network = []; const hostname = await resolveHostname(options.host); const protocol = options.https ? 'https' : 'http'; const port = address.port; const base = config.rawBase === './' || config.rawBase === '' ? '/' : config.rawBase; if (hostname.host && loopbackHosts.has(hostname.host)) { let hostnameName = hostname.name; // ipv6 host if (hostnameName.includes(':')) { hostnameName = `[${hostnameName}]`; } local.push(`${protocol}://${hostnameName}:${port}${base}`); } else { Object.values(os$3$1.networkInterfaces()) .flatMap((nInterface) => nInterface ?? []) .filter((detail) => detail && detail.address && (detail.family === 'IPv4' || // @ts-expect-error Node 18.0 - 18.3 returns number detail.family === 4)) .forEach((detail) => { let host = detail.address.replace('127.0.0.1', hostname.name); // ipv6 host if (host.includes(':')) { host = `[${host}]`; } const url = `${protocol}://${host}:${port}${base}`; if (detail.address.includes('127.0.0.1')) { local.push(url); } else { network.push(url); } }); } return { local, network }; } function arraify$2(target) { return Array.isArray(target) ? target : [target]; } // Taken from https://stackoverflow.com/a/36328890 const multilineCommentsRE$1 = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g; const singlelineCommentsRE$1 = /\/\/.*/g; const requestQuerySplitRE = /\?(?!.*[/|}])/; // @ts-expect-error jest only exists when running Jest const usingDynamicImport$1 = typeof jest === 'undefined'; /** * Dynamically import files. It will make sure it's not being compiled away by TS/Rollup. * * As a temporary workaround for Jest's lack of stable ESM support, we fallback to require * if we're in a Jest environment. * See https://github.com/vitejs/vite/pull/5197#issuecomment-938054077 * * @param file File path to import. */ const dynamicImport = usingDynamicImport$1 ? new Function('file', 'return import(file)') : _require$3$1; function parseRequest(id) { const [_, search] = id.split(requestQuerySplitRE, 2); if (!search) { return null; } return Object.fromEntries(new URLSearchParams$1(search)); } const blankReplacer = (match) => ' '.repeat(match.length); function getHash(text) { return createHash$4('sha256').update(text).digest('hex').substring(0, 8); } const _dirname = path$o$1.dirname(fileURLToPath(import.meta.url)); const requireResolveFromRootWithFallback = (root, id) => { // check existence first, so if the package is not found, // it won't be cached by nodejs, since there isn't a way to invalidate them: // https://github.com/nodejs/node/issues/44663 const found = resolvePackageData(id, root) || resolvePackageData(id, _dirname); if (!found) { const error = new Error(`${JSON.stringify(id)} not found.`); error.code = 'MODULE_NOT_FOUND'; throw error; } // actually resolve // Search in the root directory first, and fallback to the default require paths. return _require$3$1.resolve(id, { paths: [root, _dirname] }); }; function emptyCssComments(raw) { return raw.replace(multilineCommentsRE$1, (s) => ' '.repeat(s.length)); } function removeComments$1(raw) { return raw.replace(multilineCommentsRE$1, '').replace(singlelineCommentsRE$1, ''); } function mergeConfigRecursively(defaults, overrides, rootPath) { const merged = { ...defaults }; for (const key in overrides) { const value = overrides[key]; if (value == null) { continue; } const existing = merged[key]; if (existing == null) { merged[key] = value; continue; } // fields that require special handling if (key === 'alias' && (rootPath === 'resolve' || rootPath === '')) { merged[key] = mergeAlias(existing, value); continue; } else if (key === 'assetsInclude' && rootPath === '') { merged[key] = [].concat(existing, value); continue; } else if (key === 'noExternal' && rootPath === 'ssr' && (existing === true || value === true)) { merged[key] = true; continue; } if (Array.isArray(existing) || Array.isArray(value)) { merged[key] = [...arraify$2(existing ?? []), ...arraify$2(value ?? [])]; continue; } if (isObject$2$1(existing) && isObject$2$1(value)) { merged[key] = mergeConfigRecursively(existing, value, rootPath ? `${rootPath}.${key}` : key); continue; } merged[key] = value; } return merged; } function mergeConfig(defaults, overrides, isRoot = true) { return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.'); } function mergeAlias(a, b) { if (!a) return b; if (!b) return a; if (isObject$2$1(a) && isObject$2$1(b)) { return { ...a, ...b }; } // the order is flipped because the alias is resolved from top-down, // where the later should have higher priority return [...normalizeAlias(b), ...normalizeAlias(a)]; } function normalizeAlias(o = []) { return Array.isArray(o) ? o.map(normalizeSingleAlias) : Object.keys(o).map((find) => normalizeSingleAlias({ find, replacement: o[find], })); } // https://github.com/vitejs/vite/issues/1363 // work around https://github.com/rollup/plugins/issues/759 function normalizeSingleAlias({ find, replacement, customResolver, }) { if (typeof find === 'string' && find[find.length - 1] === '/' && replacement[replacement.length - 1] === '/') { find = find.slice(0, find.length - 1); replacement = replacement.slice(0, replacement.length - 1); } const alias = { find, replacement, }; if (customResolver) { alias.customResolver = customResolver; } return alias; } /** * Transforms transpiled code result where line numbers aren't altered, * so we can skip sourcemap generation during dev */ function transformStableResult(s, id, config) { return { code: s.toString(), map: config.command === 'build' && config.build.sourcemap ? s.generateMap({ hires: true, source: id }) : null, }; } async function asyncFlatten(arr) { do { arr = (await Promise.all(arr)).flat(Infinity); } while (arr.some((v) => v?.then)); return arr; } // strip UTF-8 BOM function stripBomTag(content) { if (content.charCodeAt(0) === 0xfeff) { return content.slice(1); } return content; } const windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/; /** * path.isAbsolute also returns true for drive relative paths on windows (e.g. /something) * this function returns false for them but true for absolute paths (e.g. C:/something) */ const isNonDriveRelativeAbsolutePath = (p) => { if (!isWindows$4$1) return p[0] === '/'; return windowsDrivePathPrefixRE.test(p); }; /** * Determine if a file is being requested with the correct case, to ensure * consistent behaviour between dev and prod and across operating systems. */ function shouldServeFile(filePath, root) { // can skip case check on Linux if (!isCaseInsensitiveFS) return true; return hasCorrectCase(filePath, root); } /** * Note that we can't use realpath here, because we don't want to follow * symlinks. */ function hasCorrectCase(file, assets) { if (file === assets) return true; const parent = path$o$1.dirname(file); if (fs$l__default.readdirSync(parent).includes(path$o$1.basename(file))) { return hasCorrectCase(parent, assets); } return false; } function joinUrlSegments(a, b) { if (!a || !b) { return a || b || ''; } if (a[a.length - 1] === '/') { a = a.substring(0, a.length - 1); } if (b[0] !== '/') { b = '/' + b; } return a + b; } function removeLeadingSlash(str) { return str[0] === '/' ? str.slice(1) : str; } function stripBase(path, base) { if (path === base) { return '/'; } const devBase = base[base.length - 1] === '/' ? base : base + '/'; return path.startsWith(devBase) ? path.slice(devBase.length - 1) : path; } function arrayEqual(a, b) { if (a === b) return true; if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) return false; } return true; } function evalValue(rawValue) { const fn = new Function(` var console, exports, global, module, process, require return (\n${rawValue}\n) `); return fn(); } const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g; function escapeRegex(str) { return str.replace(escapeRegexRE, '\\$&'); } /* eslint no-console: 0 */ const LogLevels = { silent: 0, error: 1, warn: 2, info: 3, }; let lastType; let lastMsg; let sameCount = 0; function clearScreen() { const repeatCount = process.stdout.rows - 2; const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : ''; console.log(blank); readline.cursorTo(process.stdout, 0, 0); readline.clearScreenDown(process.stdout); } function createLogger$1(level = 'info', options = {}) { if (options.customLogger) { return options.customLogger; } const loggedErrors = new WeakSet(); const { prefix = '[vite]', allowClearScreen = true } = options; const thresh = LogLevels[level]; const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI; const clear = canClearScreen ? clearScreen : () => { }; function output(type, msg, options = {}) { if (thresh >= LogLevels[type]) { const method = type === 'info' ? 'log' : type; const format = () => { if (options.timestamp) { const tag = type === 'info' ? colors$1$1.cyan(colors$1$1.bold(prefix)) : type === 'warn' ? colors$1$1.yellow(colors$1$1.bold(prefix)) : colors$1$1.red(colors$1$1.bold(prefix)); return `${colors$1$1.dim(new Date().toLocaleTimeString())} ${tag} ${msg}`; } else { return msg; } }; if (options.error) { loggedErrors.add(options.error); } if (canClearScreen) { if (type === lastType && msg === lastMsg) { sameCount++; clear(); console[method](format(), colors$1$1.yellow(`(x${sameCount + 1})`)); } else { sameCount = 0; lastMsg = msg; lastType = type; if (options.clear) { clear(); } console[method](format()); } } else { console[method](format()); } } } const warnedMessages = new Set(); const logger = { hasWarned: false, info(msg, opts) { output('info', msg, opts); }, warn(msg, opts) { logger.hasWarned = true; output('warn', msg, opts); }, warnOnce(msg, opts) { if (warnedMessages.has(msg)) return; logger.hasWarned = true; output('warn', msg, opts); warnedMessages.add(msg); }, error(msg, opts) { logger.hasWarned = true; output('error', msg, opts); }, clearScreen(type) { if (thresh >= LogLevels[type]) { clear(); } }, hasErrorLogged(error) { return loggedErrors.has(error); }, }; return logger; } function printServerUrls(urls, optionsHost, info) { const colorUrl = (url) => colors$1$1.cyan(url.replace(/:(\d+)\//, (_, port) => `:${colors$1$1.bold(port)}/`)); for (const url of urls.local) { info(` ${colors$1$1.green('➜')} ${colors$1$1.bold('Local')}: ${colorUrl(url)}`); } for (const url of urls.network) { info(` ${colors$1$1.green('➜')} ${colors$1$1.bold('Network')}: ${colorUrl(url)}`); } if (urls.network.length === 0 && optionsHost === undefined) { info(colors$1$1.dim(` ${colors$1$1.green('➜')} ${colors$1$1.bold('Network')}: use `) + colors$1$1.bold('--host') + colors$1$1.dim(' to expose')); } } const groups = [ { name: 'Assets', color: colors$1$1.green }, { name: 'CSS', color: colors$1$1.magenta }, { name: 'JS', color: colors$1$1.cyan }, ]; const COMPRESSIBLE_ASSETS_RE = /\.(?:html|json|svg|txt|xml|xhtml)$/; function buildReporterPlugin(config) { const compress = promisify$5(gzip); const chunkLimit = config.build.chunkSizeWarningLimit; const tty = process.stdout.isTTY && !process.env.CI; const shouldLogInfo = LogLevels[config.logLevel || 'info'] >= LogLevels.info; let hasTransformed = false; let hasRenderedChunk = false; let hasCompressChunk = false; let transformedCount = 0; let chunkCount = 0; let compressedCount = 0; let startTime = Date.now(); async function getCompressedSize(code) { if (config.build.ssr || !config.build.reportCompressedSize) { return null; } if (shouldLogInfo && !hasCompressChunk) { if (!tty) { config.logger.info('computing gzip size...'); } else { writeLine('computing gzip size (0)...'); } hasCompressChunk = true; } const compressed = await compress(typeof code === 'string' ? code : Buffer.from(code)); compressedCount++; if (shouldLogInfo && tty) { writeLine(`computing gzip size (${compressedCount})...`); } return compressed.length; } const logTransform = throttle((id) => { writeLine(`transforming (${transformedCount}) ${colors$1$1.dim(path$o$1.relative(config.root, id))}`); }); return { name: 'vite:reporter', transform(_, id) { transformedCount++; if (shouldLogInfo) { if (!tty) { if (!hasTransformed) { config.logger.info(`transforming...`); } } else { if (id.includes(`?`)) return; logTransform(id); } hasTransformed = true; } return null; }, options() { startTime = Date.now(); }, buildStart() { transformedCount = 0; }, buildEnd() { if (shouldLogInfo) { if (tty) { clearLine(); } config.logger.info(`${colors$1$1.green(`✓`)} ${transformedCount} modules transformed.`); } }, renderStart() { chunkCount = 0; compressedCount = 0; }, renderChunk() { chunkCount++; if (shouldLogInfo) { if (!tty) { if (!hasRenderedChunk) { config.logger.info('rendering chunks...'); } } else { writeLine(`rendering chunks (${chunkCount})...`); } hasRenderedChunk = true; } return null; }, generateBundle() { if (shouldLogInfo && tty) clearLine(); }, async writeBundle({ dir: outDir }, output) { let hasLargeChunks = false; if (shouldLogInfo) { const entries = (await Promise.all(Object.values(output).map(async (chunk) => { if (chunk.type === 'chunk') { return { name: chunk.fileName, group: 'JS', size: chunk.code.length, compressedSize: await getCompressedSize(chunk.code), mapSize: chunk.map ? chunk.map.toString().length : null, }; } else { if (chunk.fileName.endsWith('.map')) return null; const isCSS = chunk.fileName.endsWith('.css'); const isCompressible = isCSS || COMPRESSIBLE_ASSETS_RE.test(chunk.fileName); return { name: chunk.fileName, group: isCSS ? 'CSS' : 'Assets', size: chunk.source.length, mapSize: null, compressedSize: isCompressible ? await getCompressedSize(chunk.source) : null, }; } }))).filter(isDefined); if (tty) clearLine(); let longest = 0; let biggestSize = 0; let biggestMap = 0; let biggestCompressSize = 0; for (const entry of entries) { if (entry.name.length > longest) longest = entry.name.length; if (entry.size > biggestSize) biggestSize = entry.size; if (entry.mapSize && entry.mapSize > biggestMap) { biggestMap = entry.mapSize; } if (entry.compressedSize && entry.compressedSize > biggestCompressSize) { biggestCompressSize = entry.compressedSize; } } const sizePad = displaySize(biggestSize).length; const mapPad = displaySize(biggestMap).length; const compressPad = displaySize(biggestCompressSize).length; const relativeOutDir = normalizePath$3$1(path$o$1.relative(config.root, path$o$1.resolve(config.root, outDir ?? config.build.outDir))); const assetsDir = path$o$1.join(config.build.assetsDir, '/'); for (const group of groups) { const filtered = entries.filter((e) => e.group === group.name); if (!filtered.length) continue; for (const entry of filtered.sort((a, z) => a.size - z.size)) { const isLarge = group.name === 'JS' && entry.size / 1000 > chunkLimit; if (isLarge) hasLargeChunks = true; const sizeColor = isLarge ? colors$1$1.yellow : colors$1$1.dim; let log = colors$1$1.dim(relativeOutDir + '/'); log += !config.build.lib && entry.name.startsWith(assetsDir) ? colors$1$1.dim(assetsDir) + group.color(entry.name .slice(assetsDir.length) .padEnd(longest + 2 - assetsDir.length)) : group.color(entry.name.padEnd(longest + 2)); log += colors$1$1.bold(sizeColor(displaySize(entry.size).padStart(sizePad))); if (entry.compressedSize) { log += colors$1$1.dim(` │ gzip: ${displaySize(entry.compressedSize).padStart(compressPad)}`); } if (entry.mapSize) { log += colors$1$1.dim(` │ map: ${displaySize(entry.mapSize).padStart(mapPad)}`); } config.logger.info(log); } } } else { hasLargeChunks = Object.values(output).some((chunk) => { return chunk.type === 'chunk' && chunk.code.length / 1000 > chunkLimit; }); } if (hasLargeChunks && config.build.minify && !config.build.lib && !config.build.ssr) { config.logger.warn(colors$1$1.yellow(`\n(!) Some chunks are larger than ${chunkLimit} kBs after minification. Consider:\n` + `- Using dynamic import() to code-split the application\n` + `- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks\n` + `- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`)); } }, closeBundle() { if (shouldLogInfo && !config.build.watch) { config.logger.info(`${colors$1$1.green(`✓ built in ${displayTime(Date.now() - startTime)}`)}`); } }, }; } function writeLine(output) { clearLine(); if (output.length < process.stdout.columns) { process.stdout.write(output); } else { process.stdout.write(output.substring(0, process.stdout.columns - 1)); } } function clearLine() { process.stdout.clearLine(0); process.stdout.cursorTo(0); } function throttle(fn) { let timerHandle = null; return (...args) => { if (timerHandle) return; fn(...args); timerHandle = setTimeout(() => { timerHandle = null; }, 100); }; } function displaySize(bytes) { return `${(bytes / 1000).toLocaleString('en', { maximumFractionDigits: 2, minimumFractionDigits: 2, })} kB`; } function displayTime(time) { // display: {X}ms if (time < 1000) { return `${time}ms`; } time = time / 1000; // display: {X}s if (time < 60) { return `${time.toFixed(2)}s`; } const mins = parseInt((time / 60).toString()); const seconds = time % 60; // display: {X}m {Y}s return `${mins}m${seconds < 1 ? '' : ` ${seconds.toFixed(0)}s`}`; } // src/find.ts async function find(filename, options) { let dir = require$$0$4.dirname(require$$0$4.resolve(filename)); const root = (options == null ? void 0 : options.root) ? require$$0$4.resolve(options.root) : null; while (dir) { const tsconfig = await tsconfigInDir(dir, options); if (tsconfig) { return tsconfig; } else { if (root === dir) { break; } const parent = require$$0$4.dirname(dir); if (parent === dir) { break; } else { dir = parent; } } } throw new Error(`no tsconfig file found for ${filename}`); } async function tsconfigInDir(dir, options) { const tsconfig = require$$0$4.join(dir, "tsconfig.json"); if (options == null ? void 0 : options.tsConfigPaths) { return options.tsConfigPaths.has(tsconfig) ? tsconfig : void 0; } try { const stat = await promises$2.stat(tsconfig); if (stat.isFile() || stat.isFIFO()) { return tsconfig; } } catch (e) { if (e.code !== "ENOENT") { throw e; } } } var sep$1 = require$$0$4.sep; async function findAll(dir, options) { const state = { files: [], calls: 0, skip: options == null ? void 0 : options.skip, err: false }; return new Promise((resolve, reject) => { walk$3(require$$0$4.resolve(dir), state, (err, files) => err ? reject(err) : resolve(files)); }); } function walk$3(dir, state, done) { if (state.err) { return; } state.calls++; readdir$5(dir, { withFileTypes: true }, (err, entries = []) => { var _a; if (state.err) { return; } if (err && !(err.code === "ENOENT" || err.code === "EACCES")) { state.err = true; done(err); } else { for (const ent of entries) { if (ent.isDirectory() && !((_a = state.skip) == null ? void 0 : _a.call(state, ent.name))) { walk$3(`${dir}${sep$1}${ent.name}`, state, done); } else if (ent.isFile() && ent.name === "tsconfig.json") { state.files.push(`${dir}${sep$1}tsconfig.json`); } } if (--state.calls === 0) { if (!state.err) { done(null, state.files); } } } }); } // src/to-json.ts function toJson(tsconfigJson) { const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson))); if (stripped.trim() === "") { return "{}"; } else { return stripped; } } function stripDanglingComma(pseudoJson) { let insideString = false; let offset = 0; let result = ""; let danglingCommaPos = null; for (let i = 0; i < pseudoJson.length; i++) { const currentCharacter = pseudoJson[i]; if (currentCharacter === '"') { const escaped = isEscaped(pseudoJson, i); if (!escaped) { insideString = !insideString; } } if (insideString) { danglingCommaPos = null; continue; } if (currentCharacter === ",") { danglingCommaPos = i; continue; } if (danglingCommaPos) { if (currentCharacter === "}" || currentCharacter === "]") { result += pseudoJson.slice(offset, danglingCommaPos) + " "; offset = danglingCommaPos + 1; danglingCommaPos = null; } else if (!currentCharacter.match(/\s/)) { danglingCommaPos = null; } } } return result + pseudoJson.substring(offset); } function isEscaped(jsonString, quotePosition) { let index = quotePosition - 1; let backslashCount = 0; while (jsonString[index] === "\\") { index -= 1; backslashCount += 1; } return Boolean(backslashCount % 2); } function strip(string, start, end) { return string.slice(start, end).replace(/\S/g, " "); } var singleComment = Symbol("singleComment"); var multiComment = Symbol("multiComment"); function stripJsonComments(jsonString) { let isInsideString = false; let isInsideComment = false; let offset = 0; let result = ""; for (let index = 0; index < jsonString.length; index++) { const currentCharacter = jsonString[index]; const nextCharacter = jsonString[index + 1]; if (!isInsideComment && currentCharacter === '"') { const escaped = isEscaped(jsonString, index); if (!escaped) { isInsideString = !isInsideString; } } if (isInsideString) { continue; } if (!isInsideComment && currentCharacter + nextCharacter === "//") { result += jsonString.slice(offset, index); offset = index; isInsideComment = singleComment; index++; } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === "\r\n") { index++; isInsideComment = false; result += strip(jsonString, offset, index); offset = index; } else if (isInsideComment === singleComment && currentCharacter === "\n") { isInsideComment = false; result += strip(jsonString, offset, index); offset = index; } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") { result += jsonString.slice(offset, index); offset = index; isInsideComment = multiComment; index++; } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === "*/") { index++; isInsideComment = false; result += strip(jsonString, offset, index + 1); offset = index + 1; } } return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset)); } function stripBom(string) { if (string.charCodeAt(0) === 65279) { return string.slice(1); } return string; } var POSIX_SEP_RE = new RegExp("\\" + require$$0$4.posix.sep, "g"); var NATIVE_SEP_RE = new RegExp("\\" + require$$0$4.sep, "g"); var PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map(); var GLOB_ALL_PATTERN = `**/*`; var DEFAULT_EXTENSIONS$1 = [".ts", ".tsx", ".mts", ".cts"]; var DEFAULT_EXTENSIONS_RE_GROUP = `\\.(?:${DEFAULT_EXTENSIONS$1.map((ext) => ext.substring(1)).join( "|" )})`; new Function("path", "return import(path).then(m => m.default)"); async function resolveTSConfig(filename) { if (require$$0$4.extname(filename) !== ".json") { return; } const tsconfig = require$$0$4.resolve(filename); try { const stat = await promises$2.stat(tsconfig); if (stat.isFile() || stat.isFIFO()) { return tsconfig; } } catch (e) { if (e.code !== "ENOENT") { throw e; } } throw new Error(`no tsconfig file found for ${filename}`); } function posix2native(filename) { return require$$0$4.posix.sep !== require$$0$4.sep && filename.includes(require$$0$4.posix.sep) ? filename.replace(POSIX_SEP_RE, require$$0$4.sep) : filename; } function native2posix(filename) { return require$$0$4.posix.sep !== require$$0$4.sep && filename.includes(require$$0$4.sep) ? filename.replace(NATIVE_SEP_RE, require$$0$4.posix.sep) : filename; } function resolve2posix(dir, filename) { if (require$$0$4.sep === require$$0$4.posix.sep) { return dir ? require$$0$4.resolve(dir, filename) : require$$0$4.resolve(filename); } return native2posix( dir ? require$$0$4.resolve(posix2native(dir), posix2native(filename)) : require$$0$4.resolve(posix2native(filename)) ); } function resolveReferencedTSConfigFiles(result) { const dir = require$$0$4.dirname(result.tsconfigFile); return result.tsconfig.references.map((ref) => { const refPath = ref.path.endsWith(".json") ? ref.path : require$$0$4.join(ref.path, "tsconfig.json"); return resolve2posix(dir, refPath); }); } function resolveSolutionTSConfig(filename, result) { if (result.referenced && DEFAULT_EXTENSIONS$1.some((ext) => filename.endsWith(ext)) && !isIncluded(filename, result)) { const solutionTSConfig = result.referenced.find( (referenced) => isIncluded(filename, referenced) ); if (solutionTSConfig) { return { ...solutionTSConfig, solution: result }; } } return result; } function isIncluded(filename, result) { const dir = native2posix(require$$0$4.dirname(result.tsconfigFile)); const files = (result.tsconfig.files || []).map((file) => resolve2posix(dir, file)); const absoluteFilename = resolve2posix(null, filename); if (files.includes(filename)) { return true; } const isIncluded2 = isGlobMatch( absoluteFilename, dir, result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN]) ); if (isIncluded2) { const isExcluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || []); return !isExcluded; } return false; } function isGlobMatch(filename, dir, patterns) { return patterns.some((pattern) => { let lastWildcardIndex = pattern.length; let hasWildcard = false; for (let i = pattern.length - 1; i > -1; i--) { if (pattern[i] === "*" || pattern[i] === "?") { lastWildcardIndex = i; hasWildcard = true; break; } } if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) { return false; } if (pattern.endsWith("*") && !DEFAULT_EXTENSIONS$1.some((ext) => filename.endsWith(ext))) { return false; } if (pattern === GLOB_ALL_PATTERN) { return filename.startsWith(`${dir}/`); } const resolvedPattern = resolve2posix(dir, pattern); let firstWildcardIndex = -1; for (let i = 0; i < resolvedPattern.length; i++) { if (resolvedPattern[i] === "*" || resolvedPattern[i] === "?") { firstWildcardIndex = i; hasWildcard = true; break; } } if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) { return false; } if (!hasWildcard) { return filename === resolvedPattern; } if (PATTERN_REGEX_CACHE.has(resolvedPattern)) { return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename); } const regex = pattern2regex(resolvedPattern); PATTERN_REGEX_CACHE.set(resolvedPattern, regex); return regex.test(filename); }); } function pattern2regex(resolvedPattern) { let regexStr = "^"; for (let i = 0; i < resolvedPattern.length; i++) { const char = resolvedPattern[i]; if (char === "?") { regexStr += "[^\\/]"; continue; } if (char === "*") { if (resolvedPattern[i + 1] === "*" && resolvedPattern[i + 2] === "/") { i += 2; regexStr += "(?:[^\\/]*\\/)*"; continue; } regexStr += "[^\\/]*"; continue; } if ("/.+^${}()|[]\\".includes(char)) { regexStr += `\\`; } regexStr += char; } if (resolvedPattern.endsWith("*")) { regexStr += DEFAULT_EXTENSIONS_RE_GROUP; } regexStr += "$"; return new RegExp(regexStr); } // src/parse.ts async function parse$f(filename, options) { const cache = options == null ? void 0 : options.cache; if (cache == null ? void 0 : cache.has(filename)) { return cache.get(filename); } let tsconfigFile; if (options == null ? void 0 : options.resolveWithEmptyIfConfigNotFound) { try { tsconfigFile = await resolveTSConfig(filename) || await find(filename, options); } catch (e) { const notFoundResult = { tsconfigFile: "no_tsconfig_file_found", tsconfig: {} }; cache == null ? void 0 : cache.set(filename, notFoundResult); return notFoundResult; } } else { tsconfigFile = await resolveTSConfig(filename) || await find(filename, options); } let result; if (cache == null ? void 0 : cache.has(tsconfigFile)) { result = cache.get(tsconfigFile); } else { result = await parseFile$1(tsconfigFile, cache); await Promise.all([parseExtends(result, cache), parseReferences(result, cache)]); cache == null ? void 0 : cache.set(tsconfigFile, result); } result = resolveSolutionTSConfig(filename, result); cache == null ? void 0 : cache.set(filename, result); return result; } async function parseFile$1(tsconfigFile, cache) { if (cache == null ? void 0 : cache.has(tsconfigFile)) { return cache.get(tsconfigFile); } try { const tsconfigJson = await promises$2.readFile(tsconfigFile, "utf-8"); const json = toJson(tsconfigJson); const result = { tsconfigFile, tsconfig: normalizeTSConfig(JSON.parse(json), require$$0$4.dirname(tsconfigFile)) }; cache == null ? void 0 : cache.set(tsconfigFile, result); return result; } catch (e) { throw new TSConfckParseError( `parsing ${tsconfigFile} failed: ${e}`, "PARSE_FILE", tsconfigFile, e ); } } function normalizeTSConfig(tsconfig, dir) { var _a; if (((_a = tsconfig.compilerOptions) == null ? void 0 : _a.baseUrl) && !require$$0$4.isAbsolute(tsconfig.compilerOptions.baseUrl)) { tsconfig.compilerOptions.baseUrl = resolve2posix(dir, tsconfig.compilerOptions.baseUrl); } return tsconfig; } async function parseReferences(result, cache) { if (!result.tsconfig.references) { return; } const referencedFiles = resolveReferencedTSConfigFiles(result); const referenced = await Promise.all(referencedFiles.map((file) => parseFile$1(file, cache))); await Promise.all(referenced.map((ref) => parseExtends(ref, cache))); result.referenced = referenced; } async function parseExtends(result, cache) { if (!result.tsconfig.extends) { return; } const extended = [ { tsconfigFile: result.tsconfigFile, tsconfig: JSON.parse(JSON.stringify(result.tsconfig)) } ]; let pos = 0; const extendsPath = []; let currentBranchDepth = 0; while (pos < extended.length) { const extending = extended[pos]; extendsPath.push(extending.tsconfigFile); if (extending.tsconfig.extends) { currentBranchDepth += 1; let resolvedExtends; if (!Array.isArray(extending.tsconfig.extends)) { resolvedExtends = [resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)]; } else { resolvedExtends = extending.tsconfig.extends.reverse().map((ex) => resolveExtends(ex, extending.tsconfigFile)); } const circularExtends = resolvedExtends.find( (tsconfigFile) => extendsPath.includes(tsconfigFile) ); if (circularExtends) { const circle = extendsPath.concat([circularExtends]).join(" -> "); throw new TSConfckParseError( `Circular dependency in "extends": ${circle}`, "EXTENDS_CIRCULAR", result.tsconfigFile ); } extended.splice( pos + 1, 0, ...await Promise.all(resolvedExtends.map((file) => parseFile$1(file, cache))) ); } else { extendsPath.splice(-currentBranchDepth); currentBranchDepth = 0; } pos = pos + 1; } result.extended = extended; for (const ext of result.extended.slice(1)) { extendTSConfig(result, ext); } } function resolveExtends(extended, from) { let error; try { return createRequire$2(from).resolve(extended); } catch (e) { error = e; } if (!require$$0$4.isAbsolute(extended) && !extended.startsWith("./") && !extended.startsWith("../")) { try { const fallbackExtended = require$$0$4.join(extended, "tsconfig.json"); return createRequire$2(from).resolve(fallbackExtended); } catch (e) { error = e; } } throw new TSConfckParseError( `failed to resolve "extends":"${extended}" in ${from}`, "EXTENDS_RESOLVE", from, error ); } var EXTENDABLE_KEYS = [ "compilerOptions", "files", "include", "exclude", "watchOptions", "compileOnSave", "typeAcquisition", "buildOptions" ]; function extendTSConfig(extending, extended) { const extendingConfig = extending.tsconfig; const extendedConfig = extended.tsconfig; const relativePath = native2posix( require$$0$4.relative(require$$0$4.dirname(extending.tsconfigFile), require$$0$4.dirname(extended.tsconfigFile)) ); for (const key of Object.keys(extendedConfig).filter((key2) => EXTENDABLE_KEYS.includes(key2))) { if (key === "compilerOptions") { if (!extendingConfig.compilerOptions) { extendingConfig.compilerOptions = {}; } for (const option of Object.keys(extendedConfig.compilerOptions)) { if (Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) { continue; } extendingConfig.compilerOptions[option] = rebaseRelative( option, extendedConfig.compilerOptions[option], relativePath ); } } else if (extendingConfig[key] === void 0) { if (key === "watchOptions") { extendingConfig.watchOptions = {}; for (const option of Object.keys(extendedConfig.watchOptions)) { extendingConfig.watchOptions[option] = rebaseRelative( option, extendedConfig.watchOptions[option], relativePath ); } } else { extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath); } } } } var REBASE_KEYS = [ // root "files", "include", "exclude", // compilerOptions "baseUrl", "rootDir", "rootDirs", "typeRoots", "outDir", "outFile", "declarationDir", // watchOptions "excludeDirectories", "excludeFiles" ]; function rebaseRelative(key, value, prependPath) { if (!REBASE_KEYS.includes(key)) { return value; } if (Array.isArray(value)) { return value.map((x) => rebasePath(x, prependPath)); } else { return rebasePath(value, prependPath); } } function rebasePath(value, prependPath) { if (require$$0$4.isAbsolute(value)) { return value; } else { return require$$0$4.posix.normalize(require$$0$4.posix.join(prependPath, value)); } } var TSConfckParseError = class extends Error { constructor(message, code, tsconfigFile, cause) { super(message); Object.setPrototypeOf(this, TSConfckParseError.prototype); this.name = TSConfckParseError.name; this.code = code; this.cause = cause; this.tsconfigFile = tsconfigFile; } }; // https://github.com/vitejs/vite/issues/2820#issuecomment-812495079 const ROOT_FILES = [ // '.git', // https://pnpm.io/workspaces/ 'pnpm-workspace.yaml', // https://rushjs.io/pages/advanced/config_files/ // 'rush.json', // https://nx.dev/latest/react/getting-started/nx-setup // 'workspace.json', // 'nx.json', // https://github.com/lerna/lerna#lernajson 'lerna.json', ]; // npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces // yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it function hasWorkspacePackageJSON(root) { const path = join$2(root, 'package.json'); if (!isFileReadable(path)) { return false; } const content = JSON.parse(fs$l__default.readFileSync(path, 'utf-8')) || {}; return !!content.workspaces; } function hasRootFile(root) { return ROOT_FILES.some((file) => fs$l__default.existsSync(join$2(root, file))); } function hasPackageJSON(root) { const path = join$2(root, 'package.json'); return fs$l__default.existsSync(path); } /** * Search up for the nearest `package.json` */ function searchForPackageRoot(current, root = current) { if (hasPackageJSON(current)) return current; const dir = dirname$1(current); // reach the fs root if (!dir || dir === current) return root; return searchForPackageRoot(dir, root); } /** * Search up for the nearest workspace root */ function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) { if (hasRootFile(current)) return current; if (hasWorkspacePackageJSON(current)) return current; const dir = dirname$1(current); // reach the fs root if (!dir || dir === current) return root; return searchForWorkspaceRoot(dir, root); } const debug$f = createDebugger$1('vite:esbuild'); const INJECT_HELPERS_IIFE_RE = /^(.*?)((?:const|var)\s+\S+\s*=\s*function\s*\([^)]*\)\s*\{.*?"use strict";)/s; const INJECT_HELPERS_UMD_RE = /^(.*?)(\(function\([^)]*\)\s*\{.+?amd.+?function\([^)]*\)\s*\{.*?"use strict";)/s; const validExtensionRE = /\.\w+$/; const jsxExtensionsRE = /\.(?:j|t)sx\b/; let server; async function transformWithEsbuild(code, filename, options, inMap) { let loader = options?.loader; if (!loader) { // if the id ends with a valid ext, use it (e.g. vue blocks) // otherwise, cleanup the query before checking the ext const ext = path$o$1 .extname(validExtensionRE.test(filename) ? filename : cleanUrl$1(filename)) .slice(1); if (ext === 'cjs' || ext === 'mjs') { loader = 'js'; } else if (ext === 'cts' || ext === 'mts') { loader = 'ts'; } else { loader = ext; } } let tsconfigRaw = options?.tsconfigRaw; // if options provide tsconfigRaw in string, it takes highest precedence if (typeof tsconfigRaw !== 'string') { // these fields would affect the compilation result // https://esbuild.github.io/content-types/#tsconfig-json const meaningfulFields = [ 'alwaysStrict', 'importsNotUsedAsValues', 'jsx', 'jsxFactory', 'jsxFragmentFactory', 'jsxImportSource', 'preserveValueImports', 'target', 'useDefineForClassFields', ]; const compilerOptionsForFile = {}; if (loader === 'ts' || loader === 'tsx') { const loadedTsconfig = await loadTsconfigJsonForFile(filename); const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {}; for (const field of meaningfulFields) { if (field in loadedCompilerOptions) { // @ts-expect-error TypeScript can't tell they are of the same type compilerOptionsForFile[field] = loadedCompilerOptions[field]; } } } const compilerOptions = { ...compilerOptionsForFile, ...tsconfigRaw?.compilerOptions, }; // esbuild derives `useDefineForClassFields` from `target` instead of `tsconfig.compilerOptions.target` // https://github.com/evanw/esbuild/issues/2584 // but we want `useDefineForClassFields` to be derived from `tsconfig.compilerOptions.target` if (compilerOptions.useDefineForClassFields === undefined) { const lowercaseTarget = compilerOptions.target?.toLowerCase() ?? 'es3'; if (lowercaseTarget.startsWith('es')) { const esVersion = lowercaseTarget.slice(2); compilerOptions.useDefineForClassFields = esVersion === 'next' || +esVersion >= 2022; } else { compilerOptions.useDefineForClassFields = false; } } // esbuild uses tsconfig fields when both the normal options and tsconfig was set // but we want to prioritize the normal options if (options) { options.jsx && (compilerOptions.jsx = undefined); options.jsxFactory && (compilerOptions.jsxFactory = undefined); options.jsxFragment && (compilerOptions.jsxFragmentFactory = undefined); options.jsxImportSource && (compilerOptions.jsxImportSource = undefined); options.target && (compilerOptions.target = undefined); } tsconfigRaw = { ...tsconfigRaw, compilerOptions, }; } const resolvedOptions = { sourcemap: true, // ensure source file name contains full query sourcefile: filename, ...options, loader, tsconfigRaw, }; // Some projects in the ecosystem are calling this function with an ESBuildOptions // object and esbuild throws an error for extra fields delete resolvedOptions.include; delete resolvedOptions.exclude; delete resolvedOptions.jsxInject; try { const result = await transform$4(code, resolvedOptions); let map; if (inMap && resolvedOptions.sourcemap) { const nextMap = JSON.parse(result.map); nextMap.sourcesContent = []; map = combineSourcemaps(filename, [ nextMap, inMap, ]); } else { map = resolvedOptions.sourcemap && resolvedOptions.sourcemap !== 'inline' ? JSON.parse(result.map) : { mappings: '' }; } return { ...result, map, }; } catch (e) { debug$f?.(`esbuild error with options used: `, resolvedOptions); // patch error information if (e.errors) { e.frame = ''; e.errors.forEach((m) => { e.frame += `\n` + prettifyMessage(m, code); }); e.loc = e.errors[0].location; } throw e; } } function esbuildPlugin(config) { const options = config.esbuild; const { jsxInject, include, exclude, ...esbuildTransformOptions } = options; const filter = createFilter$3(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/); // Remove optimization options for dev as we only need to transpile them, // and for build as the final optimization is in `buildEsbuildPlugin` const transformOptions = { target: 'esnext', charset: 'utf8', ...esbuildTransformOptions, minify: false, minifyIdentifiers: false, minifySyntax: false, minifyWhitespace: false, treeShaking: false, // keepNames is not needed when minify is disabled. // Also transforming multiple times with keepNames enabled breaks // tree-shaking. (#9164) keepNames: false, }; initTSConfck(config.root); return { name: 'vite:esbuild', configureServer(_server) { server = _server; server.watcher .on('add', reloadOnTsconfigChange) .on('change', reloadOnTsconfigChange) .on('unlink', reloadOnTsconfigChange); }, buildEnd() { // recycle serve to avoid preventing Node self-exit (#6815) server = null; }, async transform(code, id) { if (filter(id) || filter(cleanUrl$1(id))) { const result = await transformWithEsbuild(code, id, transformOptions); if (result.warnings.length) { result.warnings.forEach((m) => { this.warn(prettifyMessage(m, code)); }); } if (jsxInject && jsxExtensionsRE.test(id)) { result.code = jsxInject + ';' + result.code; } return { code: result.code, map: result.map, }; } }, }; } const rollupToEsbuildFormatMap = { es: 'esm', cjs: 'cjs', // passing `var Lib = (() => {})()` to esbuild with format = "iife" // will turn it to `(() => { var Lib = (() => {})() })()`, // so we remove the format config to tell esbuild not doing this // // although esbuild doesn't change format, there is still possibility // that `{ treeShaking: true }` removes a top-level no-side-effect variable // like: `var Lib = 1`, which becomes `` after esbuild transforming, // but thankfully rollup does not do this optimization now iife: undefined, }; const buildEsbuildPlugin = (config) => { initTSConfck(config.root); return { name: 'vite:esbuild-transpile', async renderChunk(code, chunk, opts) { // @ts-expect-error injected by @vitejs/plugin-legacy if (opts.__vite_skip_esbuild__) { return null; } const options = resolveEsbuildTranspileOptions(config, opts.format); if (!options) { return null; } const res = await transformWithEsbuild(code, chunk.fileName, options); if (config.build.lib) { // #7188, esbuild adds helpers out of the UMD and IIFE wrappers, and the // names are minified potentially causing collision with other globals. // We use a regex to inject the helpers inside the wrappers. // We don't need to create a MagicString here because both the helpers and // the headers don't modify the sourcemap const injectHelpers = opts.format === 'umd' ? INJECT_HELPERS_UMD_RE : opts.format === 'iife' ? INJECT_HELPERS_IIFE_RE : undefined; if (injectHelpers) { res.code = res.code.replace(injectHelpers, (_, helpers, header) => header + helpers); } } return res; }, }; }; function resolveEsbuildTranspileOptions(config, format) { const target = config.build.target; const minify = config.build.minify === 'esbuild'; if ((!target || target === 'esnext') && !minify) { return null; } // Do not minify whitespace for ES lib output since that would remove // pure annotations and break tree-shaking // https://github.com/vuejs/core/issues/2860#issuecomment-926882793 const isEsLibBuild = config.build.lib && format === 'es'; const esbuildOptions = config.esbuild || {}; const options = { charset: 'utf8', ...esbuildOptions, target: target || undefined, format: rollupToEsbuildFormatMap[format], // the final build should always support dynamic import and import.meta. // if they need to be polyfilled, plugin-legacy should be used. // plugin-legacy detects these two features when checking for modern code. supported: { 'dynamic-import': true, 'import-meta': true, ...esbuildOptions.supported, }, }; // If no minify, disable all minify options if (!minify) { return { ...options, minify: false, minifyIdentifiers: false, minifySyntax: false, minifyWhitespace: false, treeShaking: false, }; } // If user enable fine-grain minify options, minify with their options instead if (options.minifyIdentifiers != null || options.minifySyntax != null || options.minifyWhitespace != null) { if (isEsLibBuild) { // Disable minify whitespace as it breaks tree-shaking return { ...options, minify: false, minifyIdentifiers: options.minifyIdentifiers ?? true, minifySyntax: options.minifySyntax ?? true, minifyWhitespace: false, treeShaking: true, }; } else { return { ...options, minify: false, minifyIdentifiers: options.minifyIdentifiers ?? true, minifySyntax: options.minifySyntax ?? true, minifyWhitespace: options.minifyWhitespace ?? true, treeShaking: true, }; } } // Else apply default minify options if (isEsLibBuild) { // Minify all except whitespace as it breaks tree-shaking return { ...options, minify: false, minifyIdentifiers: true, minifySyntax: true, minifyWhitespace: false, treeShaking: true, }; } else { return { ...options, minify: true, treeShaking: true, }; } } function prettifyMessage(m, code) { let res = colors$1$1.yellow(m.text); if (m.location) { const lines = code.split(/\r?\n/g); const line = Number(m.location.line); const column = Number(m.location.column); const offset = lines .slice(0, line - 1) .map((l) => l.length) .reduce((total, l) => total + l + 1, 0) + column; res += `\n` + generateCodeFrame(code, offset, offset + 1); } return res + `\n`; } let tsconfckRoot; let tsconfckParseOptions = { resolveWithEmptyIfConfigNotFound: true }; function initTSConfck(root, force = false) { // bail if already cached if (!force && root === tsconfckRoot) return; const workspaceRoot = searchForWorkspaceRoot(root); tsconfckRoot = root; tsconfckParseOptions = initTSConfckParseOptions(workspaceRoot); // cached as the options value itself when promise is resolved tsconfckParseOptions.then((options) => { if (root === tsconfckRoot) { tsconfckParseOptions = options; } }); } async function initTSConfckParseOptions(workspaceRoot) { const start = debug$f ? performance.now() : 0; const options = { cache: new Map(), root: workspaceRoot, tsConfigPaths: new Set(await findAll(workspaceRoot, { skip: (dir) => dir === 'node_modules' || dir === '.git', })), resolveWithEmptyIfConfigNotFound: true, }; debug$f?.(timeFrom(start), 'tsconfck init', colors$1$1.dim(workspaceRoot)); return options; } async function loadTsconfigJsonForFile(filename) { try { const result = await parse$f(filename, await tsconfckParseOptions); // tsconfig could be out of root, make sure it is watched on dev if (server && result.tsconfigFile !== 'no_tsconfig_file_found') { ensureWatchedFile$1(server.watcher, result.tsconfigFile, server.config.root); } return result.tsconfig; } catch (e) { if (e instanceof TSConfckParseError) { // tsconfig could be out of root, make sure it is watched on dev if (server && e.tsconfigFile) { ensureWatchedFile$1(server.watcher, e.tsconfigFile, server.config.root); } } throw e; } } async function reloadOnTsconfigChange(changedFile) { // server could be closed externally after a file change is detected if (!server) return; // any tsconfig.json that's added in the workspace could be closer to a code file than a previously cached one // any json file in the tsconfig cache could have been used to compile ts if (path$o$1.basename(changedFile) === 'tsconfig.json' || (changedFile.endsWith('.json') && (await tsconfckParseOptions)?.cache?.has(changedFile))) { server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`, { clear: server.config.clearScreen, timestamp: true }); // clear module graph to remove code compiled with outdated config server.moduleGraph.invalidateAll(); // reset tsconfck so that recompile works with up2date configs initTSConfck(server.config.root, true); // server may not be available if vite config is updated at the same time if (server) { // force full reload server.ws.send({ type: 'full-reload', path: '*', }); } } } var dist$1$1 = {}; var __importDefault$2 = (commonjsGlobal$2 && commonjsGlobal$2.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(dist$1$1, "__esModule", { value: true }); var Worker_1 = dist$1$1.Worker = void 0; const os_1$1 = __importDefault$2(require$$2$1); const worker_threads_1$1 = require$$1; let Worker$1 = class Worker { constructor(fn, options = {}) { this.code = genWorkerCode$1(fn); this.max = options.max || Math.max(1, os_1$1.default.cpus().length - 1); this.pool = []; this.idlePool = []; this.queue = []; } async run(...args) { const worker = await this._getAvailableWorker(); return new Promise((resolve, reject) => { worker.currentResolve = resolve; worker.currentReject = reject; worker.postMessage(args); }); } stop() { this.pool.forEach((w) => w.unref()); this.queue.forEach(([_, reject]) => reject(new Error('Main worker pool stopped before a worker was available.'))); this.pool = []; this.idlePool = []; this.queue = []; } async _getAvailableWorker() { // has idle one? if (this.idlePool.length) { return this.idlePool.shift(); } // can spawn more? if (this.pool.length < this.max) { const worker = new worker_threads_1$1.Worker(this.code, { eval: true }); worker.on('message', (res) => { worker.currentResolve && worker.currentResolve(res); worker.currentResolve = null; this._assignDoneWorker(worker); }); worker.on('error', (err) => { worker.currentReject && worker.currentReject(err); worker.currentReject = null; }); worker.on('exit', (code) => { const i = this.pool.indexOf(worker); if (i > -1) this.pool.splice(i, 1); if (code !== 0 && worker.currentReject) { worker.currentReject(new Error(`Wroker stopped with non-0 exit code ${code}`)); worker.currentReject = null; } }); this.pool.push(worker); return worker; } // no one is available, we have to wait let resolve; let reject; const onWorkerAvailablePromise = new Promise((r, rj) => { resolve = r; reject = rj; }); this.queue.push([resolve, reject]); return onWorkerAvailablePromise; } _assignDoneWorker(worker) { // someone's waiting already? if (this.queue.length) { const [resolve] = this.queue.shift(); resolve(worker); return; } // take a rest. this.idlePool.push(worker); } }; Worker_1 = dist$1$1.Worker = Worker$1; function genWorkerCode$1(fn) { return ` const doWork = ${fn.toString()} const { parentPort } = require('worker_threads') parentPort.on('message', async (args) => { const res = await doWork(...args) parentPort.postMessage(res) }) `; } let terserPath; const loadTerserPath = (root) => { if (terserPath) return terserPath; try { terserPath = requireResolveFromRootWithFallback(root, 'terser'); } catch (e) { if (e.code === 'MODULE_NOT_FOUND') { throw new Error('terser not found. Since Vite v3, terser has become an optional dependency. You need to install it.'); } else { const message = new Error(`terser failed to load:\n${e.message}`); message.stack = e.stack + '\n' + message.stack; throw message; } } return terserPath; }; function terserPlugin(config) { const makeWorker = () => new Worker_1(async (terserPath, code, options) => { // test fails when using `import`. maybe related: https://github.com/nodejs/node/issues/43205 // eslint-disable-next-line no-restricted-globals -- this function runs inside cjs const terser = require$2(terserPath); return terser.minify(code, options); }); let worker; return { name: 'vite:terser', async renderChunk(code, _chunk, outputOptions) { // This plugin is included for any non-false value of config.build.minify, // so that normal chunks can use the preferred minifier, and legacy chunks // can use terser. if (config.build.minify !== 'terser' && // @ts-expect-error injected by @vitejs/plugin-legacy !outputOptions.__vite_force_terser__) { return null; } // Do not minify ES lib output since that would remove pure annotations // and break tree-shaking. if (config.build.lib && outputOptions.format === 'es') { return null; } // Lazy load worker. worker || (worker = makeWorker()); const terserPath = loadTerserPath(config.root); const res = await worker.run(terserPath, code, { safari10: true, ...config.build.terserOptions, sourceMap: !!outputOptions.sourcemap, module: outputOptions.format.startsWith('es'), toplevel: outputOptions.format === 'cjs', }); return { code: res.code, map: res.map, }; }, closeBundle() { worker?.stop(); }, }; } var json$1 = JSON; var isArray$1$1 = Array.isArray || function (x) { return {}.toString.call(x) === '[object Array]'; }; var objectKeys = Object.keys || function (obj) { var has = Object.prototype.hasOwnProperty || function () { return true; }; var keys = []; for (var key in obj) { if (has.call(obj, key)) { keys.push(key); } } return keys; }; var jsonStableStringify = function (obj, opts) { if (!opts) { opts = {}; } if (typeof opts === 'function') { opts = { cmp: opts }; } var space = opts.space || ''; if (typeof space === 'number') { space = Array(space + 1).join(' '); } var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false; var replacer = opts.replacer || function (key, value) { return value; }; var cmp = opts.cmp && (function (f) { return function (node) { return function (a, b) { var aobj = { key: a, value: node[a] }; var bobj = { key: b, value: node[b] }; return f(aobj, bobj); }; }; }(opts.cmp)); var seen = []; return (function stringify(parent, key, node, level) { var indent = space ? '\n' + new Array(level + 1).join(space) : ''; var colonSeparator = space ? ': ' : ':'; if (node && node.toJSON && typeof node.toJSON === 'function') { node = node.toJSON(); } node = replacer.call(parent, key, node); if (node === undefined) { return; } if (typeof node !== 'object' || node === null) { return json$1.stringify(node); } if (isArray$1$1(node)) { var out = []; for (var i = 0; i < node.length; i++) { var item = stringify(node, i, node[i], level + 1) || json$1.stringify(null); out.push(indent + space + item); } return '[' + out.join(',') + indent + ']'; } if (seen.indexOf(node) !== -1) { if (cycles) { return json$1.stringify('__cycle__'); } throw new TypeError('Converting circular structure to JSON'); } else { seen.push(node); } var keys = objectKeys(node).sort(cmp && cmp(node)); var out = []; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = stringify(node, key, node[key], level + 1); if (!value) { continue; } var keyValue = json$1.stringify(key) + colonSeparator + value; out.push(indent + space + keyValue); } seen.splice(seen.indexOf(node), 1); return '{' + out.join(',') + indent + '}'; }({ '': obj }, '', obj, 0)); }; var jsonStableStringify$1 = /*@__PURE__*/getDefaultExportFromCjs$2(jsonStableStringify); const mimes$1 = { "ez": "application/andrew-inset", "aw": "application/applixware", "atom": "application/atom+xml", "atomcat": "application/atomcat+xml", "atomdeleted": "application/atomdeleted+xml", "atomsvc": "application/atomsvc+xml", "dwd": "application/atsc-dwd+xml", "held": "application/atsc-held+xml", "rsat": "application/atsc-rsat+xml", "bdoc": "application/bdoc", "xcs": "application/calendar+xml", "ccxml": "application/ccxml+xml", "cdfx": "application/cdfx+xml", "cdmia": "application/cdmi-capability", "cdmic": "application/cdmi-container", "cdmid": "application/cdmi-domain", "cdmio": "application/cdmi-object", "cdmiq": "application/cdmi-queue", "cu": "application/cu-seeme", "mpd": "application/dash+xml", "davmount": "application/davmount+xml", "dbk": "application/docbook+xml", "dssc": "application/dssc+der", "xdssc": "application/dssc+xml", "es": "application/ecmascript", "ecma": "application/ecmascript", "emma": "application/emma+xml", "emotionml": "application/emotionml+xml", "epub": "application/epub+zip", "exi": "application/exi", "fdt": "application/fdt+xml", "pfr": "application/font-tdpfr", "geojson": "application/geo+json", "gml": "application/gml+xml", "gpx": "application/gpx+xml", "gxf": "application/gxf", "gz": "application/gzip", "hjson": "application/hjson", "stk": "application/hyperstudio", "ink": "application/inkml+xml", "inkml": "application/inkml+xml", "ipfix": "application/ipfix", "its": "application/its+xml", "jar": "application/java-archive", "war": "application/java-archive", "ear": "application/java-archive", "ser": "application/java-serialized-object", "class": "application/java-vm", "js": "application/javascript", "mjs": "application/javascript", "json": "application/json", "map": "application/json", "json5": "application/json5", "jsonml": "application/jsonml+json", "jsonld": "application/ld+json", "lgr": "application/lgr+xml", "lostxml": "application/lost+xml", "hqx": "application/mac-binhex40", "cpt": "application/mac-compactpro", "mads": "application/mads+xml", "webmanifest": "application/manifest+json", "mrc": "application/marc", "mrcx": "application/marcxml+xml", "ma": "application/mathematica", "nb": "application/mathematica", "mb": "application/mathematica", "mathml": "application/mathml+xml", "mbox": "application/mbox", "mscml": "application/mediaservercontrol+xml", "metalink": "application/metalink+xml", "meta4": "application/metalink4+xml", "mets": "application/mets+xml", "maei": "application/mmt-aei+xml", "musd": "application/mmt-usd+xml", "mods": "application/mods+xml", "m21": "application/mp21", "mp21": "application/mp21", "mp4s": "application/mp4", "m4p": "application/mp4", "doc": "application/msword", "dot": "application/msword", "mxf": "application/mxf", "nq": "application/n-quads", "nt": "application/n-triples", "cjs": "application/node", "bin": "application/octet-stream", "dms": "application/octet-stream", "lrf": "application/octet-stream", "mar": "application/octet-stream", "so": "application/octet-stream", "dist": "application/octet-stream", "distz": "application/octet-stream", "pkg": "application/octet-stream", "bpk": "application/octet-stream", "dump": "application/octet-stream", "elc": "application/octet-stream", "deploy": "application/octet-stream", "exe": "application/octet-stream", "dll": "application/octet-stream", "deb": "application/octet-stream", "dmg": "application/octet-stream", "iso": "application/octet-stream", "img": "application/octet-stream", "msi": "application/octet-stream", "msp": "application/octet-stream", "msm": "application/octet-stream", "buffer": "application/octet-stream", "oda": "application/oda", "opf": "application/oebps-package+xml", "ogx": "application/ogg", "omdoc": "application/omdoc+xml", "onetoc": "application/onenote", "onetoc2": "application/onenote", "onetmp": "application/onenote", "onepkg": "application/onenote", "oxps": "application/oxps", "relo": "application/p2p-overlay+xml", "xer": "application/patch-ops-error+xml", "pdf": "application/pdf", "pgp": "application/pgp-encrypted", "asc": "application/pgp-signature", "sig": "application/pgp-signature", "prf": "application/pics-rules", "p10": "application/pkcs10", "p7m": "application/pkcs7-mime", "p7c": "application/pkcs7-mime", "p7s": "application/pkcs7-signature", "p8": "application/pkcs8", "ac": "application/pkix-attr-cert", "cer": "application/pkix-cert", "crl": "application/pkix-crl", "pkipath": "application/pkix-pkipath", "pki": "application/pkixcmp", "pls": "application/pls+xml", "ai": "application/postscript", "eps": "application/postscript", "ps": "application/postscript", "provx": "application/provenance+xml", "cww": "application/prs.cww", "pskcxml": "application/pskc+xml", "raml": "application/raml+yaml", "rdf": "application/rdf+xml", "owl": "application/rdf+xml", "rif": "application/reginfo+xml", "rnc": "application/relax-ng-compact-syntax", "rl": "application/resource-lists+xml", "rld": "application/resource-lists-diff+xml", "rs": "application/rls-services+xml", "rapd": "application/route-apd+xml", "sls": "application/route-s-tsid+xml", "rusd": "application/route-usd+xml", "gbr": "application/rpki-ghostbusters", "mft": "application/rpki-manifest", "roa": "application/rpki-roa", "rsd": "application/rsd+xml", "rss": "application/rss+xml", "rtf": "application/rtf", "sbml": "application/sbml+xml", "scq": "application/scvp-cv-request", "scs": "application/scvp-cv-response", "spq": "application/scvp-vp-request", "spp": "application/scvp-vp-response", "sdp": "application/sdp", "senmlx": "application/senml+xml", "sensmlx": "application/sensml+xml", "setpay": "application/set-payment-initiation", "setreg": "application/set-registration-initiation", "shf": "application/shf+xml", "siv": "application/sieve", "sieve": "application/sieve", "smi": "application/smil+xml", "smil": "application/smil+xml", "rq": "application/sparql-query", "srx": "application/sparql-results+xml", "gram": "application/srgs", "grxml": "application/srgs+xml", "sru": "application/sru+xml", "ssdl": "application/ssdl+xml", "ssml": "application/ssml+xml", "swidtag": "application/swid+xml", "tei": "application/tei+xml", "teicorpus": "application/tei+xml", "tfi": "application/thraud+xml", "tsd": "application/timestamped-data", "toml": "application/toml", "trig": "application/trig", "ttml": "application/ttml+xml", "ubj": "application/ubjson", "rsheet": "application/urc-ressheet+xml", "td": "application/urc-targetdesc+xml", "vxml": "application/voicexml+xml", "wasm": "application/wasm", "wgt": "application/widget", "hlp": "application/winhlp", "wsdl": "application/wsdl+xml", "wspolicy": "application/wspolicy+xml", "xaml": "application/xaml+xml", "xav": "application/xcap-att+xml", "xca": "application/xcap-caps+xml", "xdf": "application/xcap-diff+xml", "xel": "application/xcap-el+xml", "xns": "application/xcap-ns+xml", "xenc": "application/xenc+xml", "xhtml": "application/xhtml+xml", "xht": "application/xhtml+xml", "xlf": "application/xliff+xml", "xml": "application/xml", "xsl": "application/xml", "xsd": "application/xml", "rng": "application/xml", "dtd": "application/xml-dtd", "xop": "application/xop+xml", "xpl": "application/xproc+xml", "xslt": "application/xml", "xspf": "application/xspf+xml", "mxml": "application/xv+xml", "xhvml": "application/xv+xml", "xvml": "application/xv+xml", "xvm": "application/xv+xml", "yang": "application/yang", "yin": "application/yin+xml", "zip": "application/zip", "3gpp": "video/3gpp", "adp": "audio/adpcm", "amr": "audio/amr", "au": "audio/basic", "snd": "audio/basic", "mid": "audio/midi", "midi": "audio/midi", "kar": "audio/midi", "rmi": "audio/midi", "mxmf": "audio/mobile-xmf", "mp3": "audio/mpeg", "m4a": "audio/mp4", "mp4a": "audio/mp4", "mpga": "audio/mpeg", "mp2": "audio/mpeg", "mp2a": "audio/mpeg", "m2a": "audio/mpeg", "m3a": "audio/mpeg", "oga": "audio/ogg", "ogg": "audio/ogg", "spx": "audio/ogg", "opus": "audio/ogg", "s3m": "audio/s3m", "sil": "audio/silk", "wav": "audio/wav", "weba": "audio/webm", "xm": "audio/xm", "ttc": "font/collection", "otf": "font/otf", "ttf": "font/ttf", "woff": "font/woff", "woff2": "font/woff2", "exr": "image/aces", "apng": "image/apng", "avif": "image/avif", "bmp": "image/bmp", "cgm": "image/cgm", "drle": "image/dicom-rle", "emf": "image/emf", "fits": "image/fits", "g3": "image/g3fax", "gif": "image/gif", "heic": "image/heic", "heics": "image/heic-sequence", "heif": "image/heif", "heifs": "image/heif-sequence", "hej2": "image/hej2k", "hsj2": "image/hsj2", "ief": "image/ief", "jls": "image/jls", "jp2": "image/jp2", "jpg2": "image/jp2", "jpeg": "image/jpeg", "jpg": "image/jpeg", "jpe": "image/jpeg", "jph": "image/jph", "jhc": "image/jphc", "jpm": "image/jpm", "jpx": "image/jpx", "jpf": "image/jpx", "jxr": "image/jxr", "jxra": "image/jxra", "jxrs": "image/jxrs", "jxs": "image/jxs", "jxsc": "image/jxsc", "jxsi": "image/jxsi", "jxss": "image/jxss", "ktx": "image/ktx", "ktx2": "image/ktx2", "png": "image/png", "btif": "image/prs.btif", "pti": "image/prs.pti", "sgi": "image/sgi", "svg": "image/svg+xml", "svgz": "image/svg+xml", "t38": "image/t38", "tif": "image/tiff", "tiff": "image/tiff", "tfx": "image/tiff-fx", "webp": "image/webp", "wmf": "image/wmf", "disposition-notification": "message/disposition-notification", "u8msg": "message/global", "u8dsn": "message/global-delivery-status", "u8mdn": "message/global-disposition-notification", "u8hdr": "message/global-headers", "eml": "message/rfc822", "mime": "message/rfc822", "3mf": "model/3mf", "gltf": "model/gltf+json", "glb": "model/gltf-binary", "igs": "model/iges", "iges": "model/iges", "msh": "model/mesh", "mesh": "model/mesh", "silo": "model/mesh", "mtl": "model/mtl", "obj": "model/obj", "stpz": "model/step+zip", "stpxz": "model/step-xml+zip", "stl": "model/stl", "wrl": "model/vrml", "vrml": "model/vrml", "x3db": "model/x3d+fastinfoset", "x3dbz": "model/x3d+binary", "x3dv": "model/x3d-vrml", "x3dvz": "model/x3d+vrml", "x3d": "model/x3d+xml", "x3dz": "model/x3d+xml", "appcache": "text/cache-manifest", "manifest": "text/cache-manifest", "ics": "text/calendar", "ifb": "text/calendar", "coffee": "text/coffeescript", "litcoffee": "text/coffeescript", "css": "text/css", "csv": "text/csv", "html": "text/html", "htm": "text/html", "shtml": "text/html", "jade": "text/jade", "jsx": "text/jsx", "less": "text/less", "markdown": "text/markdown", "md": "text/markdown", "mml": "text/mathml", "mdx": "text/mdx", "n3": "text/n3", "txt": "text/plain", "text": "text/plain", "conf": "text/plain", "def": "text/plain", "list": "text/plain", "log": "text/plain", "in": "text/plain", "ini": "text/plain", "dsc": "text/prs.lines.tag", "rtx": "text/richtext", "sgml": "text/sgml", "sgm": "text/sgml", "shex": "text/shex", "slim": "text/slim", "slm": "text/slim", "spdx": "text/spdx", "stylus": "text/stylus", "styl": "text/stylus", "tsv": "text/tab-separated-values", "t": "text/troff", "tr": "text/troff", "roff": "text/troff", "man": "text/troff", "me": "text/troff", "ms": "text/troff", "ttl": "text/turtle", "uri": "text/uri-list", "uris": "text/uri-list", "urls": "text/uri-list", "vcard": "text/vcard", "vtt": "text/vtt", "yaml": "text/yaml", "yml": "text/yaml", "3gp": "video/3gpp", "3g2": "video/3gpp2", "h261": "video/h261", "h263": "video/h263", "h264": "video/h264", "m4s": "video/iso.segment", "jpgv": "video/jpeg", "jpgm": "image/jpm", "mj2": "video/mj2", "mjp2": "video/mj2", "ts": "video/mp2t", "mp4": "video/mp4", "mp4v": "video/mp4", "mpg4": "video/mp4", "mpeg": "video/mpeg", "mpg": "video/mpeg", "mpe": "video/mpeg", "m1v": "video/mpeg", "m2v": "video/mpeg", "ogv": "video/ogg", "qt": "video/quicktime", "mov": "video/quicktime", "webm": "video/webm" }; function lookup(extn) { let tmp = ('' + extn).trim().toLowerCase(); let idx = tmp.lastIndexOf('.'); return mimes$1[!~idx ? tmp : tmp.substring(++idx)]; } let BitSet$2 = class BitSet { constructor(arg) { this.bits = arg instanceof BitSet ? arg.bits.slice() : []; } add(n) { this.bits[n >> 5] |= 1 << (n & 31); } has(n) { return !!(this.bits[n >> 5] & (1 << (n & 31))); } }; let Chunk$2 = class Chunk { constructor(start, end, content) { this.start = start; this.end = end; this.original = content; this.intro = ''; this.outro = ''; this.content = content; this.storeName = false; this.edited = false; { this.previous = null; this.next = null; } } appendLeft(content) { this.outro += content; } appendRight(content) { this.intro = this.intro + content; } clone() { const chunk = new Chunk(this.start, this.end, this.original); chunk.intro = this.intro; chunk.outro = this.outro; chunk.content = this.content; chunk.storeName = this.storeName; chunk.edited = this.edited; return chunk; } contains(index) { return this.start < index && index < this.end; } eachNext(fn) { let chunk = this; while (chunk) { fn(chunk); chunk = chunk.next; } } eachPrevious(fn) { let chunk = this; while (chunk) { fn(chunk); chunk = chunk.previous; } } edit(content, storeName, contentOnly) { this.content = content; if (!contentOnly) { this.intro = ''; this.outro = ''; } this.storeName = storeName; this.edited = true; return this; } prependLeft(content) { this.outro = content + this.outro; } prependRight(content) { this.intro = content + this.intro; } split(index) { const sliceIndex = index - this.start; const originalBefore = this.original.slice(0, sliceIndex); const originalAfter = this.original.slice(sliceIndex); this.original = originalBefore; const newChunk = new Chunk(index, this.end, originalAfter); newChunk.outro = this.outro; this.outro = ''; this.end = index; if (this.edited) { // TODO is this block necessary?... newChunk.edit('', false); this.content = ''; } else { this.content = originalBefore; } newChunk.next = this.next; if (newChunk.next) newChunk.next.previous = newChunk; newChunk.previous = this; this.next = newChunk; return newChunk; } toString() { return this.intro + this.content + this.outro; } trimEnd(rx) { this.outro = this.outro.replace(rx, ''); if (this.outro.length) return true; const trimmed = this.content.replace(rx, ''); if (trimmed.length) { if (trimmed !== this.content) { this.split(this.start + trimmed.length).edit('', undefined, true); } return true; } else { this.edit('', undefined, true); this.intro = this.intro.replace(rx, ''); if (this.intro.length) return true; } } trimStart(rx) { this.intro = this.intro.replace(rx, ''); if (this.intro.length) return true; const trimmed = this.content.replace(rx, ''); if (trimmed.length) { if (trimmed !== this.content) { this.split(this.end - trimmed.length); this.edit('', undefined, true); } return true; } else { this.edit('', undefined, true); this.outro = this.outro.replace(rx, ''); if (this.outro.length) return true; } } }; function getBtoa$2 () { if (typeof window !== 'undefined' && typeof window.btoa === 'function') { return (str) => window.btoa(unescape(encodeURIComponent(str))); } else if (typeof Buffer === 'function') { return (str) => Buffer.from(str, 'utf-8').toString('base64'); } else { return () => { throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); }; } } const btoa$1$1 = /*#__PURE__*/ getBtoa$2(); let SourceMap$3 = class SourceMap { constructor(properties) { this.version = 3; this.file = properties.file; this.sources = properties.sources; this.sourcesContent = properties.sourcesContent; this.names = properties.names; this.mappings = encode$1(properties.mappings); if (typeof properties.x_google_ignoreList !== 'undefined') { this.x_google_ignoreList = properties.x_google_ignoreList; } } toString() { return JSON.stringify(this); } toUrl() { return 'data:application/json;charset=utf-8;base64,' + btoa$1$1(this.toString()); } }; function guessIndent$2(code) { const lines = code.split('\n'); const tabbed = lines.filter((line) => /^\t+/.test(line)); const spaced = lines.filter((line) => /^ {2,}/.test(line)); if (tabbed.length === 0 && spaced.length === 0) { return null; } // More lines tabbed than spaced? Assume tabs, and // default to tabs in the case of a tie (or nothing // to go on) if (tabbed.length >= spaced.length) { return '\t'; } // Otherwise, we need to guess the multiple const min = spaced.reduce((previous, current) => { const numSpaces = /^ +/.exec(current)[0].length; return Math.min(numSpaces, previous); }, Infinity); return new Array(min + 1).join(' '); } function getRelativePath$2(from, to) { const fromParts = from.split(/[/\\]/); const toParts = to.split(/[/\\]/); fromParts.pop(); // get dirname while (fromParts[0] === toParts[0]) { fromParts.shift(); toParts.shift(); } if (fromParts.length) { let i = fromParts.length; while (i--) fromParts[i] = '..'; } return fromParts.concat(toParts).join('/'); } const toString$2 = Object.prototype.toString; function isObject$1$1(thing) { return toString$2.call(thing) === '[object Object]'; } function getLocator$2(source) { const originalLines = source.split('\n'); const lineOffsets = []; for (let i = 0, pos = 0; i < originalLines.length; i++) { lineOffsets.push(pos); pos += originalLines[i].length + 1; } return function locate(index) { let i = 0; let j = lineOffsets.length; while (i < j) { const m = (i + j) >> 1; if (index < lineOffsets[m]) { j = m; } else { i = m + 1; } } const line = i - 1; const column = index - lineOffsets[line]; return { line, column }; }; } let Mappings$2 = class Mappings { constructor(hires) { this.hires = hires; this.generatedCodeLine = 0; this.generatedCodeColumn = 0; this.raw = []; this.rawSegments = this.raw[this.generatedCodeLine] = []; this.pending = null; } addEdit(sourceIndex, content, loc, nameIndex) { if (content.length) { const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; if (nameIndex >= 0) { segment.push(nameIndex); } this.rawSegments.push(segment); } else if (this.pending) { this.rawSegments.push(this.pending); } this.advance(content); this.pending = null; } addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { let originalCharIndex = chunk.start; let first = true; while (originalCharIndex < chunk.end) { if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]); } if (original[originalCharIndex] === '\n') { loc.line += 1; loc.column = 0; this.generatedCodeLine += 1; this.raw[this.generatedCodeLine] = this.rawSegments = []; this.generatedCodeColumn = 0; first = true; } else { loc.column += 1; this.generatedCodeColumn += 1; first = false; } originalCharIndex += 1; } this.pending = null; } advance(str) { if (!str) return; const lines = str.split('\n'); if (lines.length > 1) { for (let i = 0; i < lines.length - 1; i++) { this.generatedCodeLine++; this.raw[this.generatedCodeLine] = this.rawSegments = []; } this.generatedCodeColumn = 0; } this.generatedCodeColumn += lines[lines.length - 1].length; } }; const n$1 = '\n'; const warned$2 = { insertLeft: false, insertRight: false, storeName: false, }; let MagicString$2 = class MagicString { constructor(string, options = {}) { const chunk = new Chunk$2(0, string.length, string); Object.defineProperties(this, { original: { writable: true, value: string }, outro: { writable: true, value: '' }, intro: { writable: true, value: '' }, firstChunk: { writable: true, value: chunk }, lastChunk: { writable: true, value: chunk }, lastSearchedChunk: { writable: true, value: chunk }, byStart: { writable: true, value: {} }, byEnd: { writable: true, value: {} }, filename: { writable: true, value: options.filename }, indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, sourcemapLocations: { writable: true, value: new BitSet$2() }, storedNames: { writable: true, value: {} }, indentStr: { writable: true, value: undefined }, ignoreList: { writable: true, value: options.ignoreList }, }); this.byStart[0] = chunk; this.byEnd[string.length] = chunk; } addSourcemapLocation(char) { this.sourcemapLocations.add(char); } append(content) { if (typeof content !== 'string') throw new TypeError('outro content must be a string'); this.outro += content; return this; } appendLeft(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byEnd[index]; if (chunk) { chunk.appendLeft(content); } else { this.intro += content; } return this; } appendRight(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byStart[index]; if (chunk) { chunk.appendRight(content); } else { this.outro += content; } return this; } clone() { const cloned = new MagicString(this.original, { filename: this.filename }); let originalChunk = this.firstChunk; let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); while (originalChunk) { cloned.byStart[clonedChunk.start] = clonedChunk; cloned.byEnd[clonedChunk.end] = clonedChunk; const nextOriginalChunk = originalChunk.next; const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); if (nextClonedChunk) { clonedChunk.next = nextClonedChunk; nextClonedChunk.previous = clonedChunk; clonedChunk = nextClonedChunk; } originalChunk = nextOriginalChunk; } cloned.lastChunk = clonedChunk; if (this.indentExclusionRanges) { cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); } cloned.sourcemapLocations = new BitSet$2(this.sourcemapLocations); cloned.intro = this.intro; cloned.outro = this.outro; return cloned; } generateDecodedMap(options) { options = options || {}; const sourceIndex = 0; const names = Object.keys(this.storedNames); const mappings = new Mappings$2(options.hires); const locate = getLocator$2(this.original); if (this.intro) { mappings.advance(this.intro); } this.firstChunk.eachNext((chunk) => { const loc = locate(chunk.start); if (chunk.intro.length) mappings.advance(chunk.intro); if (chunk.edited) { mappings.addEdit( sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1 ); } else { mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); } if (chunk.outro.length) mappings.advance(chunk.outro); }); return { file: options.file ? options.file.split(/[/\\]/).pop() : undefined, sources: [options.source ? getRelativePath$2(options.file || '', options.source) : (options.file || '')], sourcesContent: options.includeContent ? [this.original] : undefined, names, mappings: mappings.raw, x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined }; } generateMap(options) { return new SourceMap$3(this.generateDecodedMap(options)); } _ensureindentStr() { if (this.indentStr === undefined) { this.indentStr = guessIndent$2(this.original); } } _getRawIndentString() { this._ensureindentStr(); return this.indentStr; } getIndentString() { this._ensureindentStr(); return this.indentStr === null ? '\t' : this.indentStr; } indent(indentStr, options) { const pattern = /^[^\r\n]/gm; if (isObject$1$1(indentStr)) { options = indentStr; indentStr = undefined; } if (indentStr === undefined) { this._ensureindentStr(); indentStr = this.indentStr || '\t'; } if (indentStr === '') return this; // noop options = options || {}; // Process exclusion ranges const isExcluded = {}; if (options.exclude) { const exclusions = typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; exclusions.forEach((exclusion) => { for (let i = exclusion[0]; i < exclusion[1]; i += 1) { isExcluded[i] = true; } }); } let shouldIndentNextCharacter = options.indentStart !== false; const replacer = (match) => { if (shouldIndentNextCharacter) return `${indentStr}${match}`; shouldIndentNextCharacter = true; return match; }; this.intro = this.intro.replace(pattern, replacer); let charIndex = 0; let chunk = this.firstChunk; while (chunk) { const end = chunk.end; if (chunk.edited) { if (!isExcluded[charIndex]) { chunk.content = chunk.content.replace(pattern, replacer); if (chunk.content.length) { shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; } } } else { charIndex = chunk.start; while (charIndex < end) { if (!isExcluded[charIndex]) { const char = this.original[charIndex]; if (char === '\n') { shouldIndentNextCharacter = true; } else if (char !== '\r' && shouldIndentNextCharacter) { shouldIndentNextCharacter = false; if (charIndex === chunk.start) { chunk.prependRight(indentStr); } else { this._splitChunk(chunk, charIndex); chunk = chunk.next; chunk.prependRight(indentStr); } } } charIndex += 1; } } charIndex = chunk.end; chunk = chunk.next; } this.outro = this.outro.replace(pattern, replacer); return this; } insert() { throw new Error( 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)' ); } insertLeft(index, content) { if (!warned$2.insertLeft) { console.warn( 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead' ); // eslint-disable-line no-console warned$2.insertLeft = true; } return this.appendLeft(index, content); } insertRight(index, content) { if (!warned$2.insertRight) { console.warn( 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead' ); // eslint-disable-line no-console warned$2.insertRight = true; } return this.prependRight(index, content); } move(start, end, index) { if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself'); this._split(start); this._split(end); this._split(index); const first = this.byStart[start]; const last = this.byEnd[end]; const oldLeft = first.previous; const oldRight = last.next; const newRight = this.byStart[index]; if (!newRight && last === this.lastChunk) return this; const newLeft = newRight ? newRight.previous : this.lastChunk; if (oldLeft) oldLeft.next = oldRight; if (oldRight) oldRight.previous = oldLeft; if (newLeft) newLeft.next = first; if (newRight) newRight.previous = last; if (!first.previous) this.firstChunk = last.next; if (!last.next) { this.lastChunk = first.previous; this.lastChunk.next = null; } first.previous = newLeft; last.next = newRight || null; if (!newLeft) this.firstChunk = first; if (!newRight) this.lastChunk = last; return this; } overwrite(start, end, content, options) { options = options || {}; return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); } update(start, end, content, options) { if (typeof content !== 'string') throw new TypeError('replacement content must be a string'); while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; if (end > this.original.length) throw new Error('end is out of bounds'); if (start === end) throw new Error( 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead' ); this._split(start); this._split(end); if (options === true) { if (!warned$2.storeName) { console.warn( 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string' ); // eslint-disable-line no-console warned$2.storeName = true; } options = { storeName: true }; } const storeName = options !== undefined ? options.storeName : false; const overwrite = options !== undefined ? options.overwrite : false; if (storeName) { const original = this.original.slice(start, end); Object.defineProperty(this.storedNames, original, { writable: true, value: true, enumerable: true, }); } const first = this.byStart[start]; const last = this.byEnd[end]; if (first) { let chunk = first; while (chunk !== last) { if (chunk.next !== this.byStart[chunk.end]) { throw new Error('Cannot overwrite across a split point'); } chunk = chunk.next; chunk.edit('', false); } first.edit(content, storeName, !overwrite); } else { // must be inserting at the end const newChunk = new Chunk$2(start, end, '').edit(content, storeName); // TODO last chunk in the array may not be the last chunk, if it's moved... last.next = newChunk; newChunk.previous = last; } return this; } prepend(content) { if (typeof content !== 'string') throw new TypeError('outro content must be a string'); this.intro = content + this.intro; return this; } prependLeft(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byEnd[index]; if (chunk) { chunk.prependLeft(content); } else { this.intro = content + this.intro; } return this; } prependRight(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byStart[index]; if (chunk) { chunk.prependRight(content); } else { this.outro = content + this.outro; } return this; } remove(start, end) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; if (start === end) return this; if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); if (start > end) throw new Error('end must be greater than start'); this._split(start); this._split(end); let chunk = this.byStart[start]; while (chunk) { chunk.intro = ''; chunk.outro = ''; chunk.edit(''); chunk = end > chunk.end ? this.byStart[chunk.end] : null; } return this; } lastChar() { if (this.outro.length) return this.outro[this.outro.length - 1]; let chunk = this.lastChunk; do { if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; if (chunk.content.length) return chunk.content[chunk.content.length - 1]; if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; } while ((chunk = chunk.previous)); if (this.intro.length) return this.intro[this.intro.length - 1]; return ''; } lastLine() { let lineIndex = this.outro.lastIndexOf(n$1); if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); let lineStr = this.outro; let chunk = this.lastChunk; do { if (chunk.outro.length > 0) { lineIndex = chunk.outro.lastIndexOf(n$1); if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; lineStr = chunk.outro + lineStr; } if (chunk.content.length > 0) { lineIndex = chunk.content.lastIndexOf(n$1); if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; lineStr = chunk.content + lineStr; } if (chunk.intro.length > 0) { lineIndex = chunk.intro.lastIndexOf(n$1); if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; lineStr = chunk.intro + lineStr; } } while ((chunk = chunk.previous)); lineIndex = this.intro.lastIndexOf(n$1); if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; return this.intro + lineStr; } slice(start = 0, end = this.original.length) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; let result = ''; // find start chunk let chunk = this.firstChunk; while (chunk && (chunk.start > start || chunk.end <= start)) { // found end chunk before start if (chunk.start < end && chunk.end >= end) { return result; } chunk = chunk.next; } if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); const startChunk = chunk; while (chunk) { if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { result += chunk.intro; } const containsEnd = chunk.start < end && chunk.end >= end; if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); const sliceStart = startChunk === chunk ? start - chunk.start : 0; const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; result += chunk.content.slice(sliceStart, sliceEnd); if (chunk.outro && (!containsEnd || chunk.end === end)) { result += chunk.outro; } if (containsEnd) { break; } chunk = chunk.next; } return result; } // TODO deprecate this? not really very useful snip(start, end) { const clone = this.clone(); clone.remove(0, start); clone.remove(end, clone.original.length); return clone; } _split(index) { if (this.byStart[index] || this.byEnd[index]) return; let chunk = this.lastSearchedChunk; const searchForward = index > chunk.end; while (chunk) { if (chunk.contains(index)) return this._splitChunk(chunk, index); chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; } } _splitChunk(chunk, index) { if (chunk.edited && chunk.content.length) { // zero-length edited chunks are a special case (overlapping replacements) const loc = getLocator$2(this.original)(index); throw new Error( `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")` ); } const newChunk = chunk.split(index); this.byEnd[index] = chunk; this.byStart[index] = newChunk; this.byEnd[newChunk.end] = newChunk; if (chunk === this.lastChunk) this.lastChunk = newChunk; this.lastSearchedChunk = chunk; return true; } toString() { let str = this.intro; let chunk = this.firstChunk; while (chunk) { str += chunk.toString(); chunk = chunk.next; } return str + this.outro; } isEmpty() { let chunk = this.firstChunk; do { if ( (chunk.intro.length && chunk.intro.trim()) || (chunk.content.length && chunk.content.trim()) || (chunk.outro.length && chunk.outro.trim()) ) return false; } while ((chunk = chunk.next)); return true; } length() { let chunk = this.firstChunk; let length = 0; do { length += chunk.intro.length + chunk.content.length + chunk.outro.length; } while ((chunk = chunk.next)); return length; } trimLines() { return this.trim('[\\r\\n]'); } trim(charType) { return this.trimStart(charType).trimEnd(charType); } trimEndAborted(charType) { const rx = new RegExp((charType || '\\s') + '+$'); this.outro = this.outro.replace(rx, ''); if (this.outro.length) return true; let chunk = this.lastChunk; do { const end = chunk.end; const aborted = chunk.trimEnd(rx); // if chunk was trimmed, we have a new lastChunk if (chunk.end !== end) { if (this.lastChunk === chunk) { this.lastChunk = chunk.next; } this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) return true; chunk = chunk.previous; } while (chunk); return false; } trimEnd(charType) { this.trimEndAborted(charType); return this; } trimStartAborted(charType) { const rx = new RegExp('^' + (charType || '\\s') + '+'); this.intro = this.intro.replace(rx, ''); if (this.intro.length) return true; let chunk = this.firstChunk; do { const end = chunk.end; const aborted = chunk.trimStart(rx); if (chunk.end !== end) { // special case... if (chunk === this.lastChunk) this.lastChunk = chunk.next; this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) return true; chunk = chunk.next; } while (chunk); return false; } trimStart(charType) { this.trimStartAborted(charType); return this; } hasChanged() { return this.original !== this.toString(); } _replaceRegexp(searchValue, replacement) { function getReplacement(match, str) { if (typeof replacement === 'string') { return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter if (i === '$') return '$'; if (i === '&') return match[0]; const num = +i; if (num < match.length) return match[+i]; return `$${i}`; }); } else { return replacement(...match, match.index, str, match.groups); } } function matchAll(re, str) { let match; const matches = []; while ((match = re.exec(str))) { matches.push(match); } return matches; } if (searchValue.global) { const matches = matchAll(searchValue, this.original); matches.forEach((match) => { if (match.index != null) this.overwrite( match.index, match.index + match[0].length, getReplacement(match, this.original) ); }); } else { const match = this.original.match(searchValue); if (match && match.index != null) this.overwrite( match.index, match.index + match[0].length, getReplacement(match, this.original) ); } return this; } _replaceString(string, replacement) { const { original } = this; const index = original.indexOf(string); if (index !== -1) { this.overwrite(index, index + string.length, replacement); } return this; } replace(searchValue, replacement) { if (typeof searchValue === 'string') { return this._replaceString(searchValue, replacement); } return this._replaceRegexp(searchValue, replacement); } _replaceAllString(string, replacement) { const { original } = this; const stringLength = string.length; for ( let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength) ) { this.overwrite(index, index + stringLength, replacement); } return this; } replaceAll(searchValue, replacement) { if (typeof searchValue === 'string') { return this._replaceAllString(searchValue, replacement); } if (!searchValue.global) { throw new TypeError( 'MagicString.prototype.replaceAll called with a non-global RegExp argument' ); } return this._replaceRegexp(searchValue, replacement); } }; const assetUrlRE = /__VITE_ASSET__([a-z\d]+)__(?:\$_(.*?)__)?/g; const rawRE = /(?:\?|&)raw(?:&|$)/; const urlRE = /(\?|&)url(?:&|$)/; const jsSourceMapRE = /\.[cm]?js\.map$/; const unnededFinalQueryCharRE = /[?&]$/; const assetCache = new WeakMap(); const generatedAssets = new WeakMap(); // add own dictionary entry by directly assigning mrmime function registerCustomMime() { // https://github.com/lukeed/mrmime/issues/3 mimes$1['ico'] = 'image/x-icon'; // https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers#flac mimes$1['flac'] = 'audio/flac'; // mrmime and mime-db is not released yet: https://github.com/jshttp/mime-db/commit/c9242a9b7d4bb25d7a0c9244adec74aeef08d8a1 mimes$1['aac'] = 'audio/aac'; // https://wiki.xiph.org/MIME_Types_and_File_Extensions#.opus_-_audio/ogg mimes$1['opus'] = 'audio/ogg'; // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types mimes$1['eot'] = 'application/vnd.ms-fontobject'; } function renderAssetUrlInJS(ctx, config, chunk, opts, code) { const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, config.isWorker); let match; let s; // Urls added with JS using e.g. // imgElement.src = "__VITE_ASSET__5aa0ddc0__" are using quotes // Urls added in CSS that is imported in JS end up like // var inlined = ".inlined{color:green;background:url(__VITE_ASSET__5aa0ddc0__)}\n"; // In both cases, the wrapping should already be fine assetUrlRE.lastIndex = 0; while ((match = assetUrlRE.exec(code))) { s || (s = new MagicString$2(code)); const [full, referenceId, postfix = ''] = match; const file = ctx.getFileName(referenceId); chunk.viteMetadata.importedAssets.add(cleanUrl$1(file)); const filename = file + postfix; const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', config, toRelativeRuntime); const replacementString = typeof replacement === 'string' ? JSON.stringify(replacement).slice(1, -1) : `"+${replacement.runtime}+"`; s.update(match.index, match.index + full.length, replacementString); } // Replace __VITE_PUBLIC_ASSET__5aa0ddc0__ with absolute paths const publicAssetUrlMap = publicAssetUrlCache.get(config); publicAssetUrlRE.lastIndex = 0; while ((match = publicAssetUrlRE.exec(code))) { s || (s = new MagicString$2(code)); const [full, hash] = match; const publicUrl = publicAssetUrlMap.get(hash).slice(1); const replacement = toOutputFilePathInJS(publicUrl, 'public', chunk.fileName, 'js', config, toRelativeRuntime); const replacementString = typeof replacement === 'string' ? JSON.stringify(replacement).slice(1, -1) : `"+${replacement.runtime}+"`; s.update(match.index, match.index + full.length, replacementString); } return s; } /** * Also supports loading plain strings with import text from './foo.txt?raw' */ function assetPlugin(config) { registerCustomMime(); return { name: 'vite:asset', buildStart() { assetCache.set(config, new Map()); generatedAssets.set(config, new Map()); }, resolveId(id) { if (!config.assetsInclude(cleanUrl$1(id))) { return; } // imports to absolute urls pointing to files in /public // will fail to resolve in the main resolver. handle them here. const publicFile = checkPublicFile(id, config); if (publicFile) { return id; } }, async load(id) { if (id[0] === '\0') { // Rollup convention, this id should be handled by the // plugin that marked it with \0 return; } // raw requests, read from disk if (rawRE.test(id)) { const file = checkPublicFile(id, config) || cleanUrl$1(id); // raw query, read file and return as string return `export default ${JSON.stringify(await promises.readFile(file, 'utf-8'))}`; } if (!config.assetsInclude(cleanUrl$1(id)) && !urlRE.test(id)) { return; } id = id.replace(urlRE, '$1').replace(unnededFinalQueryCharRE, ''); const url = await fileToUrl(id, config, this); return `export default ${JSON.stringify(url)}`; }, renderChunk(code, chunk, opts) { const s = renderAssetUrlInJS(this, config, chunk, opts, code); if (s) { return { code: s.toString(), map: config.build.sourcemap ? s.generateMap({ hires: true }) : null, }; } else { return null; } }, generateBundle(_, bundle) { // do not emit assets for SSR build if (config.command === 'build' && config.build.ssr && !config.build.ssrEmitAssets) { for (const file in bundle) { if (bundle[file].type === 'asset' && !file.endsWith('ssr-manifest.json') && !jsSourceMapRE.test(file)) { delete bundle[file]; } } } }, }; } function checkPublicFile(url, { publicDir }) { // note if the file is in /public, the resolver would have returned it // as-is so it's not going to be a fully resolved path. if (!publicDir || url[0] !== '/') { return; } const publicFile = path$o$1.join(publicDir, cleanUrl$1(url)); if (!publicFile.startsWith(publicDir)) { // can happen if URL starts with '../' return; } if (fs$l__default.existsSync(publicFile)) { return publicFile; } else { return; } } async function fileToUrl(id, config, ctx) { if (config.command === 'serve') { return fileToDevUrl(id, config); } else { return fileToBuiltUrl(id, config, ctx); } } function fileToDevUrl(id, config) { let rtn; if (checkPublicFile(id, config)) { // in public dir, keep the url as-is rtn = id; } else if (id.startsWith(config.root)) { // in project root, infer short public path rtn = '/' + path$o$1.posix.relative(config.root, id); } else { // outside of project root, use absolute fs path // (this is special handled by the serve static middleware rtn = path$o$1.posix.join(FS_PREFIX, id); } const base = joinUrlSegments(config.server?.origin ?? '', config.base); return joinUrlSegments(base, removeLeadingSlash(rtn)); } function getPublicAssetFilename(hash, config) { return publicAssetUrlCache.get(config)?.get(hash); } const publicAssetUrlCache = new WeakMap(); const publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g; function publicFileToBuiltUrl(url, config) { if (config.command !== 'build') { // We don't need relative base or renderBuiltUrl support during dev return joinUrlSegments(config.base, url); } const hash = getHash(url); let cache = publicAssetUrlCache.get(config); if (!cache) { cache = new Map(); publicAssetUrlCache.set(config, cache); } if (!cache.get(hash)) { cache.set(hash, url); } return `__VITE_PUBLIC_ASSET__${hash}__`; } const GIT_LFS_PREFIX = Buffer$1.from('version https://git-lfs.github.com'); function isGitLfsPlaceholder(content) { if (content.length < GIT_LFS_PREFIX.length) return false; // Check whether the content begins with the characteristic string of Git LFS placeholders return GIT_LFS_PREFIX.compare(content, 0, GIT_LFS_PREFIX.length) === 0; } /** * Register an asset to be emitted as part of the bundle (if necessary) * and returns the resolved public URL */ async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false) { if (!skipPublicCheck && checkPublicFile(id, config)) { return publicFileToBuiltUrl(id, config); } const cache = assetCache.get(config); const cached = cache.get(id); if (cached) { return cached; } const file = cleanUrl$1(id); const content = await promises.readFile(file); let url; if (config.build.lib || (!file.endsWith('.svg') && !file.endsWith('.html') && content.length < Number(config.build.assetsInlineLimit) && !isGitLfsPlaceholder(content))) { if (config.build.lib && isGitLfsPlaceholder(content)) { config.logger.warn(colors$1$1.yellow(`Inlined file ${id} was not downloaded via Git LFS`)); } const mimeType = lookup(file) ?? 'application/octet-stream'; // base64 inlined as a string url = `data:${mimeType};base64,${content.toString('base64')}`; } else { // emit as asset const { search, hash } = parse$k(id); const postfix = (search || '') + (hash || ''); const referenceId = pluginContext.emitFile({ // Ignore directory structure for asset file names name: path$o$1.basename(file), type: 'asset', source: content, }); const originalName = normalizePath$3$1(path$o$1.relative(config.root, file)); generatedAssets.get(config).set(referenceId, { originalName }); url = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`; // TODO_BASE } cache.set(id, url); return url; } async function urlToBuiltUrl(url, importer, config, pluginContext) { if (checkPublicFile(url, config)) { return publicFileToBuiltUrl(url, config); } const file = url[0] === '/' ? path$o$1.join(config.root, url) : path$o$1.join(path$o$1.dirname(importer), url); return fileToBuiltUrl(file, config, pluginContext, // skip public check since we just did it above true); } function manifestPlugin(config) { const manifest = {}; let outputCount; return { name: 'vite:manifest', buildStart() { outputCount = 0; }, generateBundle({ format }, bundle) { function getChunkName(chunk) { if (chunk.facadeModuleId) { let name = normalizePath$3$1(path$o$1.relative(config.root, chunk.facadeModuleId)); if (format === 'system' && !chunk.name.includes('-legacy')) { const ext = path$o$1.extname(name); const endPos = ext.length !== 0 ? -ext.length : undefined; name = name.slice(0, endPos) + `-legacy` + ext; } return name.replace(/\0/g, ''); } else { return `_` + path$o$1.basename(chunk.fileName); } } function getInternalImports(imports) { const filteredImports = []; for (const file of imports) { if (bundle[file] === undefined) { continue; } filteredImports.push(getChunkName(bundle[file])); } return filteredImports; } function createChunk(chunk) { const manifestChunk = { file: chunk.fileName, }; if (chunk.facadeModuleId) { manifestChunk.src = getChunkName(chunk); } if (chunk.isEntry) { manifestChunk.isEntry = true; } if (chunk.isDynamicEntry) { manifestChunk.isDynamicEntry = true; } if (chunk.imports.length) { const internalImports = getInternalImports(chunk.imports); if (internalImports.length > 0) { manifestChunk.imports = internalImports; } } if (chunk.dynamicImports.length) { const internalImports = getInternalImports(chunk.dynamicImports); if (internalImports.length > 0) { manifestChunk.dynamicImports = internalImports; } } if (chunk.viteMetadata?.importedCss.size) { manifestChunk.css = [...chunk.viteMetadata.importedCss]; } if (chunk.viteMetadata?.importedAssets.size) { manifestChunk.assets = [...chunk.viteMetadata.importedAssets]; } return manifestChunk; } function createAsset(asset, src, isEntry) { const manifestChunk = { file: asset.fileName, src, }; if (isEntry) manifestChunk.isEntry = true; return manifestChunk; } const fileNameToAssetMeta = new Map(); const assets = generatedAssets.get(config); assets.forEach((asset, referenceId) => { const fileName = this.getFileName(referenceId); fileNameToAssetMeta.set(fileName, asset); }); const fileNameToAsset = new Map(); for (const file in bundle) { const chunk = bundle[file]; if (chunk.type === 'chunk') { manifest[getChunkName(chunk)] = createChunk(chunk); } else if (chunk.type === 'asset' && typeof chunk.name === 'string') { // Add every unique asset to the manifest, keyed by its original name const assetMeta = fileNameToAssetMeta.get(chunk.fileName); const src = assetMeta?.originalName ?? chunk.name; const asset = createAsset(chunk, src, assetMeta?.isEntry); manifest[src] = asset; fileNameToAsset.set(chunk.fileName, asset); } } // Add deduplicated assets to the manifest assets.forEach(({ originalName }, referenceId) => { if (!manifest[originalName]) { const fileName = this.getFileName(referenceId); const asset = fileNameToAsset.get(fileName); if (asset) { manifest[originalName] = asset; } } }); outputCount++; const output = config.build.rollupOptions?.output; const outputLength = Array.isArray(output) ? output.length : 1; if (outputCount >= outputLength) { this.emitFile({ fileName: typeof config.build.manifest === 'string' ? config.build.manifest : 'manifest.json', type: 'asset', source: jsonStableStringify$1(manifest, { space: 2 }), }); } }, }; } // This is based on @rollup/plugin-data-uri const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/; const base64RE = /base64/i; const dataUriPrefix = `\0/@data-uri/`; /** * Build only, since importing from a data URI works natively. */ function dataURIPlugin() { let resolved; return { name: 'vite:data-uri', buildStart() { resolved = new Map(); }, resolveId(id) { if (!dataUriRE.test(id)) { return; } const uri = new URL$3(id); if (uri.protocol !== 'data:') { return; } const match = uri.pathname.match(dataUriRE); if (!match) { return; } const [, mime, format, data] = match; if (mime !== 'text/javascript') { throw new Error(`data URI with non-JavaScript mime type is not supported. If you're using legacy JavaScript MIME types (such as 'application/javascript'), please use 'text/javascript' instead.`); } // decode data const base64 = format && base64RE.test(format.substring(1)); const content = base64 ? Buffer.from(data, 'base64').toString('utf-8') : data; resolved.set(id, content); return dataUriPrefix + id; }, load(id) { if (id.startsWith(dataUriPrefix)) { return resolved.get(id.slice(dataUriPrefix.length)); } }, }; } /* es-module-lexer 1.2.1 */ const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$e(E,g="@"){if(!C)return init$1.then((()=>parse$e(E)));const I=E.length+1,o=(C.__heap_base.value||C.__heap_base)+4*I-C.memory.buffer.byteLength;o>0&&C.memory.grow(Math.ceil(o/65536));const D=C.sa(I-1);if((A?B:Q)(E,new Uint16Array(C.memory.buffer,D,I)),!C.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,C.e()).split("\n").length}:${C.e()-E.lastIndexOf("\n",C.e()-1)}`),{idx:C.e()});const K=[],k=[];for(;C.ri();){const A=C.is(),Q=C.ie(),B=C.ai(),g=C.id(),I=C.ss(),o=C.se();let D;C.ip()&&(D=J(E.slice(-1===g?A-1:A,-1===g?Q+1:Q))),K.push({n:D,s:A,e:Q,ss:I,se:o,d:g,a:B});}for(;C.re();){const A=C.es(),Q=C.ee(),B=C.els(),g=C.ele(),I=E.slice(A,Q),o=I[0],D=B<0?void 0:E.slice(B,g),K=D?D[0]:"";k.push({s:A,e:Q,ls:B,le:g,n:'"'===o||"'"===o?J(I):I,ln:'"'===K||"'"===K?J(D):D});}function J(A){try{return (0, eval)(A)}catch(A){}}return [K,k,!!C.f()]}function Q(A,Q){const B=A.length;let C=0;for(;C>>8;}}function B(A,Q){const B=A.length;let C=0;for(;CA.charCodeAt(0))))).then(WebAssembly.instantiate).then((({exports:A})=>{C=A;}));var E$1; var convertSourceMap$1$1 = {}; (function (exports) { Object.defineProperty(exports, 'commentRegex', { get: function getCommentRegex () { // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data. return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg; } }); Object.defineProperty(exports, 'mapFileCommentRegex', { get: function getMapFileCommentRegex () { // Matches sourceMappingURL in either // or /* comment styles. return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg; } }); var decodeBase64; if (typeof Buffer !== 'undefined') { if (typeof Buffer.from === 'function') { decodeBase64 = decodeBase64WithBufferFrom; } else { decodeBase64 = decodeBase64WithNewBuffer; } } else { decodeBase64 = decodeBase64WithAtob; } function decodeBase64WithBufferFrom(base64) { return Buffer.from(base64, 'base64').toString(); } function decodeBase64WithNewBuffer(base64) { if (typeof value === 'number') { throw new TypeError('The value to decode must not be of type number.'); } return new Buffer(base64, 'base64').toString(); } function decodeBase64WithAtob(base64) { return decodeURIComponent(escape(atob(base64))); } function stripComment(sm) { return sm.split(',').pop(); } function readFromFileMap(sm, read) { var r = exports.mapFileCommentRegex.exec(sm); // for some odd reason //# .. captures in 1 and /* .. */ in 2 var filename = r[1] || r[2]; try { var sm = read(filename); if (sm != null && typeof sm.catch === 'function') { return sm.catch(throwError); } else { return sm; } } catch (e) { throwError(e); } function throwError(e) { throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack); } } function Converter (sm, opts) { opts = opts || {}; if (opts.hasComment) { sm = stripComment(sm); } if (opts.encoding === 'base64') { sm = decodeBase64(sm); } else if (opts.encoding === 'uri') { sm = decodeURIComponent(sm); } if (opts.isJSON || opts.encoding) { sm = JSON.parse(sm); } this.sourcemap = sm; } Converter.prototype.toJSON = function (space) { return JSON.stringify(this.sourcemap, null, space); }; if (typeof Buffer !== 'undefined') { if (typeof Buffer.from === 'function') { Converter.prototype.toBase64 = encodeBase64WithBufferFrom; } else { Converter.prototype.toBase64 = encodeBase64WithNewBuffer; } } else { Converter.prototype.toBase64 = encodeBase64WithBtoa; } function encodeBase64WithBufferFrom() { var json = this.toJSON(); return Buffer.from(json, 'utf8').toString('base64'); } function encodeBase64WithNewBuffer() { var json = this.toJSON(); if (typeof json === 'number') { throw new TypeError('The json to encode must not be of type number.'); } return new Buffer(json, 'utf8').toString('base64'); } function encodeBase64WithBtoa() { var json = this.toJSON(); return btoa(unescape(encodeURIComponent(json))); } Converter.prototype.toURI = function () { var json = this.toJSON(); return encodeURIComponent(json); }; Converter.prototype.toComment = function (options) { var encoding, content, data; if (options != null && options.encoding === 'uri') { encoding = ''; content = this.toURI(); } else { encoding = ';base64'; content = this.toBase64(); } data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content; return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; }; // returns copy instead of original Converter.prototype.toObject = function () { return JSON.parse(this.toJSON()); }; Converter.prototype.addProperty = function (key, value) { if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead'); return this.setProperty(key, value); }; Converter.prototype.setProperty = function (key, value) { this.sourcemap[key] = value; return this; }; Converter.prototype.getProperty = function (key) { return this.sourcemap[key]; }; exports.fromObject = function (obj) { return new Converter(obj); }; exports.fromJSON = function (json) { return new Converter(json, { isJSON: true }); }; exports.fromURI = function (uri) { return new Converter(uri, { encoding: 'uri' }); }; exports.fromBase64 = function (base64) { return new Converter(base64, { encoding: 'base64' }); }; exports.fromComment = function (comment) { var m, encoding; comment = comment .replace(/^\/\*/g, '//') .replace(/\*\/$/g, ''); m = exports.commentRegex.exec(comment); encoding = m && m[4] || 'uri'; return new Converter(comment, { encoding: encoding, hasComment: true }); }; function makeConverter(sm) { return new Converter(sm, { isJSON: true }); } exports.fromMapFileComment = function (comment, read) { if (typeof read === 'string') { throw new Error( 'String directory paths are no longer supported with `fromMapFileComment`\n' + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' ) } var sm = readFromFileMap(comment, read); if (sm != null && typeof sm.then === 'function') { return sm.then(makeConverter); } else { return makeConverter(sm); } }; // Finds last sourcemap comment in file or returns null if none was found exports.fromSource = function (content) { var m = content.match(exports.commentRegex); return m ? exports.fromComment(m.pop()) : null; }; // Finds last sourcemap comment in file or returns null if none was found exports.fromMapFileSource = function (content, read) { if (typeof read === 'string') { throw new Error( 'String directory paths are no longer supported with `fromMapFileSource`\n' + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' ) } var m = content.match(exports.mapFileCommentRegex); return m ? exports.fromMapFileComment(m.pop(), read) : null; }; exports.removeComments = function (src) { return src.replace(exports.commentRegex, ''); }; exports.removeMapFileComments = function (src) { return src.replace(exports.mapFileCommentRegex, ''); }; exports.generateMapFileComment = function (file, options) { var data = 'sourceMappingURL=' + file; return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; }; } (convertSourceMap$1$1)); var convertSourceMap = /*@__PURE__*/getDefaultExportFromCjs$2(convertSourceMap$1$1); const debug$e = createDebugger$1('vite:sourcemap', { onlyWhenFocused: true, }); // Virtual modules should be prefixed with a null byte to avoid a // false positive "missing source" warning. We also check for certain // prefixes used for special handling in esbuildDepPlugin. const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/; async function injectSourcesContent(map, file, logger) { let sourceRoot; try { // The source root is undefined for virtual modules and permission errors. sourceRoot = await promises.realpath(path$o$1.resolve(path$o$1.dirname(file), map.sourceRoot || '')); } catch { } const missingSources = []; map.sourcesContent = await Promise.all(map.sources.map((sourcePath) => { if (sourcePath && !virtualSourceRE.test(sourcePath)) { sourcePath = decodeURI(sourcePath); if (sourceRoot) { sourcePath = path$o$1.resolve(sourceRoot, sourcePath); } return promises.readFile(sourcePath, 'utf-8').catch(() => { missingSources.push(sourcePath); return null; }); } return null; })); // Use this command… // DEBUG="vite:sourcemap" vite build // …to log the missing sources. if (missingSources.length) { logger.warnOnce(`Sourcemap for "${file}" points to missing source files`); debug$e?.(`Missing sources:\n ` + missingSources.join(`\n `)); } } function genSourceMapUrl(map) { if (typeof map !== 'string') { map = JSON.stringify(map); } return `data:application/json;base64,${Buffer.from(map).toString('base64')}`; } function getCodeWithSourcemap(type, code, map) { if (debug$e) { code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`; } if (type === 'js') { code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`; } else if (type === 'css') { code += `\n/*# sourceMappingURL=${genSourceMapUrl(map)} */`; } return code; } function applySourcemapIgnoreList(map, sourcemapPath, sourcemapIgnoreList, logger) { let { x_google_ignoreList } = map; if (x_google_ignoreList === undefined) { x_google_ignoreList = []; } for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) { const sourcePath = map.sources[sourcesIndex]; if (!sourcePath) continue; const ignoreList = sourcemapIgnoreList(path$o$1.isAbsolute(sourcePath) ? sourcePath : path$o$1.resolve(path$o$1.dirname(sourcemapPath), sourcePath), sourcemapPath); if (logger && typeof ignoreList !== 'boolean') { logger.warn('sourcemapIgnoreList function must return a boolean.'); } if (ignoreList && !x_google_ignoreList.includes(sourcesIndex)) { x_google_ignoreList.push(sourcesIndex); } } if (x_google_ignoreList.length > 0) { if (!map.x_google_ignoreList) map.x_google_ignoreList = x_google_ignoreList; } } function e(e,n,r){throw new Error(r?`No known conditions for "${n}" specifier in "${e}" package`:`Missing "${n}" specifier in "${e}" package`)}function n$3(n,i,o,f){let s,u,l=r(n,o),c=function(e){let n=new Set(["default",...e.conditions||[]]);return e.unsafe||n.add(e.require?"require":"import"),e.unsafe||n.add(e.browser?"browser":"node"),n}(f||{}),a=i[l];if(void 0===a){let e,n,r,t;for(t in i)n&&t.length1&&(r=t.indexOf("*",1),~r&&(e=RegExp("^"+t.substring(0,r)+"(.*)"+t.substring(1+r)).exec(l),e&&e[1]&&(u=e[1],n=t))));a=i[n];}return a||e(n,l),s=t(a,c),s||e(n,l,1),u&&function(e,n){let r,t=0,i=e.length,o=/[*]/g,f=/[/]$/;for(;t code) { return false } pos += set[i + 1]; if (pos >= code) { return true } } return false } // Test whether a given character code starts an identifier. function isIdentifierStart$1(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$1.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet$1(code, astralIdentifierStartCodes$1) } // Test whether a given character is part of an identifier. function isIdentifierChar$1(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$1.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet$1(code, astralIdentifierStartCodes$1) || isInAstralSet$1(code, astralIdentifierCodes$1) } // ## Token types // The assignment of fine-grained, information-carrying type objects // allows the tokenizer to store the information it has about a // token in a way that is very cheap for the parser to look up. // All token type variables start with an underscore, to make them // easy to recognize. // The `beforeExpr` property is used to disambiguate between regular // expressions and divisions. It is set on all token types that can // be followed by an expression (thus, a slash after them would be a // regular expression). // // The `startsExpr` property is used to check if the token ends a // `yield` expression. It is set on all token types that either can // directly start an expression (like a quotation mark) or can // continue an expression (like the body of a string). // // `isLoop` marks a keyword as starting a loop, which is important // to know when parsing a label, in order to allow or disallow // continue jumps to that label. var TokenType$2 = function TokenType(label, conf) { if ( conf === void 0 ) conf = {}; this.label = label; this.keyword = conf.keyword; this.beforeExpr = !!conf.beforeExpr; this.startsExpr = !!conf.startsExpr; this.isLoop = !!conf.isLoop; this.isAssign = !!conf.isAssign; this.prefix = !!conf.prefix; this.postfix = !!conf.postfix; this.binop = conf.binop || null; this.updateContext = null; }; function binop$1(name, prec) { return new TokenType$2(name, {beforeExpr: true, binop: prec}) } var beforeExpr$1 = {beforeExpr: true}, startsExpr$1 = {startsExpr: true}; // Map keyword names to token types. var keywords$2$1 = {}; // Succinct definitions of keyword token types function kw$1(name, options) { if ( options === void 0 ) options = {}; options.keyword = name; return keywords$2$1[name] = new TokenType$2(name, options) } var types$1$1 = { num: new TokenType$2("num", startsExpr$1), regexp: new TokenType$2("regexp", startsExpr$1), string: new TokenType$2("string", startsExpr$1), name: new TokenType$2("name", startsExpr$1), privateId: new TokenType$2("privateId", startsExpr$1), eof: new TokenType$2("eof"), // Punctuation token types. bracketL: new TokenType$2("[", {beforeExpr: true, startsExpr: true}), bracketR: new TokenType$2("]"), braceL: new TokenType$2("{", {beforeExpr: true, startsExpr: true}), braceR: new TokenType$2("}"), parenL: new TokenType$2("(", {beforeExpr: true, startsExpr: true}), parenR: new TokenType$2(")"), comma: new TokenType$2(",", beforeExpr$1), semi: new TokenType$2(";", beforeExpr$1), colon: new TokenType$2(":", beforeExpr$1), dot: new TokenType$2("."), question: new TokenType$2("?", beforeExpr$1), questionDot: new TokenType$2("?."), arrow: new TokenType$2("=>", beforeExpr$1), template: new TokenType$2("template"), invalidTemplate: new TokenType$2("invalidTemplate"), ellipsis: new TokenType$2("...", beforeExpr$1), backQuote: new TokenType$2("`", startsExpr$1), dollarBraceL: new TokenType$2("${", {beforeExpr: true, startsExpr: true}), // Operators. These carry several kinds of properties to help the // parser use them properly (the presence of these properties is // what categorizes them as operators). // // `binop`, when present, specifies that this operator is a binary // operator, and will refer to its precedence. // // `prefix` and `postfix` mark the operator as a prefix or postfix // unary operator. // // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as // binary operators with a very low precedence, that should result // in AssignmentExpression nodes. eq: new TokenType$2("=", {beforeExpr: true, isAssign: true}), assign: new TokenType$2("_=", {beforeExpr: true, isAssign: true}), incDec: new TokenType$2("++/--", {prefix: true, postfix: true, startsExpr: true}), prefix: new TokenType$2("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), logicalOR: binop$1("||", 1), logicalAND: binop$1("&&", 2), bitwiseOR: binop$1("|", 3), bitwiseXOR: binop$1("^", 4), bitwiseAND: binop$1("&", 5), equality: binop$1("==/!=/===/!==", 6), relational: binop$1("/<=/>=", 7), bitShift: binop$1("<>/>>>", 8), plusMin: new TokenType$2("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), modulo: binop$1("%", 10), star: binop$1("*", 10), slash: binop$1("/", 10), starstar: new TokenType$2("**", {beforeExpr: true}), coalesce: binop$1("??", 1), // Keyword token types. _break: kw$1("break"), _case: kw$1("case", beforeExpr$1), _catch: kw$1("catch"), _continue: kw$1("continue"), _debugger: kw$1("debugger"), _default: kw$1("default", beforeExpr$1), _do: kw$1("do", {isLoop: true, beforeExpr: true}), _else: kw$1("else", beforeExpr$1), _finally: kw$1("finally"), _for: kw$1("for", {isLoop: true}), _function: kw$1("function", startsExpr$1), _if: kw$1("if"), _return: kw$1("return", beforeExpr$1), _switch: kw$1("switch"), _throw: kw$1("throw", beforeExpr$1), _try: kw$1("try"), _var: kw$1("var"), _const: kw$1("const"), _while: kw$1("while", {isLoop: true}), _with: kw$1("with"), _new: kw$1("new", {beforeExpr: true, startsExpr: true}), _this: kw$1("this", startsExpr$1), _super: kw$1("super", startsExpr$1), _class: kw$1("class", startsExpr$1), _extends: kw$1("extends", beforeExpr$1), _export: kw$1("export"), _import: kw$1("import", startsExpr$1), _null: kw$1("null", startsExpr$1), _true: kw$1("true", startsExpr$1), _false: kw$1("false", startsExpr$1), _in: kw$1("in", {beforeExpr: true, binop: 7}), _instanceof: kw$1("instanceof", {beforeExpr: true, binop: 7}), _typeof: kw$1("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), _void: kw$1("void", {beforeExpr: true, prefix: true, startsExpr: true}), _delete: kw$1("delete", {beforeExpr: true, prefix: true, startsExpr: true}) }; // Matches a whole line break (where CRLF is considered a single // line break). Used to count lines. var lineBreak$1 = /\r\n?|\n|\u2028|\u2029/; var lineBreakG$1 = new RegExp(lineBreak$1.source, "g"); function isNewLine$1(code) { return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 } function nextLineBreak$1(code, from, end) { if ( end === void 0 ) end = code.length; for (var i = from; i < end; i++) { var next = code.charCodeAt(i); if (isNewLine$1(next)) { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 } } return -1 } var nonASCIIwhitespace$1 = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; var skipWhiteSpace$2 = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; var ref$1 = Object.prototype; var hasOwnProperty$1$1 = ref$1.hasOwnProperty; var toString$1$1 = ref$1.toString; var hasOwn$1 = Object.hasOwn || (function (obj, propName) { return ( hasOwnProperty$1$1.call(obj, propName) ); }); var isArray$3 = Array.isArray || (function (obj) { return ( toString$1$1.call(obj) === "[object Array]" ); }); function wordsRegexp$1(words) { return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") } function codePointToString$1(code) { // UTF-16 Decoding if (code <= 0xFFFF) { return String.fromCharCode(code) } code -= 0x10000; return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) } var loneSurrogate$1 = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; // These are used when `options.locations` is on, for the // `startLoc` and `endLoc` properties. var Position$1 = function Position(line, col) { this.line = line; this.column = col; }; Position$1.prototype.offset = function offset (n) { return new Position$1(this.line, this.column + n) }; var SourceLocation$1 = function SourceLocation(p, start, end) { this.start = start; this.end = end; if (p.sourceFile !== null) { this.source = p.sourceFile; } }; // The `getLineInfo` function is mostly useful when the // `locations` option is off (for performance reasons) and you // want to find the line/column position for a given character // offset. `input` should be the code string that the offset refers // into. function getLineInfo$1(input, offset) { for (var line = 1, cur = 0;;) { var nextBreak = nextLineBreak$1(input, cur, offset); if (nextBreak < 0) { return new Position$1(line, offset - cur) } ++line; cur = nextBreak; } } // A second argument must be given to configure the parser process. // These options are recognized (only `ecmaVersion` is required): var defaultOptions$1 = { // `ecmaVersion` indicates the ECMAScript version to parse. Must be // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` // (the latest version the library supports). This influences // support for strict mode, the set of reserved words, and support // for new syntax features. ecmaVersion: null, // `sourceType` indicates the mode the code should be parsed in. // Can be either `"script"` or `"module"`. This influences global // strict mode and parsing of `import` and `export` declarations. sourceType: "script", // `onInsertedSemicolon` can be a callback that will be called // when a semicolon is automatically inserted. It will be passed // the position of the comma as an offset, and if `locations` is // enabled, it is given the location as a `{line, column}` object // as second argument. onInsertedSemicolon: null, // `onTrailingComma` is similar to `onInsertedSemicolon`, but for // trailing commas. onTrailingComma: null, // By default, reserved words are only enforced if ecmaVersion >= 5. // Set `allowReserved` to a boolean value to explicitly turn this on // an off. When this option has the value "never", reserved words // and keywords can also not be used as property names. allowReserved: null, // When enabled, a return at the top level is not considered an // error. allowReturnOutsideFunction: false, // When enabled, import/export statements are not constrained to // appearing at the top of the program, and an import.meta expression // in a script isn't considered an error. allowImportExportEverywhere: false, // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. // When enabled, await identifiers are allowed to appear at the top-level scope, // but they are still not allowed in non-async functions. allowAwaitOutsideFunction: null, // When enabled, super identifiers are not constrained to // appearing in methods and do not raise an error when they appear elsewhere. allowSuperOutsideMethod: null, // When enabled, hashbang directive in the beginning of file is // allowed and treated as a line comment. Enabled by default when // `ecmaVersion` >= 2023. allowHashBang: false, // When `locations` is on, `loc` properties holding objects with // `start` and `end` properties in `{line, column}` form (with // line being 1-based and column 0-based) will be attached to the // nodes. locations: false, // A function can be passed as `onToken` option, which will // cause Acorn to call that function with object in the same // format as tokens returned from `tokenizer().getToken()`. Note // that you are not allowed to call the parser from the // callback—that will corrupt its internal state. onToken: null, // A function can be passed as `onComment` option, which will // cause Acorn to call that function with `(block, text, start, // end)` parameters whenever a comment is skipped. `block` is a // boolean indicating whether this is a block (`/* */`) comment, // `text` is the content of the comment, and `start` and `end` are // character offsets that denote the start and end of the comment. // When the `locations` option is on, two more parameters are // passed, the full `{line, column}` locations of the start and // end of the comments. Note that you are not allowed to call the // parser from the callback—that will corrupt its internal state. onComment: null, // Nodes have their start and end characters offsets recorded in // `start` and `end` properties (directly on the node, rather than // the `loc` object, which holds line/column data. To also add a // [semi-standardized][range] `range` property holding a `[start, // end]` array with the same numbers, set the `ranges` option to // `true`. // // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 ranges: false, // It is possible to parse multiple files into a single AST by // passing the tree produced by parsing the first file as // `program` option in subsequent parses. This will add the // toplevel forms of the parsed file to the `Program` (top) node // of an existing parse tree. program: null, // When `locations` is on, you can pass this to record the source // file in every node's `loc` object. sourceFile: null, // This value, if given, is stored in every node, whether // `locations` is on or off. directSourceFile: null, // When enabled, parenthesized expressions are represented by // (non-standard) ParenthesizedExpression nodes preserveParens: false }; // Interpret and default an options object var warnedAboutEcmaVersion$1 = false; function getOptions$1(opts) { var options = {}; for (var opt in defaultOptions$1) { options[opt] = opts && hasOwn$1(opts, opt) ? opts[opt] : defaultOptions$1[opt]; } if (options.ecmaVersion === "latest") { options.ecmaVersion = 1e8; } else if (options.ecmaVersion == null) { if (!warnedAboutEcmaVersion$1 && typeof console === "object" && console.warn) { warnedAboutEcmaVersion$1 = true; console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); } options.ecmaVersion = 11; } else if (options.ecmaVersion >= 2015) { options.ecmaVersion -= 2009; } if (options.allowReserved == null) { options.allowReserved = options.ecmaVersion < 5; } if (!opts || opts.allowHashBang == null) { options.allowHashBang = options.ecmaVersion >= 14; } if (isArray$3(options.onToken)) { var tokens = options.onToken; options.onToken = function (token) { return tokens.push(token); }; } if (isArray$3(options.onComment)) { options.onComment = pushComment$1(options, options.onComment); } return options } function pushComment$1(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$1(this, startLoc, endLoc); } if (options.ranges) { comment.range = [start, end]; } array.push(comment); } } // Each scope gets a bitset that may contain these flags var SCOPE_TOP$1 = 1, SCOPE_FUNCTION$1 = 2, SCOPE_ASYNC$1 = 4, SCOPE_GENERATOR$1 = 8, SCOPE_ARROW$1 = 16, SCOPE_SIMPLE_CATCH$1 = 32, SCOPE_SUPER$1 = 64, SCOPE_DIRECT_SUPER$1 = 128, SCOPE_CLASS_STATIC_BLOCK$1 = 256, SCOPE_VAR$1 = SCOPE_TOP$1 | SCOPE_FUNCTION$1 | SCOPE_CLASS_STATIC_BLOCK$1; function functionFlags$1(async, generator) { return SCOPE_FUNCTION$1 | (async ? SCOPE_ASYNC$1 : 0) | (generator ? SCOPE_GENERATOR$1 : 0) } // Used in checkLVal* and declareName to determine the type of a binding var BIND_NONE$1 = 0, // Not a binding BIND_VAR$1 = 1, // Var-style binding BIND_LEXICAL$1 = 2, // Let- or const-style binding BIND_FUNCTION$1 = 3, // Function declaration BIND_SIMPLE_CATCH$1 = 4, // Simple (identifier pattern) catch binding BIND_OUTSIDE$1 = 5; // Special case for function names as bound inside the function var Parser$1$1 = function Parser(options, input, startPos) { this.options = options = getOptions$1(options); this.sourceFile = options.sourceFile; this.keywords = wordsRegexp$1(keywords$1$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); var reserved = ""; if (options.allowReserved !== true) { reserved = reservedWords$3[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; if (options.sourceType === "module") { reserved += " await"; } } this.reservedWords = wordsRegexp$1(reserved); var reservedStrict = (reserved ? reserved + " " : "") + reservedWords$3.strict; this.reservedWordsStrict = wordsRegexp$1(reservedStrict); this.reservedWordsStrictBind = wordsRegexp$1(reservedStrict + " " + reservedWords$3.strictBind); this.input = String(input); // Used to signal to callers of `readWord1` whether the word // contained any escape sequences. This is needed because words with // escape sequences must not be interpreted as keywords. this.containsEsc = false; // Set up token state // The current position of the tokenizer in the input. if (startPos) { this.pos = startPos; this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; this.curLine = this.input.slice(0, this.lineStart).split(lineBreak$1).length; } else { this.pos = this.lineStart = 0; this.curLine = 1; } // Properties of the current token: // Its type this.type = types$1$1.eof; // For tokens that include more information than their type, the value this.value = null; // Its start and end offset this.start = this.end = this.pos; // And, if locations are used, the {line, column} object // corresponding to those offsets this.startLoc = this.endLoc = this.curPosition(); // Position information for the previous token this.lastTokEndLoc = this.lastTokStartLoc = null; this.lastTokStart = this.lastTokEnd = this.pos; // The context stack is used to superficially track syntactic // context to predict whether a regular expression is allowed in a // given position. this.context = this.initialContext(); this.exprAllowed = true; // Figure out if it's a module code. this.inModule = options.sourceType === "module"; this.strict = this.inModule || this.strictDirective(this.pos); // Used to signify the start of a potential arrow function this.potentialArrowAt = -1; this.potentialArrowInForAwait = false; // Positions to delayed-check that yield/await does not exist in default parameters. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; // Labels in scope. this.labels = []; // Thus-far undefined exports. this.undefinedExports = Object.create(null); // If enabled, skip leading hashbang line. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") { this.skipLineComment(2); } // Scope tracking for duplicate variable names (see scope.js) this.scopeStack = []; this.enterScope(SCOPE_TOP$1); // For RegExp validation this.regexpState = null; // The stack of private names. // Each element has two properties: 'declared' and 'used'. // When it exited from the outermost class definition, all used private names must be declared. this.privateNameStack = []; }; var prototypeAccessors$1 = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } }; Parser$1$1.prototype.parse = function parse () { var node = this.options.program || this.startNode(); this.nextToken(); return this.parseTopLevel(node) }; prototypeAccessors$1.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION$1) > 0 }; prototypeAccessors$1.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR$1) > 0 && !this.currentVarScope().inClassFieldInit }; prototypeAccessors$1.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC$1) > 0 && !this.currentVarScope().inClassFieldInit }; prototypeAccessors$1.canAwait.get = function () { for (var i = this.scopeStack.length - 1; i >= 0; i--) { var scope = this.scopeStack[i]; if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK$1) { return false } if (scope.flags & SCOPE_FUNCTION$1) { return (scope.flags & SCOPE_ASYNC$1) > 0 } } return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction }; prototypeAccessors$1.allowSuper.get = function () { var ref = this.currentThisScope(); var flags = ref.flags; var inClassFieldInit = ref.inClassFieldInit; return (flags & SCOPE_SUPER$1) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod }; prototypeAccessors$1.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER$1) > 0 }; prototypeAccessors$1.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; prototypeAccessors$1.allowNewDotTarget.get = function () { var ref = this.currentThisScope(); var flags = ref.flags; var inClassFieldInit = ref.inClassFieldInit; return (flags & (SCOPE_FUNCTION$1 | SCOPE_CLASS_STATIC_BLOCK$1)) > 0 || inClassFieldInit }; prototypeAccessors$1.inClassStaticBlock.get = function () { return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK$1) > 0 }; Parser$1$1.extend = function extend () { var plugins = [], len = arguments.length; while ( len-- ) plugins[ len ] = arguments[ len ]; var cls = this; for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } return cls }; Parser$1$1.parse = function parse (input, options) { return new this(options, input).parse() }; Parser$1$1.parseExpressionAt = function parseExpressionAt (input, pos, options) { var parser = new this(options, input, pos); parser.nextToken(); return parser.parseExpression() }; Parser$1$1.tokenizer = function tokenizer (input, options) { return new this(options, input) }; Object.defineProperties( Parser$1$1.prototype, prototypeAccessors$1 ); var pp$9$1 = Parser$1$1.prototype; // ## Parser utilities var literal$1 = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; pp$9$1.strictDirective = function(start) { if (this.options.ecmaVersion < 5) { return false } for (;;) { // Try to find string literal. skipWhiteSpace$2.lastIndex = start; start += skipWhiteSpace$2.exec(this.input)[0].length; var match = literal$1.exec(this.input.slice(start)); if (!match) { return false } if ((match[1] || match[2]) === "use strict") { skipWhiteSpace$2.lastIndex = start + match[0].length; var spaceAfter = skipWhiteSpace$2.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; var next = this.input.charAt(end); return next === ";" || next === "}" || (lineBreak$1.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) } start += match[0].length; // Skip semicolon, if any. skipWhiteSpace$2.lastIndex = start; start += skipWhiteSpace$2.exec(this.input)[0].length; if (this.input[start] === ";") { start++; } } }; // Predicate that tests whether the next token is of the given // type, and if yes, consumes it as a side effect. pp$9$1.eat = function(type) { if (this.type === type) { this.next(); return true } else { return false } }; // Tests whether parsed token is a contextual keyword. pp$9$1.isContextual = function(name) { return this.type === types$1$1.name && this.value === name && !this.containsEsc }; // Consumes contextual keyword if possible. pp$9$1.eatContextual = function(name) { if (!this.isContextual(name)) { return false } this.next(); return true }; // Asserts that following token is given contextual keyword. pp$9$1.expectContextual = function(name) { if (!this.eatContextual(name)) { this.unexpected(); } }; // Test whether a semicolon can be inserted at the current position. pp$9$1.canInsertSemicolon = function() { return this.type === types$1$1.eof || this.type === types$1$1.braceR || lineBreak$1.test(this.input.slice(this.lastTokEnd, this.start)) }; pp$9$1.insertSemicolon = function() { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon) { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } return true } }; // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. pp$9$1.semicolon = function() { if (!this.eat(types$1$1.semi) && !this.insertSemicolon()) { this.unexpected(); } }; pp$9$1.afterTrailingComma = function(tokType, notNext) { if (this.type === tokType) { if (this.options.onTrailingComma) { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } if (!notNext) { this.next(); } return true } }; // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error. pp$9$1.expect = function(type) { this.eat(type) || this.unexpected(); }; // Raise an unexpected token error. pp$9$1.unexpected = function(pos) { this.raise(pos != null ? pos : this.start, "Unexpected token"); }; var DestructuringErrors$1 = function DestructuringErrors() { this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1; }; pp$9$1.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, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); } }; pp$9$1.checkExpressionErrors = function(refDestructuringErrors, andThrow) { if (!refDestructuringErrors) { return false } var shorthandAssign = refDestructuringErrors.shorthandAssign; var doubleProto = refDestructuringErrors.doubleProto; if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } if (shorthandAssign >= 0) { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } if (doubleProto >= 0) { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } }; pp$9$1.checkYieldAwaitInDefaultParams = function() { if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } if (this.awaitPos) { this.raise(this.awaitPos, "Await expression cannot be a default value"); } }; pp$9$1.isSimpleAssignTarget = function(expr) { if (expr.type === "ParenthesizedExpression") { return this.isSimpleAssignTarget(expr.expression) } return expr.type === "Identifier" || expr.type === "MemberExpression" }; var pp$8$1 = Parser$1$1.prototype; // ### Statement parsing // Parse a program. Initializes the parser, reads any number of // statements, and wraps them in a Program node. Optionally takes a // `program` argument. If present, the statements will be appended // to its body instead of creating a new node. pp$8$1.parseTopLevel = function(node) { var exports = Object.create(null); if (!node.body) { node.body = []; } while (this.type !== types$1$1.eof) { var stmt = this.parseStatement(null, true, exports); node.body.push(stmt); } if (this.inModule) { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) { var name = list[i]; this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); } } this.adaptDirectivePrologue(node.body); this.next(); node.sourceType = this.options.sourceType; return this.finishNode(node, "Program") }; var loopLabel$1 = {kind: "loop"}, switchLabel$1 = {kind: "switch"}; pp$8$1.isLet = function(context) { if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } skipWhiteSpace$2.lastIndex = this.pos; var skip = skipWhiteSpace$2.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 || nextCh === 92) { return true } // '[', '/' if (context) { return false } if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral if (isIdentifierStart$1(nextCh, true)) { var pos = next + 1; while (isIdentifierChar$1(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } var ident = this.input.slice(next, pos); if (!keywordRelationalOperator$1.test(ident)) { return true } } return false }; // check 'async [no LineTerminator here] function' // - 'async /*foo*/ function' is OK. // - 'async /*\n*/ function' is invalid. pp$8$1.isAsyncFunction = function() { if (this.options.ecmaVersion < 8 || !this.isContextual("async")) { return false } skipWhiteSpace$2.lastIndex = this.pos; var skip = skipWhiteSpace$2.exec(this.input); var next = this.pos + skip[0].length, after; return !lineBreak$1.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar$1(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) }; // Parse a single statement. // // If expecting a statement and finding a slash operator, parse a // regular expression literal. This is to handle cases like // `if (foo) /blah/.exec(foo)`, where looking at the previous token // does not help. pp$8$1.parseStatement = function(context, topLevel, exports) { var starttype = this.type, node = this.startNode(), kind; if (this.isLet(context)) { starttype = types$1$1._var; kind = "let"; } // Most types of statements are recognized by the keyword they // start with. Many are trivial to parse, some require a bit of // complexity. switch (starttype) { case types$1$1._break: case types$1$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword) case types$1$1._debugger: return this.parseDebuggerStatement(node) case types$1$1._do: return this.parseDoStatement(node) case types$1$1._for: return this.parseForStatement(node) case types$1$1._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$1$1._class: if (context) { this.unexpected(); } return this.parseClass(node, true) case types$1$1._if: return this.parseIfStatement(node) case types$1$1._return: return this.parseReturnStatement(node) case types$1$1._switch: return this.parseSwitchStatement(node) case types$1$1._throw: return this.parseThrowStatement(node) case types$1$1._try: return this.parseTryStatement(node) case types$1$1._const: case types$1$1._var: kind = kind || this.value; if (context && kind !== "var") { this.unexpected(); } return this.parseVarStatement(node, kind) case types$1$1._while: return this.parseWhileStatement(node) case types$1$1._with: return this.parseWithStatement(node) case types$1$1.braceL: return this.parseBlock(true, node) case types$1$1.semi: return this.parseEmptyStatement(node) case types$1$1._export: case types$1$1._import: if (this.options.ecmaVersion > 10 && starttype === types$1$1._import) { skipWhiteSpace$2.lastIndex = this.pos; var skip = skipWhiteSpace$2.exec(this.input); var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); if (nextCh === 40 || nextCh === 46) // '(' or '.' { return this.parseExpressionStatement(node, this.parseExpression()) } } if (!this.options.allowImportExportEverywhere) { if (!topLevel) { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } if (!this.inModule) { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } } return starttype === types$1$1._import ? this.parseImport(node) : this.parseExport(node, exports) // If the statement does not start with a statement keyword or a // brace, it's an ExpressionStatement or LabeledStatement. We // simply start parsing an expression, and afterwards, if the // next token is a colon and the expression was a simple // Identifier node, we switch to interpreting it as a label. default: if (this.isAsyncFunction()) { if (context) { this.unexpected(); } this.next(); return this.parseFunctionStatement(node, true, !context) } var maybeName = this.value, expr = this.parseExpression(); if (starttype === types$1$1.name && expr.type === "Identifier" && this.eat(types$1$1.colon)) { return this.parseLabeledStatement(node, maybeName, expr, context) } else { return this.parseExpressionStatement(node, expr) } } }; pp$8$1.parseBreakContinueStatement = function(node, keyword) { var isBreak = keyword === "break"; this.next(); if (this.eat(types$1$1.semi) || this.insertSemicolon()) { node.label = null; } else if (this.type !== types$1$1.name) { this.unexpected(); } else { node.label = this.parseIdent(); this.semicolon(); } // Verify that there is an actual destination to break or // continue to. var i = 0; for (; i < this.labels.length; ++i) { var lab = this.labels[i]; if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } if (node.label && isBreak) { break } } } if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") }; pp$8$1.parseDebuggerStatement = function(node) { this.next(); this.semicolon(); return this.finishNode(node, "DebuggerStatement") }; pp$8$1.parseDoStatement = function(node) { this.next(); this.labels.push(loopLabel$1); node.body = this.parseStatement("do"); this.labels.pop(); this.expect(types$1$1._while); node.test = this.parseParenExpression(); if (this.options.ecmaVersion >= 6) { this.eat(types$1$1.semi); } else { this.semicolon(); } return this.finishNode(node, "DoWhileStatement") }; // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpression`), and then check // whether the next token is `in` or `of`. When there is no init // part (semicolon immediately after the opening parenthesis), it // is a regular `for` loop. pp$8$1.parseForStatement = function(node) { this.next(); var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; this.labels.push(loopLabel$1); this.enterScope(0); this.expect(types$1$1.parenL); if (this.type === types$1$1.semi) { if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, null) } var isLet = this.isLet(); if (this.type === types$1$1._var || this.type === types$1$1._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$1$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { if (this.options.ecmaVersion >= 9) { if (this.type === types$1$1._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 startsWithLet = this.isContextual("let"), isForOf = false; var refDestructuringErrors = new DestructuringErrors$1; var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); if (this.type === types$1$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { if (this.options.ecmaVersion >= 9) { if (this.type === types$1$1._in) { if (awaitAt > -1) { this.unexpected(awaitAt); } } else { node.await = awaitAt > -1; } } if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); } this.toAssignable(init, false, refDestructuringErrors); this.checkLValPattern(init); return this.parseForIn(node, init) } else { this.checkExpressionErrors(refDestructuringErrors, true); } if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, init) }; pp$8$1.parseFunctionStatement = function(node, isAsync, declarationPosition) { this.next(); return this.parseFunction(node, FUNC_STATEMENT$1 | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT$1), false, isAsync) }; pp$8$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$1$1._else) ? this.parseStatement("if") : null; return this.finishNode(node, "IfStatement") }; pp$8$1.parseReturnStatement = function(node) { if (!this.inFunction && !this.options.allowReturnOutsideFunction) { this.raise(this.start, "'return' outside of function"); } this.next(); // In `return` (and `break`/`continue`), the keywords with // optional arguments, we eagerly look for a semicolon or the // possibility to insert one. if (this.eat(types$1$1.semi) || this.insertSemicolon()) { node.argument = null; } else { node.argument = this.parseExpression(); this.semicolon(); } return this.finishNode(node, "ReturnStatement") }; pp$8$1.parseSwitchStatement = function(node) { this.next(); node.discriminant = this.parseParenExpression(); node.cases = []; this.expect(types$1$1.braceL); this.labels.push(switchLabel$1); this.enterScope(0); // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is used to keep the node that we are currently // adding statements to. var cur; for (var sawDefault = false; this.type !== types$1$1.braceR;) { if (this.type === types$1$1._case || this.type === types$1$1._default) { var isCase = this.type === types$1$1._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$1$1.colon); } else { if (!cur) { this.unexpected(); } cur.consequent.push(this.parseStatement(null)); } } this.exitScope(); if (cur) { this.finishNode(cur, "SwitchCase"); } this.next(); // Closing brace this.labels.pop(); return this.finishNode(node, "SwitchStatement") }; pp$8$1.parseThrowStatement = function(node) { this.next(); if (lineBreak$1.test(this.input.slice(this.lastTokEnd, this.start))) { this.raise(this.lastTokEnd, "Illegal newline after throw"); } node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement") }; // Reused empty array added for node fields that are always empty. var empty$1$1 = []; pp$8$1.parseTryStatement = function(node) { this.next(); node.block = this.parseBlock(); node.handler = null; if (this.type === types$1$1._catch) { var clause = this.startNode(); this.next(); if (this.eat(types$1$1.parenL)) { clause.param = this.parseBindingAtom(); var simple = clause.param.type === "Identifier"; this.enterScope(simple ? SCOPE_SIMPLE_CATCH$1 : 0); this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH$1 : BIND_LEXICAL$1); this.expect(types$1$1.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$1$1._finally) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) { this.raise(node.start, "Missing catch or finally clause"); } return this.finishNode(node, "TryStatement") }; pp$8$1.parseVarStatement = function(node, kind) { this.next(); this.parseVar(node, false, kind); this.semicolon(); return this.finishNode(node, "VariableDeclaration") }; pp$8$1.parseWhileStatement = function(node) { this.next(); node.test = this.parseParenExpression(); this.labels.push(loopLabel$1); node.body = this.parseStatement("while"); this.labels.pop(); return this.finishNode(node, "WhileStatement") }; pp$8$1.parseWithStatement = function(node) { if (this.strict) { this.raise(this.start, "'with' in strict mode"); } this.next(); node.object = this.parseParenExpression(); node.body = this.parseStatement("with"); return this.finishNode(node, "WithStatement") }; pp$8$1.parseEmptyStatement = function(node) { this.next(); return this.finishNode(node, "EmptyStatement") }; pp$8$1.parseLabeledStatement = function(node, maybeName, expr, context) { for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) { var label = list[i$1]; if (label.name === maybeName) { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); } } var kind = this.type.isLoop ? "loop" : this.type === types$1$1._switch ? "switch" : null; for (var i = this.labels.length - 1; i >= 0; i--) { var label$1 = this.labels[i]; if (label$1.statementStart === node.start) { // Update information about previous labels on this node label$1.statementStart = this.start; label$1.kind = kind; } else { break } } this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); this.labels.pop(); node.label = expr; return this.finishNode(node, "LabeledStatement") }; pp$8$1.parseExpressionStatement = function(node, expr) { node.expression = expr; this.semicolon(); return this.finishNode(node, "ExpressionStatement") }; // Parse a semicolon-enclosed block of statements, handling `"use // strict"` declarations when `allowStrict` is true (used for // function bodies). pp$8$1.parseBlock = function(createNewLexicalScope, node, exitStrict) { if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; if ( node === void 0 ) node = this.startNode(); node.body = []; this.expect(types$1$1.braceL); if (createNewLexicalScope) { this.enterScope(0); } while (this.type !== types$1$1.braceR) { var stmt = this.parseStatement(null); node.body.push(stmt); } if (exitStrict) { this.strict = false; } this.next(); if (createNewLexicalScope) { this.exitScope(); } return this.finishNode(node, "BlockStatement") }; // Parse a regular `for` loop. The disambiguation code in // `parseStatement` will already have parsed the init statement or // expression. pp$8$1.parseFor = function(node, init) { node.init = init; this.expect(types$1$1.semi); node.test = this.type === types$1$1.semi ? null : this.parseExpression(); this.expect(types$1$1.semi); node.update = this.type === types$1$1.parenR ? null : this.parseExpression(); this.expect(types$1$1.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, "ForStatement") }; // Parse a `for`/`in` and `for`/`of` loop, which are almost // same from parser's perspective. pp$8$1.parseForIn = function(node, init) { var isForIn = this.type === types$1$1._in; this.next(); if ( init.type === "VariableDeclaration" && init.declarations[0].init != null && ( !isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier" ) ) { this.raise( init.start, ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") ); } node.left = init; node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); this.expect(types$1$1.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") }; // Parse a list of variable declarations. pp$8$1.parseVar = function(node, isFor, kind) { node.declarations = []; node.kind = kind; for (;;) { var decl = this.startNode(); this.parseVarId(decl, kind); if (this.eat(types$1$1.eq)) { decl.init = this.parseMaybeAssign(isFor); } else if (kind === "const" && !(this.type === types$1$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { this.unexpected(); } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1$1._in || this.isContextual("of")))) { this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); } else { decl.init = null; } node.declarations.push(this.finishNode(decl, "VariableDeclarator")); if (!this.eat(types$1$1.comma)) { break } } return node }; pp$8$1.parseVarId = function(decl, kind) { decl.id = this.parseBindingAtom(); this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR$1 : BIND_LEXICAL$1, false); }; var FUNC_STATEMENT$1 = 1, FUNC_HANGING_STATEMENT$1 = 2, FUNC_NULLABLE_ID$1 = 4; // Parse a function declaration or literal (depending on the // `statement & FUNC_STATEMENT`). // Remove `allowExpressionBody` for 7.0.0, as it is only called with false pp$8$1.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { this.initFunction(node); if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { if (this.type === types$1$1.star && (statement & FUNC_HANGING_STATEMENT$1)) { this.unexpected(); } node.generator = this.eat(types$1$1.star); } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } if (statement & FUNC_STATEMENT$1) { node.id = (statement & FUNC_NULLABLE_ID$1) && this.type !== types$1$1.name ? null : this.parseIdent(); if (node.id && !(statement & FUNC_HANGING_STATEMENT$1)) // If it is a regular function declaration in sloppy mode, then it is // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding // mode depends on properties of the current scope (see // treatFunctionsAsVar). { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR$1 : BIND_LEXICAL$1 : BIND_FUNCTION$1); } } var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags$1(node.async, node.generator)); if (!(statement & FUNC_STATEMENT$1)) { node.id = this.type === types$1$1.name ? this.parseIdent() : null; } this.parseFunctionParams(node); this.parseFunctionBody(node, allowExpressionBody, false, forInit); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, (statement & FUNC_STATEMENT$1) ? "FunctionDeclaration" : "FunctionExpression") }; pp$8$1.parseFunctionParams = function(node) { this.expect(types$1$1.parenL); node.params = this.parseBindingList(types$1$1.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); }; // Parse a class declaration or literal (depending on the // `isStatement` parameter). pp$8$1.parseClass = function(node, isStatement) { this.next(); // ecma-262 14.6 Class Definitions // A class definition is always strict mode code. var oldStrict = this.strict; this.strict = true; this.parseClassId(node, isStatement); this.parseClassSuper(node); var privateNameMap = this.enterClassBody(); var classBody = this.startNode(); var hadConstructor = false; classBody.body = []; this.expect(types$1$1.braceL); while (this.type !== types$1$1.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; } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted$1(privateNameMap, element)) { this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); } } } this.strict = oldStrict; this.next(); node.body = this.finishNode(classBody, "ClassBody"); this.exitClassBody(); return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") }; pp$8$1.parseClassElement = function(constructorAllowsSuper) { if (this.eat(types$1$1.semi)) { return null } var ecmaVersion = this.options.ecmaVersion; var node = this.startNode(); var keyName = ""; var isGenerator = false; var isAsync = false; var kind = "method"; var isStatic = false; if (this.eatContextual("static")) { // Parse static init block if (ecmaVersion >= 13 && this.eat(types$1$1.braceL)) { this.parseClassStaticBlock(node); return node } if (this.isClassElementNameStart() || this.type === types$1$1.star) { isStatic = true; } else { keyName = "static"; } } node.static = isStatic; if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { if ((this.isClassElementNameStart() || this.type === types$1$1.star) && !this.canInsertSemicolon()) { isAsync = true; } else { keyName = "async"; } } if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1$1.star)) { isGenerator = true; } if (!keyName && !isAsync && !isGenerator) { var lastValue = this.value; if (this.eatContextual("get") || this.eatContextual("set")) { if (this.isClassElementNameStart()) { kind = lastValue; } else { keyName = lastValue; } } } // Parse element name if (keyName) { // 'async', 'get', 'set', or 'static' were not a keyword contextually. // The last token is any of those. Make it the element name. node.computed = false; node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); node.key.name = keyName; this.finishNode(node.key, "Identifier"); } else { this.parseClassElementName(node); } // Parse element value if (ecmaVersion < 13 || this.type === types$1$1.parenL || kind !== "method" || isGenerator || isAsync) { var isConstructor = !node.static && checkKeyName$1(node, "constructor"); var allowsDirectSuper = isConstructor && constructorAllowsSuper; // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } node.kind = isConstructor ? "constructor" : kind; this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); } else { this.parseClassField(node); } return node }; pp$8$1.isClassElementNameStart = function() { return ( this.type === types$1$1.name || this.type === types$1$1.privateId || this.type === types$1$1.num || this.type === types$1$1.string || this.type === types$1$1.bracketL || this.type.keyword ) }; pp$8$1.parseClassElementName = function(element) { if (this.type === types$1$1.privateId) { if (this.value === "constructor") { this.raise(this.start, "Classes can't have an element named '#constructor'"); } element.computed = false; element.key = this.parsePrivateIdent(); } else { this.parsePropertyName(element); } }; pp$8$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { // Check key and flags var key = method.key; if (method.kind === "constructor") { 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"); } } else if (method.static && checkKeyName$1(method, "prototype")) { this.raise(key.start, "Classes may not have a static property named prototype"); } // Parse value var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); // Check value if (method.kind === "get" && value.params.length !== 0) { this.raiseRecoverable(value.start, "getter should have no params"); } if (method.kind === "set" && value.params.length !== 1) { this.raiseRecoverable(value.start, "setter should have exactly one param"); } if (method.kind === "set" && value.params[0].type === "RestElement") { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } return this.finishNode(method, "MethodDefinition") }; pp$8$1.parseClassField = function(field) { if (checkKeyName$1(field, "constructor")) { this.raise(field.key.start, "Classes can't have a field named 'constructor'"); } else if (field.static && checkKeyName$1(field, "prototype")) { this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); } if (this.eat(types$1$1.eq)) { // To raise SyntaxError if 'arguments' exists in the initializer. var scope = this.currentThisScope(); var inClassFieldInit = scope.inClassFieldInit; scope.inClassFieldInit = true; field.value = this.parseMaybeAssign(); scope.inClassFieldInit = inClassFieldInit; } else { field.value = null; } this.semicolon(); return this.finishNode(field, "PropertyDefinition") }; pp$8$1.parseClassStaticBlock = function(node) { node.body = []; var oldLabels = this.labels; this.labels = []; this.enterScope(SCOPE_CLASS_STATIC_BLOCK$1 | SCOPE_SUPER$1); while (this.type !== types$1$1.braceR) { var stmt = this.parseStatement(null); node.body.push(stmt); } this.next(); this.exitScope(); this.labels = oldLabels; return this.finishNode(node, "StaticBlock") }; pp$8$1.parseClassId = function(node, isStatement) { if (this.type === types$1$1.name) { node.id = this.parseIdent(); if (isStatement) { this.checkLValSimple(node.id, BIND_LEXICAL$1, false); } } else { if (isStatement === true) { this.unexpected(); } node.id = null; } }; pp$8$1.parseClassSuper = function(node) { node.superClass = this.eat(types$1$1._extends) ? this.parseExprSubscripts(null, false) : null; }; pp$8$1.enterClassBody = function() { var element = {declared: Object.create(null), used: []}; this.privateNameStack.push(element); return element.declared }; pp$8$1.exitClassBody = function() { var ref = this.privateNameStack.pop(); var declared = ref.declared; var used = ref.used; var len = this.privateNameStack.length; var parent = len === 0 ? null : this.privateNameStack[len - 1]; for (var i = 0; i < used.length; ++i) { var id = used[i]; if (!hasOwn$1(declared, id.name)) { if (parent) { parent.used.push(id); } else { this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); } } } }; function isPrivateNameConflicted$1(privateNameMap, element) { var name = element.key.name; var curr = privateNameMap[name]; var next = "true"; if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { next = (element.static ? "s" : "i") + element.kind; } // `class { get #a(){}; static set #a(_){} }` is also conflict. if ( curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget" ) { privateNameMap[name] = "true"; return false } else if (!curr) { privateNameMap[name] = next; return false } else { return true } } function checkKeyName$1(node, name) { var computed = node.computed; var key = node.key; return !computed && ( key.type === "Identifier" && key.name === name || key.type === "Literal" && key.value === name ) } // Parses module export declaration. pp$8$1.parseExport = function(node, exports) { this.next(); // export * from '...' if (this.eat(types$1$1.star)) { if (this.options.ecmaVersion >= 11) { if (this.eatContextual("as")) { node.exported = this.parseModuleExportName(); this.checkExport(exports, node.exported, this.lastTokStart); } else { node.exported = null; } } this.expectContextual("from"); if (this.type !== types$1$1.string) { this.unexpected(); } node.source = this.parseExprAtom(); this.semicolon(); return this.finishNode(node, "ExportAllDeclaration") } if (this.eat(types$1$1._default)) { // export default ... this.checkExport(exports, "default", this.lastTokStart); var isAsync; if (this.type === types$1$1._function || (isAsync = this.isAsyncFunction())) { var fNode = this.startNode(); this.next(); if (isAsync) { this.next(); } node.declaration = this.parseFunction(fNode, FUNC_STATEMENT$1 | FUNC_NULLABLE_ID$1, false, isAsync); } else if (this.type === types$1$1._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, 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$1$1.string) { this.unexpected(); } node.source = this.parseExprAtom(); } else { for (var i = 0, list = node.specifiers; i < list.length; i += 1) { // check for keywords used as local names var spec = list[i]; this.checkUnreserved(spec.local); // check if export is defined this.checkLocalExport(spec.local); if (spec.local.type === "Literal") { this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); } } node.source = null; } this.semicolon(); } return this.finishNode(node, "ExportNamedDeclaration") }; pp$8$1.checkExport = function(exports, name, pos) { if (!exports) { return } if (typeof name !== "string") { name = name.type === "Identifier" ? name.name : name.value; } if (hasOwn$1(exports, name)) { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } exports[name] = true; }; pp$8$1.checkPatternExport = function(exports, pat) { var type = pat.type; if (type === "Identifier") { this.checkExport(exports, pat, pat.start); } else if (type === "ObjectPattern") { for (var i = 0, list = pat.properties; i < list.length; i += 1) { var prop = list[i]; this.checkPatternExport(exports, prop); } } else if (type === "ArrayPattern") { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { var elt = list$1[i$1]; if (elt) { this.checkPatternExport(exports, elt); } } } else if (type === "Property") { this.checkPatternExport(exports, pat.value); } else if (type === "AssignmentPattern") { this.checkPatternExport(exports, pat.left); } else if (type === "RestElement") { this.checkPatternExport(exports, pat.argument); } else if (type === "ParenthesizedExpression") { this.checkPatternExport(exports, pat.expression); } }; pp$8$1.checkVariableExport = function(exports, decls) { if (!exports) { return } for (var i = 0, list = decls; i < list.length; i += 1) { var decl = list[i]; this.checkPatternExport(exports, decl.id); } }; pp$8$1.shouldParseExportStatement = function() { return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction() }; // Parses a comma-separated list of module exports. pp$8$1.parseExportSpecifiers = function(exports) { var nodes = [], first = true; // export { x, y as z } [from '...'] this.expect(types$1$1.braceL); while (!this.eat(types$1$1.braceR)) { if (!first) { this.expect(types$1$1.comma); if (this.afterTrailingComma(types$1$1.braceR)) { break } } else { first = false; } var node = this.startNode(); node.local = this.parseModuleExportName(); node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; this.checkExport( exports, node.exported, node.exported.start ); nodes.push(this.finishNode(node, "ExportSpecifier")); } return nodes }; // Parses import declaration. pp$8$1.parseImport = function(node) { this.next(); // import '...' if (this.type === types$1$1.string) { node.specifiers = empty$1$1; node.source = this.parseExprAtom(); } else { node.specifiers = this.parseImportSpecifiers(); this.expectContextual("from"); node.source = this.type === types$1$1.string ? this.parseExprAtom() : this.unexpected(); } this.semicolon(); return this.finishNode(node, "ImportDeclaration") }; // Parses a comma-separated list of module imports. pp$8$1.parseImportSpecifiers = function() { var nodes = [], first = true; if (this.type === types$1$1.name) { // import defaultObj, { x, y as z } from '...' var node = this.startNode(); node.local = this.parseIdent(); this.checkLValSimple(node.local, BIND_LEXICAL$1); nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); if (!this.eat(types$1$1.comma)) { return nodes } } if (this.type === types$1$1.star) { var node$1 = this.startNode(); this.next(); this.expectContextual("as"); node$1.local = this.parseIdent(); this.checkLValSimple(node$1.local, BIND_LEXICAL$1); nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); return nodes } this.expect(types$1$1.braceL); while (!this.eat(types$1$1.braceR)) { if (!first) { this.expect(types$1$1.comma); if (this.afterTrailingComma(types$1$1.braceR)) { break } } else { first = false; } var node$2 = this.startNode(); node$2.imported = this.parseModuleExportName(); if (this.eatContextual("as")) { node$2.local = this.parseIdent(); } else { this.checkUnreserved(node$2.imported); node$2.local = node$2.imported; } this.checkLValSimple(node$2.local, BIND_LEXICAL$1); nodes.push(this.finishNode(node$2, "ImportSpecifier")); } return nodes }; pp$8$1.parseModuleExportName = function() { if (this.options.ecmaVersion >= 13 && this.type === types$1$1.string) { var stringLiteral = this.parseLiteral(this.value); if (loneSurrogate$1.test(stringLiteral.value)) { this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); } return stringLiteral } return this.parseIdent(true) }; // Set `ExpressionStatement#directive` property for directive prologues. pp$8$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$8$1.isDirectiveCandidate = function(statement) { return ( this.options.ecmaVersion >= 5 && statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && // Reject parenthesized strings. (this.input[statement.start] === "\"" || this.input[statement.start] === "'") ) }; var pp$7$1 = Parser$1$1.prototype; // Convert existing expression atom to assignable pattern // if possible. pp$7$1.toAssignable = function(node, isBinding, refDestructuringErrors) { if (this.options.ecmaVersion >= 6 && node) { switch (node.type) { case "Identifier": if (this.inAsync && node.name === "await") { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } break case "ObjectPattern": case "ArrayPattern": case "AssignmentPattern": case "RestElement": break case "ObjectExpression": node.type = "ObjectPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } for (var i = 0, list = node.properties; i < list.length; i += 1) { var prop = list[i]; this.toAssignable(prop, isBinding); // Early error: // AssignmentRestProperty[Yield, Await] : // `...` DestructuringAssignmentTarget[Yield, Await] // // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. if ( prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") ) { this.raise(prop.argument.start, "Unexpected token"); } } break case "Property": // AssignmentProperty has type === "Property" if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } this.toAssignable(node.value, isBinding); break case "ArrayExpression": node.type = "ArrayPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } this.toAssignableList(node.elements, isBinding); break case "SpreadElement": node.type = "RestElement"; this.toAssignable(node.argument, isBinding); if (node.argument.type === "AssignmentPattern") { this.raise(node.argument.start, "Rest elements cannot have a default value"); } break case "AssignmentExpression": if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } node.type = "AssignmentPattern"; delete node.operator; this.toAssignable(node.left, isBinding); break case "ParenthesizedExpression": this.toAssignable(node.expression, isBinding, refDestructuringErrors); break case "ChainExpression": this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); break case "MemberExpression": if (!isBinding) { break } default: this.raise(node.start, "Assigning to rvalue"); } } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } return node }; // Convert list of expression atoms to binding list. pp$7$1.toAssignableList = function(exprList, isBinding) { var end = exprList.length; for (var i = 0; i < end; i++) { var elt = exprList[i]; if (elt) { this.toAssignable(elt, isBinding); } } if (end) { var last = exprList[end - 1]; if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") { this.unexpected(last.argument.start); } } return exprList }; // Parses spread element. pp$7$1.parseSpread = function(refDestructuringErrors) { var node = this.startNode(); this.next(); node.argument = this.parseMaybeAssign(false, refDestructuringErrors); return this.finishNode(node, "SpreadElement") }; pp$7$1.parseRestBinding = function() { var node = this.startNode(); this.next(); // RestElement inside of a function parameter must be an identifier if (this.options.ecmaVersion === 6 && this.type !== types$1$1.name) { this.unexpected(); } node.argument = this.parseBindingAtom(); return this.finishNode(node, "RestElement") }; // Parses lvalue (assignable) atom. pp$7$1.parseBindingAtom = function() { if (this.options.ecmaVersion >= 6) { switch (this.type) { case types$1$1.bracketL: var node = this.startNode(); this.next(); node.elements = this.parseBindingList(types$1$1.bracketR, true, true); return this.finishNode(node, "ArrayPattern") case types$1$1.braceL: return this.parseObj(true) } } return this.parseIdent() }; pp$7$1.parseBindingList = function(close, allowEmpty, allowTrailingComma) { var elts = [], first = true; while (!this.eat(close)) { if (first) { first = false; } else { this.expect(types$1$1.comma); } if (allowEmpty && this.type === types$1$1.comma) { elts.push(null); } else if (allowTrailingComma && this.afterTrailingComma(close)) { break } else if (this.type === types$1$1.ellipsis) { var rest = this.parseRestBinding(); this.parseBindingListItem(rest); elts.push(rest); if (this.type === types$1$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } this.expect(close); break } else { var elem = this.parseMaybeDefault(this.start, this.startLoc); this.parseBindingListItem(elem); elts.push(elem); } } return elts }; pp$7$1.parseBindingListItem = function(param) { return param }; // Parses assignment pattern around given atom if possible. pp$7$1.parseMaybeDefault = function(startPos, startLoc, left) { left = left || this.parseBindingAtom(); if (this.options.ecmaVersion < 6 || !this.eat(types$1$1.eq)) { return left } var node = this.startNodeAt(startPos, startLoc); node.left = left; node.right = this.parseMaybeAssign(); return this.finishNode(node, "AssignmentPattern") }; // The following three functions all verify that a node is an lvalue — // something that can be bound, or assigned to. In order to do so, they perform // a variety of checks: // // - Check that none of the bound/assigned-to identifiers are reserved words. // - Record name declarations for bindings in the appropriate scope. // - Check duplicate argument names, if checkClashes is set. // // If a complex binding pattern is encountered (e.g., object and array // destructuring), the entire pattern is recursively checked. // // There are three versions of checkLVal*() appropriate for different // circumstances: // // - checkLValSimple() shall be used if the syntactic construct supports // nothing other than identifiers and member expressions. Parenthesized // expressions are also correctly handled. This is generally appropriate for // constructs for which the spec says // // > It is a Syntax Error if AssignmentTargetType of [the production] is not // > simple. // // It is also appropriate for checking if an identifier is valid and not // defined elsewhere, like import declarations or function/class identifiers. // // Examples where this is used include: // a += …; // import a from '…'; // where a is the node to be checked. // // - checkLValPattern() shall be used if the syntactic construct supports // anything checkLValSimple() supports, as well as object and array // destructuring patterns. This is generally appropriate for constructs for // which the spec says // // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor // > an ArrayLiteral and AssignmentTargetType of [the production] is not // > simple. // // Examples where this is used include: // (a = …); // const a = …; // try { … } catch (a) { … } // where a is the node to be checked. // // - checkLValInnerPattern() shall be used if the syntactic construct supports // anything checkLValPattern() supports, as well as default assignment // patterns, rest elements, and other constructs that may appear within an // object or array destructuring pattern. // // As a special case, function parameters also use checkLValInnerPattern(), // as they also support defaults and rest constructs. // // These functions deliberately support both assignment and binding constructs, // as the logic for both is exceedingly similar. If the node is the target of // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it // should be set to the appropriate BIND_* constant, like BIND_VAR or // BIND_LEXICAL. // // If the function is called with a non-BIND_NONE bindingType, then // additionally a checkClashes object may be specified to allow checking for // duplicate argument names. checkClashes is ignored if the provided construct // is an assignment (i.e., bindingType is BIND_NONE). pp$7$1.checkLValSimple = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE$1; var isBind = bindingType !== BIND_NONE$1; switch (expr.type) { case "Identifier": if (this.strict && this.reservedWordsStrictBind.test(expr.name)) { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } if (isBind) { if (bindingType === BIND_LEXICAL$1 && expr.name === "let") { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } if (checkClashes) { if (hasOwn$1(checkClashes, expr.name)) { this.raiseRecoverable(expr.start, "Argument name clash"); } checkClashes[expr.name] = true; } if (bindingType !== BIND_OUTSIDE$1) { this.declareName(expr.name, bindingType, expr.start); } } break case "ChainExpression": this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); break case "MemberExpression": if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } break case "ParenthesizedExpression": if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } return this.checkLValSimple(expr.expression, bindingType, checkClashes) default: this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); } }; pp$7$1.checkLValPattern = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE$1; switch (expr.type) { case "ObjectPattern": for (var i = 0, list = expr.properties; i < list.length; i += 1) { var prop = list[i]; this.checkLValInnerPattern(prop, bindingType, checkClashes); } break case "ArrayPattern": for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { var elem = list$1[i$1]; if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } } break default: this.checkLValSimple(expr, bindingType, checkClashes); } }; pp$7$1.checkLValInnerPattern = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE$1; switch (expr.type) { case "Property": // AssignmentProperty has type === "Property" this.checkLValInnerPattern(expr.value, bindingType, checkClashes); break case "AssignmentPattern": this.checkLValPattern(expr.left, bindingType, checkClashes); break case "RestElement": this.checkLValPattern(expr.argument, bindingType, checkClashes); break default: this.checkLValPattern(expr, bindingType, checkClashes); } }; // The algorithm used to determine whether a regexp can appear at a var TokContext$1 = function TokContext(token, isExpr, preserveSpace, override, generator) { this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override; this.generator = !!generator; }; var types$2$1 = { b_stat: new TokContext$1("{", false), b_expr: new TokContext$1("{", true), b_tmpl: new TokContext$1("${", false), p_stat: new TokContext$1("(", false), p_expr: new TokContext$1("(", true), q_tmpl: new TokContext$1("`", true, true, function (p) { return p.tryReadTemplateToken(); }), f_stat: new TokContext$1("function", false), f_expr: new TokContext$1("function", true), f_expr_gen: new TokContext$1("function", true, false, null, true), f_gen: new TokContext$1("function", false, false, null, true) }; var pp$6$1 = Parser$1$1.prototype; pp$6$1.initialContext = function() { return [types$2$1.b_stat] }; pp$6$1.curContext = function() { return this.context[this.context.length - 1] }; pp$6$1.braceIsBlock = function(prevType) { var parent = this.curContext(); if (parent === types$2$1.f_expr || parent === types$2$1.f_stat) { return true } if (prevType === types$1$1.colon && (parent === types$2$1.b_stat || parent === types$2$1.b_expr)) { return !parent.isExpr } // The check for `tt.name && exprAllowed` detects whether we are // after a `yield` or `of` construct. See the `updateContext` for // `tt.name`. if (prevType === types$1$1._return || prevType === types$1$1.name && this.exprAllowed) { return lineBreak$1.test(this.input.slice(this.lastTokEnd, this.start)) } if (prevType === types$1$1._else || prevType === types$1$1.semi || prevType === types$1$1.eof || prevType === types$1$1.parenR || prevType === types$1$1.arrow) { return true } if (prevType === types$1$1.braceL) { return parent === types$2$1.b_stat } if (prevType === types$1$1._var || prevType === types$1$1._const || prevType === types$1$1.name) { return false } return !this.exprAllowed }; pp$6$1.inGeneratorContext = function() { for (var i = this.context.length - 1; i >= 1; i--) { var context = this.context[i]; if (context.token === "function") { return context.generator } } return false }; pp$6$1.updateContext = function(prevType) { var update, type = this.type; if (type.keyword && prevType === types$1$1.dot) { this.exprAllowed = false; } else if (update = type.updateContext) { update.call(this, prevType); } else { this.exprAllowed = type.beforeExpr; } }; // Used to handle egde cases when token context could not be inferred correctly during tokenization phase pp$6$1.overrideContext = function(tokenCtx) { if (this.curContext() !== tokenCtx) { this.context[this.context.length - 1] = tokenCtx; } }; // Token-specific context update code types$1$1.parenR.updateContext = types$1$1.braceR.updateContext = function() { if (this.context.length === 1) { this.exprAllowed = true; return } var out = this.context.pop(); if (out === types$2$1.b_stat && this.curContext().token === "function") { out = this.context.pop(); } this.exprAllowed = !out.isExpr; }; types$1$1.braceL.updateContext = function(prevType) { this.context.push(this.braceIsBlock(prevType) ? types$2$1.b_stat : types$2$1.b_expr); this.exprAllowed = true; }; types$1$1.dollarBraceL.updateContext = function() { this.context.push(types$2$1.b_tmpl); this.exprAllowed = true; }; types$1$1.parenL.updateContext = function(prevType) { var statementParens = prevType === types$1$1._if || prevType === types$1$1._for || prevType === types$1$1._with || prevType === types$1$1._while; this.context.push(statementParens ? types$2$1.p_stat : types$2$1.p_expr); this.exprAllowed = true; }; types$1$1.incDec.updateContext = function() { // tokExprAllowed stays unchanged }; types$1$1._function.updateContext = types$1$1._class.updateContext = function(prevType) { if (prevType.beforeExpr && prevType !== types$1$1._else && !(prevType === types$1$1.semi && this.curContext() !== types$2$1.p_stat) && !(prevType === types$1$1._return && lineBreak$1.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types$1$1.colon || prevType === types$1$1.braceL) && this.curContext() === types$2$1.b_stat)) { this.context.push(types$2$1.f_expr); } else { this.context.push(types$2$1.f_stat); } this.exprAllowed = false; }; types$1$1.backQuote.updateContext = function() { if (this.curContext() === types$2$1.q_tmpl) { this.context.pop(); } else { this.context.push(types$2$1.q_tmpl); } this.exprAllowed = false; }; types$1$1.star.updateContext = function(prevType) { if (prevType === types$1$1._function) { var index = this.context.length - 1; if (this.context[index] === types$2$1.f_expr) { this.context[index] = types$2$1.f_expr_gen; } else { this.context[index] = types$2$1.f_gen; } } this.exprAllowed = true; }; types$1$1.name.updateContext = function(prevType) { var allowed = false; if (this.options.ecmaVersion >= 6 && prevType !== types$1$1.dot) { if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) { allowed = true; } } this.exprAllowed = allowed; }; // A recursive descent parser operates by defining functions for all var pp$5$1 = Parser$1$1.prototype; // Check if property name clashes with already added. // Object/class getters and setters are not allowed to clash — // either with each other or with an init property — and in // strict mode, init properties are also not allowed to be repeated. pp$5$1.checkPropClash = function(prop, propHash, refDestructuringErrors) { if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") { return } if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) { return } var key = prop.key; var name; switch (key.type) { case "Identifier": name = key.name; break case "Literal": name = String(key.value); break default: return } var kind = prop.kind; if (this.options.ecmaVersion >= 6) { if (name === "__proto__" && kind === "init") { if (propHash.proto) { if (refDestructuringErrors) { if (refDestructuringErrors.doubleProto < 0) { refDestructuringErrors.doubleProto = key.start; } } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } } propHash.proto = true; } return } name = "$" + name; var other = propHash[name]; if (other) { var redefinition; if (kind === "init") { redefinition = this.strict && other.init || other.get || other.set; } else { redefinition = other.init || other[kind]; } if (redefinition) { this.raiseRecoverable(key.start, "Redefinition of property"); } } else { other = propHash[name] = { init: false, get: false, set: false }; } other[kind] = true; }; // ### Expression parsing // These nest, from the most general expression type at the top to // 'atomic', nondivisible expression types at the bottom. Most of // the functions will simply let the function(s) below them parse, // and, *if* the syntactic construct they handle is present, wrap // the AST node that the inner parser gave them in another node. // Parse a full expression. The optional arguments are used to // forbid the `in` operator (in for loops initalization expressions) // and provide reference for storing '=' operator inside shorthand // property assignment in contexts where both object expression // and object pattern might appear (so it's possible to raise // delayed syntax error at correct position). pp$5$1.parseExpression = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); if (this.type === types$1$1.comma) { var node = this.startNodeAt(startPos, startLoc); node.expressions = [expr]; while (this.eat(types$1$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } return this.finishNode(node, "SequenceExpression") } return expr }; // Parse an assignment expression. This includes applications of // operators like `+=`. pp$5$1.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { if (this.isContextual("yield")) { if (this.inGenerator) { return this.parseYield(forInit) } // The tokenizer will assume an expression is allowed after // `yield`, but this isn't that kind of yield else { this.exprAllowed = false; } } var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; if (refDestructuringErrors) { oldParenAssign = refDestructuringErrors.parenthesizedAssign; oldTrailingComma = refDestructuringErrors.trailingComma; oldDoubleProto = refDestructuringErrors.doubleProto; refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; } else { refDestructuringErrors = new DestructuringErrors$1; ownDestructuringErrors = true; } var startPos = this.start, startLoc = this.startLoc; if (this.type === types$1$1.parenL || this.type === types$1$1.name) { this.potentialArrowAt = this.start; this.potentialArrowInForAwait = forInit === "await"; } var left = this.parseMaybeConditional(forInit, refDestructuringErrors); if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } if (this.type.isAssign) { var node = this.startNodeAt(startPos, startLoc); node.operator = this.value; if (this.type === types$1$1.eq) { left = this.toAssignable(left, false, refDestructuringErrors); } if (!ownDestructuringErrors) { refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; } if (refDestructuringErrors.shorthandAssign >= left.start) { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly if (this.type === types$1$1.eq) { this.checkLValPattern(left); } else { this.checkLValSimple(left); } node.left = left; this.next(); node.right = this.parseMaybeAssign(forInit); if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; } return this.finishNode(node, "AssignmentExpression") } else { if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } } if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } return left }; // Parse a ternary conditional (`?:`) operator. pp$5$1.parseMaybeConditional = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprOps(forInit, refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } if (this.eat(types$1$1.question)) { var node = this.startNodeAt(startPos, startLoc); node.test = expr; node.consequent = this.parseMaybeAssign(); this.expect(types$1$1.colon); node.alternate = this.parseMaybeAssign(forInit); return this.finishNode(node, "ConditionalExpression") } return expr }; // Start the precedence parser. pp$5$1.parseExprOps = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) }; // Parse binary operators with the operator precedence parsing // algorithm. `left` is the left-hand side of the operator. // `minPrec` provides context that allows the function to stop and // defer further parser to one of its callers when it encounters an // operator that has a lower precedence than the set it is parsing. pp$5$1.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { var prec = this.type.binop; if (prec != null && (!forInit || this.type !== types$1$1._in)) { if (prec > minPrec) { var logical = this.type === types$1$1.logicalOR || this.type === types$1$1.logicalAND; var coalesce = this.type === types$1$1.coalesce; if (coalesce) { // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. prec = types$1$1.logicalAND.binop; } var op = this.value; this.next(); var startPos = this.start, startLoc = this.startLoc; var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); if ((logical && this.type === types$1$1.coalesce) || (coalesce && (this.type === types$1$1.logicalOR || this.type === types$1$1.logicalAND))) { this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); } return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) } } return left }; pp$5$1.buildBinary = function(startPos, startLoc, left, right, op, logical) { if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); } var node = this.startNodeAt(startPos, startLoc); node.left = left; node.operator = op; node.right = right; return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") }; // Parse unary operators, both prefix and postfix. pp$5$1.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { var startPos = this.start, startLoc = this.startLoc, expr; if (this.isContextual("await") && this.canAwait) { expr = this.parseAwait(forInit); sawUnary = true; } else if (this.type.prefix) { var node = this.startNode(), update = this.type === types$1$1.incDec; node.operator = this.value; node.prefix = true; this.next(); node.argument = this.parseMaybeUnary(null, true, update, forInit); this.checkExpressionErrors(refDestructuringErrors, true); if (update) { this.checkLValSimple(node.argument); } else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } else if (node.operator === "delete" && isPrivateFieldAccess$1(node.argument)) { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } else { sawUnary = true; } expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); } else if (!sawUnary && this.type === types$1$1.privateId) { if (forInit || this.privateNameStack.length === 0) { this.unexpected(); } expr = this.parsePrivateIdent(); // only could be private fields in 'in', such as #x in obj if (this.type !== types$1$1._in) { this.unexpected(); } } else { expr = this.parseExprSubscripts(refDestructuringErrors, forInit); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } while (this.type.postfix && !this.canInsertSemicolon()) { var node$1 = this.startNodeAt(startPos, startLoc); node$1.operator = this.value; node$1.prefix = false; node$1.argument = expr; this.checkLValSimple(expr); this.next(); expr = this.finishNode(node$1, "UpdateExpression"); } } if (!incDec && this.eat(types$1$1.starstar)) { if (sawUnary) { this.unexpected(this.lastTokStart); } else { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) } } else { return expr } }; function isPrivateFieldAccess$1(node) { return ( node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess$1(node.expression) ) } // Parse call, dot, and `[]`-subscript expressions. pp$5$1.parseExprSubscripts = function(refDestructuringErrors, forInit) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprAtom(refDestructuringErrors, forInit); if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") { return expr } var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); if (refDestructuringErrors && result.type === "MemberExpression") { if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } } return result }; pp$5$1.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.potentialArrowAt === base.start; var optionalChained = false; while (true) { var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); if (element.optional) { optionalChained = true; } if (element === base || element.type === "ArrowFunctionExpression") { if (optionalChained) { var chainNode = this.startNodeAt(startPos, startLoc); chainNode.expression = element; element = this.finishNode(chainNode, "ChainExpression"); } return element } base = element; } }; pp$5$1.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { var optionalSupported = this.options.ecmaVersion >= 11; var optional = optionalSupported && this.eat(types$1$1.questionDot); if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } var computed = this.eat(types$1$1.bracketL); if (computed || (optional && this.type !== types$1$1.parenL && this.type !== types$1$1.backQuote) || this.eat(types$1$1.dot)) { var node = this.startNodeAt(startPos, startLoc); node.object = base; if (computed) { node.property = this.parseExpression(); this.expect(types$1$1.bracketR); } else if (this.type === types$1$1.privateId && base.type !== "Super") { node.property = this.parsePrivateIdent(); } else { node.property = this.parseIdent(this.options.allowReserved !== "never"); } node.computed = !!computed; if (optionalSupported) { node.optional = optional; } base = this.finishNode(node, "MemberExpression"); } else if (!noCalls && this.eat(types$1$1.parenL)) { var refDestructuringErrors = new DestructuringErrors$1, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; var exprList = this.parseExprList(types$1$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1$1.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, forInit) } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; var node$1 = this.startNodeAt(startPos, startLoc); node$1.callee = base; node$1.arguments = exprList; if (optionalSupported) { node$1.optional = optional; } base = this.finishNode(node$1, "CallExpression"); } else if (this.type === types$1$1.backQuote) { if (optional || optionalChained) { this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); } var node$2 = this.startNodeAt(startPos, startLoc); node$2.tag = base; node$2.quasi = this.parseTemplate({isTagged: true}); base = this.finishNode(node$2, "TaggedTemplateExpression"); } return base }; // Parse an atomic expression — either a single token that is an // expression, an expression started by a keyword like `function` or // `new`, or an expression wrapped in punctuation like `()`, `[]`, // or `{}`. pp$5$1.parseExprAtom = function(refDestructuringErrors, forInit) { // 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$1$1.slash) { this.readRegexp(); } var node, canBeArrow = this.potentialArrowAt === this.start; switch (this.type) { case types$1$1._super: if (!this.allowSuper) { this.raise(this.start, "'super' keyword outside a method"); } node = this.startNode(); this.next(); if (this.type === types$1$1.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$1$1.dot && this.type !== types$1$1.bracketL && this.type !== types$1$1.parenL) { this.unexpected(); } return this.finishNode(node, "Super") case types$1$1._this: node = this.startNode(); this.next(); return this.finishNode(node, "ThisExpression") case types$1$1.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$1$1._function)) { this.overrideContext(types$2$1.f_expr); return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit) } if (canBeArrow && !this.canInsertSemicolon()) { if (this.eat(types$1$1.arrow)) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) } if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1$1.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { id = this.parseIdent(false); if (this.canInsertSemicolon() || !this.eat(types$1$1.arrow)) { this.unexpected(); } return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit) } } return id case types$1$1.regexp: var value = this.value; node = this.parseLiteral(value.value); node.regex = {pattern: value.pattern, flags: value.flags}; return node case types$1$1.num: case types$1$1.string: return this.parseLiteral(this.value) case types$1$1._null: case types$1$1._true: case types$1$1._false: node = this.startNode(); node.value = this.type === types$1$1._null ? null : this.type === types$1$1._true; node.raw = this.type.keyword; this.next(); return this.finishNode(node, "Literal") case types$1$1.parenL: var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); if (refDestructuringErrors) { if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) { refDestructuringErrors.parenthesizedAssign = start; } if (refDestructuringErrors.parenthesizedBind < 0) { refDestructuringErrors.parenthesizedBind = start; } } return expr case types$1$1.bracketL: node = this.startNode(); this.next(); node.elements = this.parseExprList(types$1$1.bracketR, true, true, refDestructuringErrors); return this.finishNode(node, "ArrayExpression") case types$1$1.braceL: this.overrideContext(types$2$1.b_expr); return this.parseObj(false, refDestructuringErrors) case types$1$1._function: node = this.startNode(); this.next(); return this.parseFunction(node, 0) case types$1$1._class: return this.parseClass(this.startNode(), false) case types$1$1._new: return this.parseNew() case types$1$1.backQuote: return this.parseTemplate() case types$1$1._import: if (this.options.ecmaVersion >= 11) { return this.parseExprImport() } else { return this.unexpected() } default: this.unexpected(); } }; pp$5$1.parseExprImport = function() { var node = this.startNode(); // Consume `import` as an identifier for `import.meta`. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } var meta = this.parseIdent(true); switch (this.type) { case types$1$1.parenL: return this.parseDynamicImport(node) case types$1$1.dot: node.meta = meta; return this.parseImportMeta(node) default: this.unexpected(); } }; pp$5$1.parseDynamicImport = function(node) { this.next(); // skip `(` // Parse node.source. node.source = this.parseMaybeAssign(); // Verify ending. if (!this.eat(types$1$1.parenR)) { var errorPos = this.start; if (this.eat(types$1$1.comma) && this.eat(types$1$1.parenR)) { this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); } else { this.unexpected(errorPos); } } return this.finishNode(node, "ImportExpression") }; pp$5$1.parseImportMeta = function(node) { this.next(); // skip `.` var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "meta") { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } if (containsEsc) { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } return this.finishNode(node, "MetaProperty") }; pp$5$1.parseLiteral = function(value) { var node = this.startNode(); node.value = value; node.raw = this.input.slice(this.start, this.end); if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } this.next(); return this.finishNode(node, "Literal") }; pp$5$1.parseParenExpression = function() { this.expect(types$1$1.parenL); var val = this.parseExpression(); this.expect(types$1$1.parenR); return val }; pp$5$1.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; if (this.options.ecmaVersion >= 6) { this.next(); var innerStartPos = this.start, innerStartLoc = this.startLoc; var exprList = [], first = true, lastIsComma = false; var refDestructuringErrors = new DestructuringErrors$1, 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$1$1.parenR) { first ? first = false : this.expect(types$1$1.comma); if (allowTrailingComma && this.afterTrailingComma(types$1$1.parenR, true)) { lastIsComma = true; break } else if (this.type === types$1$1.ellipsis) { spreadStart = this.start; exprList.push(this.parseParenItem(this.parseRestBinding())); if (this.type === types$1$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } break } else { exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); } } var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; this.expect(types$1$1.parenR); if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1$1.arrow)) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; return this.parseParenArrowList(startPos, startLoc, exprList, forInit) } if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } if (spreadStart) { this.unexpected(spreadStart); } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; if (exprList.length > 1) { val = this.startNodeAt(innerStartPos, innerStartLoc); val.expressions = exprList; this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); } else { val = exprList[0]; } } else { val = this.parseParenExpression(); } if (this.options.preserveParens) { var par = this.startNodeAt(startPos, startLoc); par.expression = val; return this.finishNode(par, "ParenthesizedExpression") } else { return val } }; pp$5$1.parseParenItem = function(item) { return item }; pp$5$1.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit) }; // New's precedence is slightly tricky. It must allow its argument to // be a `[]` or dot subscript expression, but not a call — at least, // not without wrapping it in parentheses. Thus, it uses the noCalls // argument to parseSubscripts to prevent it from consuming the // argument list. var empty$2 = []; pp$5$1.parseNew = function() { if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } var node = this.startNode(); var meta = this.parseIdent(true); if (this.options.ecmaVersion >= 6 && this.eat(types$1$1.dot)) { node.meta = meta; var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "target") { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } if (containsEsc) { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } if (!this.allowNewDotTarget) { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); } return this.finishNode(node, "MetaProperty") } var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1$1._import; node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false); if (isImport && node.callee.type === "ImportExpression") { this.raise(startPos, "Cannot use new with import()"); } if (this.eat(types$1$1.parenL)) { node.arguments = this.parseExprList(types$1$1.parenR, this.options.ecmaVersion >= 8, false); } else { node.arguments = empty$2; } return this.finishNode(node, "NewExpression") }; // Parse template expression. pp$5$1.parseTemplateElement = function(ref) { var isTagged = ref.isTagged; var elem = this.startNode(); if (this.type === types$1$1.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$1$1.backQuote; return this.finishNode(elem, "TemplateElement") }; pp$5$1.parseTemplate = function(ref) { if ( ref === void 0 ) ref = {}; var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; var node = this.startNode(); this.next(); node.expressions = []; var curElt = this.parseTemplateElement({isTagged: isTagged}); node.quasis = [curElt]; while (!curElt.tail) { if (this.type === types$1$1.eof) { this.raise(this.pos, "Unterminated template literal"); } this.expect(types$1$1.dollarBraceL); node.expressions.push(this.parseExpression()); this.expect(types$1$1.braceR); node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); } this.next(); return this.finishNode(node, "TemplateLiteral") }; pp$5$1.isAsyncProp = function(prop) { return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types$1$1.name || this.type === types$1$1.num || this.type === types$1$1.string || this.type === types$1$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1$1.star)) && !lineBreak$1.test(this.input.slice(this.lastTokEnd, this.start)) }; // Parse an object literal or binding pattern. pp$5$1.parseObj = function(isPattern, refDestructuringErrors) { var node = this.startNode(), first = true, propHash = {}; node.properties = []; this.next(); while (!this.eat(types$1$1.braceR)) { if (!first) { this.expect(types$1$1.comma); if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1$1.braceR)) { break } } else { first = false; } var prop = this.parseProperty(isPattern, refDestructuringErrors); if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } node.properties.push(prop); } return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") }; pp$5$1.parseProperty = function(isPattern, refDestructuringErrors) { var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; if (this.options.ecmaVersion >= 9 && this.eat(types$1$1.ellipsis)) { if (isPattern) { prop.argument = this.parseIdent(false); if (this.type === types$1$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } return this.finishNode(prop, "RestElement") } // Parse argument. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); // To disallow trailing comma via `this.toAssignable()`. if (this.type === types$1$1.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$1$1.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$1$1.star); this.parsePropertyName(prop); } else { isAsync = false; } this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); return this.finishNode(prop, "Property") }; pp$5$1.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { if ((isGenerator || isAsync) && this.type === types$1$1.colon) { this.unexpected(); } if (this.eat(types$1$1.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$1$1.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$1$1.comma && this.type !== types$1$1.braceR && this.type !== types$1$1.eq)) { if (isGenerator || isAsync) { this.unexpected(); } prop.kind = prop.key.name; this.parsePropertyName(prop); prop.value = this.parseMethod(false); var paramCount = prop.kind === "get" ? 0 : 1; if (prop.value.params.length !== paramCount) { var start = prop.value.start; if (prop.kind === "get") { this.raiseRecoverable(start, "getter should have no params"); } else { this.raiseRecoverable(start, "setter should have exactly one param"); } } else { if (prop.kind === "set" && prop.value.params[0].type === "RestElement") { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } } } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { if (isGenerator || isAsync) { this.unexpected(); } this.checkUnreserved(prop.key); if (prop.key.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = startPos; } prop.kind = "init"; if (isPattern) { prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); } else if (this.type === types$1$1.eq && refDestructuringErrors) { if (refDestructuringErrors.shorthandAssign < 0) { refDestructuringErrors.shorthandAssign = this.start; } prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); } else { prop.value = this.copyNode(prop.key); } prop.shorthand = true; } else { this.unexpected(); } }; pp$5$1.parsePropertyName = function(prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(types$1$1.bracketL)) { prop.computed = true; prop.key = this.parseMaybeAssign(); this.expect(types$1$1.bracketR); return prop.key } else { prop.computed = false; } } return prop.key = this.type === types$1$1.num || this.type === types$1$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") }; // Initialize empty function node. pp$5$1.initFunction = function(node) { node.id = null; if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } if (this.options.ecmaVersion >= 8) { node.async = false; } }; // Parse object or class method. pp$5$1.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.initFunction(node); if (this.options.ecmaVersion >= 6) { node.generator = isGenerator; } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags$1(isAsync, node.generator) | SCOPE_SUPER$1 | (allowDirectSuper ? SCOPE_DIRECT_SUPER$1 : 0)); this.expect(types$1$1.parenL); node.params = this.parseBindingList(types$1$1.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); this.parseFunctionBody(node, false, true, false); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "FunctionExpression") }; // Parse arrow function expression with given parameters. pp$5$1.parseArrowExpression = function(node, params, isAsync, forInit) { var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.enterScope(functionFlags$1(isAsync, false) | SCOPE_ARROW$1); this.initFunction(node); if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; node.params = this.toAssignableList(params, true); this.parseFunctionBody(node, true, false, forInit); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "ArrowFunctionExpression") }; // Parse function body and check parameters. pp$5$1.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { var isExpression = isArrowFunction && this.type !== types$1$1.braceL; var oldStrict = this.strict, useStrict = false; if (isExpression) { node.body = this.parseMaybeAssign(forInit); node.expression = true; this.checkParams(node, false); } else { var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); if (!oldStrict || nonSimple) { useStrict = this.strictDirective(this.end); // If this is a strict mode function, verify that argument names // are not repeated, and it does not try to bind the words `eval` // or `arguments`. if (useStrict && nonSimple) { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } } // Start a new scope with regard to labels and the `inFunction` // flag (restore them to their old value afterwards). var oldLabels = this.labels; this.labels = []; if (useStrict) { this.strict = true; } // Add the params to varDeclaredNames to ensure that an error is thrown // if a let/const declaration in the function clashes with one of the params. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE$1); } node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); node.expression = false; this.adaptDirectivePrologue(node.body.body); this.labels = oldLabels; } this.exitScope(); }; pp$5$1.isSimpleParamList = function(params) { for (var i = 0, list = params; i < list.length; i += 1) { var param = list[i]; if (param.type !== "Identifier") { return false } } return true }; // Checks function params for various disallowed patterns such as using "eval" // or "arguments" and duplicate parameters. pp$5$1.checkParams = function(node, allowDuplicates) { var nameHash = Object.create(null); for (var i = 0, list = node.params; i < list.length; i += 1) { var param = list[i]; this.checkLValInnerPattern(param, BIND_VAR$1, allowDuplicates ? null : nameHash); } }; // Parses a comma-separated list of expressions, and returns them as // an array. `close` is the token type that ends the list, and // `allowEmpty` can be turned on to allow subsequent commas with // nothing in between them to be parsed as `null` (which is needed // for array literals). pp$5$1.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { var elts = [], first = true; while (!this.eat(close)) { if (!first) { this.expect(types$1$1.comma); if (allowTrailingComma && this.afterTrailingComma(close)) { break } } else { first = false; } var elt = (void 0); if (allowEmpty && this.type === types$1$1.comma) { elt = null; } else if (this.type === types$1$1.ellipsis) { elt = this.parseSpread(refDestructuringErrors); if (refDestructuringErrors && this.type === types$1$1.comma && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this.start; } } else { elt = this.parseMaybeAssign(false, refDestructuringErrors); } elts.push(elt); } return elts }; pp$5$1.checkUnreserved = function(ref) { var start = ref.start; var end = ref.end; var name = ref.name; if (this.inGenerator && name === "yield") { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } if (this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } if (this.currentThisScope().inClassFieldInit && name === "arguments") { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } if (this.inClassStaticBlock && (name === "arguments" || name === "await")) { this.raise(start, ("Cannot use " + name + " in class static initialization block")); } if (this.keywords.test(name)) { this.raise(start, ("Unexpected keyword '" + name + "'")); } if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) { return } var re = this.strict ? this.reservedWordsStrict : this.reservedWords; if (re.test(name)) { if (!this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); } }; // Parse the next token as an identifier. If `liberal` is true (used // when parsing properties), it will also convert keywords into // identifiers. pp$5$1.parseIdent = function(liberal) { var node = this.startNode(); if (this.type === types$1$1.name) { node.name = this.value; } else if (this.type.keyword) { node.name = this.type.keyword; // To fix https://github.com/acornjs/acorn/issues/575 // `class` and `function` keywords push new context into this.context. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { this.context.pop(); } } else { this.unexpected(); } this.next(!!liberal); this.finishNode(node, "Identifier"); if (!liberal) { this.checkUnreserved(node); if (node.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = node.start; } } return node }; pp$5$1.parsePrivateIdent = function() { var node = this.startNode(); if (this.type === types$1$1.privateId) { node.name = this.value; } else { this.unexpected(); } this.next(); this.finishNode(node, "PrivateIdentifier"); // For validating existence if (this.privateNameStack.length === 0) { this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); } else { this.privateNameStack[this.privateNameStack.length - 1].used.push(node); } return node }; // Parses yield expression inside generator. pp$5$1.parseYield = function(forInit) { if (!this.yieldPos) { this.yieldPos = this.start; } var node = this.startNode(); this.next(); if (this.type === types$1$1.semi || this.canInsertSemicolon() || (this.type !== types$1$1.star && !this.type.startsExpr)) { node.delegate = false; node.argument = null; } else { node.delegate = this.eat(types$1$1.star); node.argument = this.parseMaybeAssign(forInit); } return this.finishNode(node, "YieldExpression") }; pp$5$1.parseAwait = function(forInit) { if (!this.awaitPos) { this.awaitPos = this.start; } var node = this.startNode(); this.next(); node.argument = this.parseMaybeUnary(null, true, false, forInit); return this.finishNode(node, "AwaitExpression") }; var pp$4$1 = Parser$1$1.prototype; // This function is used to raise exceptions on parse errors. It // takes an offset integer (into the current `input`) to indicate // the location of the error, attaches the position to the end // of the error message, and then raises a `SyntaxError` with that // message. pp$4$1.raise = function(pos, message) { var loc = getLineInfo$1(this.input, pos); message += " (" + loc.line + ":" + loc.column + ")"; var err = new SyntaxError(message); err.pos = pos; err.loc = loc; err.raisedAt = this.pos; throw err }; pp$4$1.raiseRecoverable = pp$4$1.raise; pp$4$1.curPosition = function() { if (this.options.locations) { return new Position$1(this.curLine, this.pos - this.lineStart) } }; var pp$3$1 = Parser$1$1.prototype; var Scope$2 = 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 = []; // A switch to disallow the identifier reference 'arguments' this.inClassFieldInit = false; }; // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. pp$3$1.enterScope = function(flags) { this.scopeStack.push(new Scope$2(flags)); }; pp$3$1.exitScope = function() { this.scopeStack.pop(); }; // The spec says: // > At the top level of a function, or script, function declarations are // > treated like var declarations rather than like lexical declarations. pp$3$1.treatFunctionsAsVarInScope = function(scope) { return (scope.flags & SCOPE_FUNCTION$1) || !this.inModule && (scope.flags & SCOPE_TOP$1) }; pp$3$1.declareName = function(name, bindingType, pos) { var redeclared = false; if (bindingType === BIND_LEXICAL$1) { 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$1)) { delete this.undefinedExports[name]; } } else if (bindingType === BIND_SIMPLE_CATCH$1) { var scope$1 = this.currentScope(); scope$1.lexical.push(name); } else if (bindingType === BIND_FUNCTION$1) { 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$1) && 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$1)) { delete this.undefinedExports[name]; } if (scope$3.flags & SCOPE_VAR$1) { break } } } if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } }; pp$3$1.checkLocalExport = function(id) { // scope.functions must be empty as Module code is always strict. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) { this.undefinedExports[id.name] = id; } }; pp$3$1.currentScope = function() { return this.scopeStack[this.scopeStack.length - 1] }; pp$3$1.currentVarScope = function() { for (var i = this.scopeStack.length - 1;; i--) { var scope = this.scopeStack[i]; if (scope.flags & SCOPE_VAR$1) { return scope } } }; // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. pp$3$1.currentThisScope = function() { for (var i = this.scopeStack.length - 1;; i--) { var scope = this.scopeStack[i]; if (scope.flags & SCOPE_VAR$1 && !(scope.flags & SCOPE_ARROW$1)) { return scope } } }; var Node$1 = function Node(parser, pos, loc) { this.type = ""; this.start = pos; this.end = 0; if (parser.options.locations) { this.loc = new SourceLocation$1(parser, loc); } if (parser.options.directSourceFile) { this.sourceFile = parser.options.directSourceFile; } if (parser.options.ranges) { this.range = [pos, 0]; } }; // Start an AST node, attaching a start offset. var pp$2$1 = Parser$1$1.prototype; pp$2$1.startNode = function() { return new Node$1(this, this.start, this.startLoc) }; pp$2$1.startNodeAt = function(pos, loc) { return new Node$1(this, pos, loc) }; // Finish an AST node, adding `type` and `end` properties. function finishNodeAt$1(node, type, pos, loc) { node.type = type; node.end = pos; if (this.options.locations) { node.loc.end = loc; } if (this.options.ranges) { node.range[1] = pos; } return node } pp$2$1.finishNode = function(node, type) { return finishNodeAt$1.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) }; // Finish node at given position pp$2$1.finishNodeAt = function(node, type, pos, loc) { return finishNodeAt$1.call(this, node, type, pos, loc) }; pp$2$1.copyNode = function(node) { var newNode = new Node$1(this, node.start, this.startLoc); for (var prop in node) { newNode[prop] = node[prop]; } return newNode }; // This file contains Unicode properties extracted from the ECMAScript specification. // The lists are extracted like so: // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) // #table-binary-unicode-properties var ecma9BinaryProperties$1 = "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$1 = ecma9BinaryProperties$1 + " Extended_Pictographic"; var ecma11BinaryProperties$1 = ecma10BinaryProperties$1; var ecma12BinaryProperties$1 = ecma11BinaryProperties$1 + " EBase EComp EMod EPres ExtPict"; var ecma13BinaryProperties$1 = ecma12BinaryProperties$1; var ecma14BinaryProperties$1 = ecma13BinaryProperties$1; var unicodeBinaryProperties$1 = { 9: ecma9BinaryProperties$1, 10: ecma10BinaryProperties$1, 11: ecma11BinaryProperties$1, 12: ecma12BinaryProperties$1, 13: ecma13BinaryProperties$1, 14: ecma14BinaryProperties$1 }; // #table-unicode-general-category-values var unicodeGeneralCategoryValues$1 = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; // #table-unicode-script-values var ecma9ScriptValues$1 = "Adlam Adlm 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 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$1 = ecma9ScriptValues$1 + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; var ecma11ScriptValues$1 = ecma10ScriptValues$1 + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; var ecma12ScriptValues$1 = ecma11ScriptValues$1 + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; var ecma13ScriptValues$1 = ecma12ScriptValues$1 + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; var ecma14ScriptValues$1 = ecma13ScriptValues$1 + " Kawi Nag_Mundari Nagm"; var unicodeScriptValues$1 = { 9: ecma9ScriptValues$1, 10: ecma10ScriptValues$1, 11: ecma11ScriptValues$1, 12: ecma12ScriptValues$1, 13: ecma13ScriptValues$1, 14: ecma14ScriptValues$1 }; var data$1 = {}; function buildUnicodeData$1(ecmaVersion) { var d = data$1[ecmaVersion] = { binary: wordsRegexp$1(unicodeBinaryProperties$1[ecmaVersion] + " " + unicodeGeneralCategoryValues$1), nonBinary: { General_Category: wordsRegexp$1(unicodeGeneralCategoryValues$1), Script: wordsRegexp$1(unicodeScriptValues$1[ecmaVersion]) } }; d.nonBinary.Script_Extensions = d.nonBinary.Script; d.nonBinary.gc = d.nonBinary.General_Category; d.nonBinary.sc = d.nonBinary.Script; d.nonBinary.scx = d.nonBinary.Script_Extensions; } for (var i$1$1 = 0, list$1 = [9, 10, 11, 12, 13, 14]; i$1$1 < list$1.length; i$1$1 += 1) { var ecmaVersion$1 = list$1[i$1$1]; buildUnicodeData$1(ecmaVersion$1); } var pp$1$1 = Parser$1$1.prototype; var RegExpValidationState$1 = function RegExpValidationState(parser) { this.parser = parser; this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : ""); this.unicodeProperties = data$1[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion]; this.source = ""; this.flags = ""; this.start = 0; this.switchU = false; this.switchN = false; this.pos = 0; this.lastIntValue = 0; this.lastStringValue = ""; this.lastAssertionIsQuantifiable = false; this.numCapturingParens = 0; this.maxBackReference = 0; this.groupNames = []; this.backReferenceNames = []; }; RegExpValidationState$1.prototype.reset = function reset (start, pattern, flags) { var unicode = flags.indexOf("u") !== -1; this.start = start | 0; this.source = pattern + ""; this.flags = flags; this.switchU = unicode && this.parser.options.ecmaVersion >= 6; this.switchN = unicode && this.parser.options.ecmaVersion >= 9; }; RegExpValidationState$1.prototype.raise = function raise (message) { this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); }; // If u flag is given, this returns the code point at the index (it combines a surrogate pair). // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). RegExpValidationState$1.prototype.at = function at (i, forceU) { if ( forceU === void 0 ) forceU = false; var s = this.source; var l = s.length; if (i >= l) { return -1 } var c = s.charCodeAt(i); if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { return c } var next = s.charCodeAt(i + 1); return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c }; RegExpValidationState$1.prototype.nextIndex = function nextIndex (i, forceU) { if ( forceU === void 0 ) forceU = false; var s = this.source; var l = s.length; if (i >= l) { return l } var c = s.charCodeAt(i), next; if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { return i + 1 } return i + 2 }; RegExpValidationState$1.prototype.current = function current (forceU) { if ( forceU === void 0 ) forceU = false; return this.at(this.pos, forceU) }; RegExpValidationState$1.prototype.lookahead = function lookahead (forceU) { if ( forceU === void 0 ) forceU = false; return this.at(this.nextIndex(this.pos, forceU), forceU) }; RegExpValidationState$1.prototype.advance = function advance (forceU) { if ( forceU === void 0 ) forceU = false; this.pos = this.nextIndex(this.pos, forceU); }; RegExpValidationState$1.prototype.eat = function eat (ch, forceU) { if ( forceU === void 0 ) forceU = false; if (this.current(forceU) === ch) { this.advance(forceU); return true } return false }; /** * Validate the flags part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp$1$1.validateRegExpFlags = function(state) { var validFlags = state.validFlags; var flags = state.flags; for (var i = 0; i < flags.length; i++) { var flag = flags.charAt(i); if (validFlags.indexOf(flag) === -1) { this.raise(state.start, "Invalid regular expression flag"); } if (flags.indexOf(flag, i + 1) > -1) { this.raise(state.start, "Duplicate regular expression flag"); } } }; /** * Validate the pattern part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp$1$1.validateRegExpPattern = function(state) { this.regexp_pattern(state); // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of // parsing contains a |GroupName|, reparse with the goal symbol // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* // exception if _P_ did not conform to the grammar, if any elements of _P_ // were not matched by the parse, or if any Early Error conditions exist. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { state.switchN = true; this.regexp_pattern(state); } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern pp$1$1.regexp_pattern = function(state) { state.pos = 0; state.lastIntValue = 0; state.lastStringValue = ""; state.lastAssertionIsQuantifiable = false; state.numCapturingParens = 0; state.maxBackReference = 0; state.groupNames.length = 0; state.backReferenceNames.length = 0; this.regexp_disjunction(state); if (state.pos !== state.source.length) { // Make the same messages as V8. if (state.eat(0x29 /* ) */)) { state.raise("Unmatched ')'"); } if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { state.raise("Lone quantifier brackets"); } } if (state.maxBackReference > state.numCapturingParens) { state.raise("Invalid escape"); } for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { var name = list[i]; if (state.groupNames.indexOf(name) === -1) { state.raise("Invalid named capture referenced"); } } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction pp$1$1.regexp_disjunction = function(state) { this.regexp_alternative(state); while (state.eat(0x7C /* | */)) { this.regexp_alternative(state); } // Make the same message as V8. if (this.regexp_eatQuantifier(state, true)) { state.raise("Nothing to repeat"); } if (state.eat(0x7B /* { */)) { state.raise("Lone quantifier brackets"); } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative pp$1$1.regexp_alternative = function(state) { while (state.pos < state.source.length && this.regexp_eatTerm(state)) { } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term pp$1$1.regexp_eatTerm = function(state) { if (this.regexp_eatAssertion(state)) { // Handle `QuantifiableAssertion Quantifier` alternative. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion // is a QuantifiableAssertion. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { // Make the same message as V8. if (state.switchU) { state.raise("Invalid quantifier"); } } return true } if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { this.regexp_eatQuantifier(state); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion pp$1$1.regexp_eatAssertion = function(state) { var start = state.pos; state.lastAssertionIsQuantifiable = false; // ^, $ if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { return true } // \b \B if (state.eat(0x5C /* \ */)) { if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { return true } state.pos = start; } // Lookahead / Lookbehind if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { var lookbehind = false; if (this.options.ecmaVersion >= 9) { lookbehind = state.eat(0x3C /* < */); } if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { this.regexp_disjunction(state); if (!state.eat(0x29 /* ) */)) { state.raise("Unterminated group"); } state.lastAssertionIsQuantifiable = !lookbehind; return true } } state.pos = start; return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier pp$1$1.regexp_eatQuantifier = function(state, noError) { if ( noError === void 0 ) noError = false; if (this.regexp_eatQuantifierPrefix(state, noError)) { state.eat(0x3F /* ? */); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix pp$1$1.regexp_eatQuantifierPrefix = function(state, noError) { return ( state.eat(0x2A /* * */) || state.eat(0x2B /* + */) || state.eat(0x3F /* ? */) || this.regexp_eatBracedQuantifier(state, noError) ) }; pp$1$1.regexp_eatBracedQuantifier = function(state, noError) { var start = state.pos; if (state.eat(0x7B /* { */)) { var min = 0, max = -1; if (this.regexp_eatDecimalDigits(state)) { min = state.lastIntValue; if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { max = state.lastIntValue; } if (state.eat(0x7D /* } */)) { // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term if (max !== -1 && max < min && !noError) { state.raise("numbers out of order in {} quantifier"); } return true } } if (state.switchU && !noError) { state.raise("Incomplete quantifier"); } state.pos = start; } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom pp$1$1.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$1$1.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$1$1.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$1$1.regexp_eatCapturingGroup = function(state) { if (state.eat(0x28 /* ( */)) { if (this.options.ecmaVersion >= 9) { this.regexp_groupSpecifier(state); } else if (state.current() === 0x3F /* ? */) { state.raise("Invalid group"); } this.regexp_disjunction(state); if (state.eat(0x29 /* ) */)) { state.numCapturingParens += 1; return true } state.raise("Unterminated group"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom pp$1$1.regexp_eatExtendedAtom = function(state) { return ( state.eat(0x2E /* . */) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state) ) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier pp$1$1.regexp_eatInvalidBracedQuantifier = function(state) { if (this.regexp_eatBracedQuantifier(state, true)) { state.raise("Nothing to repeat"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter pp$1$1.regexp_eatSyntaxCharacter = function(state) { var ch = state.current(); if (isSyntaxCharacter$1(ch)) { state.lastIntValue = ch; state.advance(); return true } return false }; function isSyntaxCharacter$1(ch) { return ( ch === 0x24 /* $ */ || ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || ch === 0x2E /* . */ || ch === 0x3F /* ? */ || ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || ch >= 0x7B /* { */ && ch <= 0x7D /* } */ ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter // But eat eager. pp$1$1.regexp_eatPatternCharacters = function(state) { var start = state.pos; var ch = 0; while ((ch = state.current()) !== -1 && !isSyntaxCharacter$1(ch)) { state.advance(); } return state.pos !== start }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter pp$1$1.regexp_eatExtendedPatternCharacter = function(state) { var ch = state.current(); if ( ch !== -1 && ch !== 0x24 /* $ */ && !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && ch !== 0x2E /* . */ && ch !== 0x3F /* ? */ && ch !== 0x5B /* [ */ && ch !== 0x5E /* ^ */ && ch !== 0x7C /* | */ ) { state.advance(); return true } return false }; // GroupSpecifier :: // [empty] // `?` GroupName pp$1$1.regexp_groupSpecifier = function(state) { if (state.eat(0x3F /* ? */)) { if (this.regexp_eatGroupName(state)) { if (state.groupNames.indexOf(state.lastStringValue) !== -1) { state.raise("Duplicate capture group name"); } state.groupNames.push(state.lastStringValue); return } state.raise("Invalid group"); } }; // GroupName :: // `<` RegExpIdentifierName `>` // Note: this updates `state.lastStringValue` property with the eaten name. pp$1$1.regexp_eatGroupName = function(state) { state.lastStringValue = ""; if (state.eat(0x3C /* < */)) { if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { return true } state.raise("Invalid capture group name"); } return false }; // RegExpIdentifierName :: // RegExpIdentifierStart // RegExpIdentifierName RegExpIdentifierPart // Note: this updates `state.lastStringValue` property with the eaten name. pp$1$1.regexp_eatRegExpIdentifierName = function(state) { state.lastStringValue = ""; if (this.regexp_eatRegExpIdentifierStart(state)) { state.lastStringValue += codePointToString$1(state.lastIntValue); while (this.regexp_eatRegExpIdentifierPart(state)) { state.lastStringValue += codePointToString$1(state.lastIntValue); } return true } return false }; // RegExpIdentifierStart :: // UnicodeIDStart // `$` // `_` // `\` RegExpUnicodeEscapeSequence[+U] pp$1$1.regexp_eatRegExpIdentifierStart = function(state) { var start = state.pos; var forceU = this.options.ecmaVersion >= 11; var ch = state.current(forceU); state.advance(forceU); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue; } if (isRegExpIdentifierStart$1(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierStart$1(ch) { return isIdentifierStart$1(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ } // RegExpIdentifierPart :: // UnicodeIDContinue // `$` // `_` // `\` RegExpUnicodeEscapeSequence[+U] // // pp$1$1.regexp_eatRegExpIdentifierPart = function(state) { var start = state.pos; var forceU = this.options.ecmaVersion >= 11; var ch = state.current(forceU); state.advance(forceU); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue; } if (isRegExpIdentifierPart$1(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierPart$1(ch) { return isIdentifierChar$1(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape pp$1$1.regexp_eatAtomEscape = function(state) { if ( this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || (state.switchN && this.regexp_eatKGroupName(state)) ) { return true } if (state.switchU) { // Make the same message as V8. if (state.current() === 0x63 /* c */) { state.raise("Invalid unicode escape"); } state.raise("Invalid escape"); } return false }; pp$1$1.regexp_eatBackReference = function(state) { var start = state.pos; if (this.regexp_eatDecimalEscape(state)) { var n = state.lastIntValue; if (state.switchU) { // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape if (n > state.maxBackReference) { state.maxBackReference = n; } return true } if (n <= state.numCapturingParens) { return true } state.pos = start; } return false }; pp$1$1.regexp_eatKGroupName = function(state) { if (state.eat(0x6B /* k */)) { if (this.regexp_eatGroupName(state)) { state.backReferenceNames.push(state.lastStringValue); return true } state.raise("Invalid named reference"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape pp$1$1.regexp_eatCharacterEscape = function(state) { return ( this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || this.regexp_eatIdentityEscape(state) ) }; pp$1$1.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$1$1.regexp_eatZero = function(state) { if (state.current() === 0x30 /* 0 */ && !isDecimalDigit$2(state.lookahead())) { state.lastIntValue = 0; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape pp$1$1.regexp_eatControlEscape = function(state) { var ch = state.current(); if (ch === 0x74 /* t */) { state.lastIntValue = 0x09; /* \t */ state.advance(); return true } if (ch === 0x6E /* n */) { state.lastIntValue = 0x0A; /* \n */ state.advance(); return true } if (ch === 0x76 /* v */) { state.lastIntValue = 0x0B; /* \v */ state.advance(); return true } if (ch === 0x66 /* f */) { state.lastIntValue = 0x0C; /* \f */ state.advance(); return true } if (ch === 0x72 /* r */) { state.lastIntValue = 0x0D; /* \r */ state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter pp$1$1.regexp_eatControlLetter = function(state) { var ch = state.current(); if (isControlLetter$1(ch)) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; function isControlLetter$1(ch) { return ( (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence pp$1$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { if ( forceU === void 0 ) forceU = false; var start = state.pos; var switchU = forceU || state.switchU; if (state.eat(0x75 /* u */)) { if (this.regexp_eatFixedHexDigits(state, 4)) { var lead = state.lastIntValue; if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { var leadSurrogateEnd = state.pos; if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { var trail = state.lastIntValue; if (trail >= 0xDC00 && trail <= 0xDFFF) { state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; return true } } state.pos = leadSurrogateEnd; state.lastIntValue = lead; } return true } if ( switchU && state.eat(0x7B /* { */) && this.regexp_eatHexDigits(state) && state.eat(0x7D /* } */) && isValidUnicode$1(state.lastIntValue) ) { return true } if (switchU) { state.raise("Invalid unicode escape"); } state.pos = start; } return false }; function isValidUnicode$1(ch) { return ch >= 0 && ch <= 0x10FFFF } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape pp$1$1.regexp_eatIdentityEscape = function(state) { if (state.switchU) { if (this.regexp_eatSyntaxCharacter(state)) { return true } if (state.eat(0x2F /* / */)) { state.lastIntValue = 0x2F; /* / */ return true } return false } var ch = state.current(); if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { state.lastIntValue = ch; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape pp$1$1.regexp_eatDecimalEscape = function(state) { state.lastIntValue = 0; var ch = state.current(); if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { do { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); state.advance(); } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape pp$1$1.regexp_eatCharacterClassEscape = function(state) { var ch = state.current(); if (isCharacterClassEscape$1(ch)) { state.lastIntValue = -1; state.advance(); return true } if ( state.switchU && this.options.ecmaVersion >= 9 && (ch === 0x50 /* P */ || ch === 0x70 /* p */) ) { state.lastIntValue = -1; state.advance(); if ( state.eat(0x7B /* { */) && this.regexp_eatUnicodePropertyValueExpression(state) && state.eat(0x7D /* } */) ) { return true } state.raise("Invalid property name"); } return false }; function isCharacterClassEscape$1(ch) { return ( ch === 0x64 /* d */ || ch === 0x44 /* D */ || ch === 0x73 /* s */ || ch === 0x53 /* S */ || ch === 0x77 /* w */ || ch === 0x57 /* W */ ) } // UnicodePropertyValueExpression :: // UnicodePropertyName `=` UnicodePropertyValue // LoneUnicodePropertyNameOrValue pp$1$1.regexp_eatUnicodePropertyValueExpression = function(state) { var start = state.pos; // UnicodePropertyName `=` UnicodePropertyValue if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { var name = state.lastStringValue; if (this.regexp_eatUnicodePropertyValue(state)) { var value = state.lastStringValue; this.regexp_validateUnicodePropertyNameAndValue(state, name, value); return true } } state.pos = start; // LoneUnicodePropertyNameOrValue if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { var nameOrValue = state.lastStringValue; this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); return true } return false }; pp$1$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { if (!hasOwn$1(state.unicodeProperties.nonBinary, name)) { state.raise("Invalid property name"); } if (!state.unicodeProperties.nonBinary[name].test(value)) { state.raise("Invalid property value"); } }; pp$1$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { if (!state.unicodeProperties.binary.test(nameOrValue)) { state.raise("Invalid property name"); } }; // UnicodePropertyName :: // UnicodePropertyNameCharacters pp$1$1.regexp_eatUnicodePropertyName = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyNameCharacter$1(ch = state.current())) { state.lastStringValue += codePointToString$1(ch); state.advance(); } return state.lastStringValue !== "" }; function isUnicodePropertyNameCharacter$1(ch) { return isControlLetter$1(ch) || ch === 0x5F /* _ */ } // UnicodePropertyValue :: // UnicodePropertyValueCharacters pp$1$1.regexp_eatUnicodePropertyValue = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyValueCharacter$1(ch = state.current())) { state.lastStringValue += codePointToString$1(ch); state.advance(); } return state.lastStringValue !== "" }; function isUnicodePropertyValueCharacter$1(ch) { return isUnicodePropertyNameCharacter$1(ch) || isDecimalDigit$2(ch) } // LoneUnicodePropertyNameOrValue :: // UnicodePropertyValueCharacters pp$1$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { return this.regexp_eatUnicodePropertyValue(state) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass pp$1$1.regexp_eatCharacterClass = function(state) { if (state.eat(0x5B /* [ */)) { state.eat(0x5E /* ^ */); this.regexp_classRanges(state); if (state.eat(0x5D /* ] */)) { return true } // Unreachable since it threw "unterminated regular expression" error before. state.raise("Unterminated character class"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash pp$1$1.regexp_classRanges = function(state) { while (this.regexp_eatClassAtom(state)) { var left = state.lastIntValue; if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { var right = state.lastIntValue; if (state.switchU && (left === -1 || right === -1)) { state.raise("Invalid character class"); } if (left !== -1 && right !== -1 && left > right) { state.raise("Range out of order in character class"); } } } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash pp$1$1.regexp_eatClassAtom = function(state) { var start = state.pos; if (state.eat(0x5C /* \ */)) { if (this.regexp_eatClassEscape(state)) { return true } if (state.switchU) { // Make the same message as V8. var ch$1 = state.current(); if (ch$1 === 0x63 /* c */ || isOctalDigit$1(ch$1)) { state.raise("Invalid class escape"); } state.raise("Invalid escape"); } state.pos = start; } var ch = state.current(); if (ch !== 0x5D /* ] */) { state.lastIntValue = ch; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape pp$1$1.regexp_eatClassEscape = function(state) { var start = state.pos; if (state.eat(0x62 /* b */)) { state.lastIntValue = 0x08; /* */ return true } if (state.switchU && state.eat(0x2D /* - */)) { state.lastIntValue = 0x2D; /* - */ return true } if (!state.switchU && state.eat(0x63 /* c */)) { if (this.regexp_eatClassControlLetter(state)) { return true } state.pos = start; } return ( this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) ) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter pp$1$1.regexp_eatClassControlLetter = function(state) { var ch = state.current(); if (isDecimalDigit$2(ch) || ch === 0x5F /* _ */) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp$1$1.regexp_eatHexEscapeSequence = function(state) { var start = state.pos; if (state.eat(0x78 /* x */)) { if (this.regexp_eatFixedHexDigits(state, 2)) { return true } if (state.switchU) { state.raise("Invalid escape"); } state.pos = start; } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits pp$1$1.regexp_eatDecimalDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isDecimalDigit$2(ch = state.current())) { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); state.advance(); } return state.pos !== start }; function isDecimalDigit$2(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits pp$1$1.regexp_eatHexDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isHexDigit$2(ch = state.current())) { state.lastIntValue = 16 * state.lastIntValue + hexToInt$1(ch); state.advance(); } return state.pos !== start }; function isHexDigit$2(ch) { return ( (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) ) } function hexToInt$1(ch) { if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { return 10 + (ch - 0x41 /* A */) } if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { return 10 + (ch - 0x61 /* a */) } return ch - 0x30 /* 0 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence // Allows only 0-377(octal) i.e. 0-255(decimal). pp$1$1.regexp_eatLegacyOctalEscapeSequence = function(state) { if (this.regexp_eatOctalDigit(state)) { var n1 = state.lastIntValue; if (this.regexp_eatOctalDigit(state)) { var n2 = state.lastIntValue; if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; } else { state.lastIntValue = n1 * 8 + n2; } } else { state.lastIntValue = n1; } return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit pp$1$1.regexp_eatOctalDigit = function(state) { var ch = state.current(); if (isOctalDigit$1(ch)) { state.lastIntValue = ch - 0x30; /* 0 */ state.advance(); return true } state.lastIntValue = 0; return false }; function isOctalDigit$1(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp$1$1.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$2(ch)) { state.pos = start; return false } state.lastIntValue = 16 * state.lastIntValue + hexToInt$1(ch); state.advance(); } return true }; // Object type used to represent tokens. Note that normally, tokens // simply exist as properties on the parser object. This is only // used for the onToken callback and the external tokenizer. var Token$2 = 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$1(p, p.startLoc, p.endLoc); } if (p.options.ranges) { this.range = [p.start, p.end]; } }; // ## Tokenizer var pp$a = Parser$1$1.prototype; // Move to the next token pp$a.next = function(ignoreEscapeSequenceInKeyword) { if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } if (this.options.onToken) { this.options.onToken(new Token$2(this)); } this.lastTokEnd = this.end; this.lastTokStart = this.start; this.lastTokEndLoc = this.endLoc; this.lastTokStartLoc = this.startLoc; this.nextToken(); }; pp$a.getToken = function() { this.next(); return new Token$2(this) }; // If we're in an ES6 environment, make parsers iterable if (typeof Symbol !== "undefined") { pp$a[Symbol.iterator] = function() { var this$1$1 = this; return { next: function () { var token = this$1$1.getToken(); return { done: token.type === types$1$1.eof, value: token } } } }; } // Toggle strict mode. Re-reads the next number or string to please // pedantic tests (`"use strict"; 010;` should fail). // Read a single token, updating the parser object's token-related // properties. pp$a.nextToken = function() { var curContext = this.curContext(); if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } this.start = this.pos; if (this.options.locations) { this.startLoc = this.curPosition(); } if (this.pos >= this.input.length) { return this.finishToken(types$1$1.eof) } if (curContext.override) { return curContext.override(this) } else { this.readToken(this.fullCharCodeAtPos()); } }; pp$a.readToken = function(code) { // Identifier or keyword. '\uXXXX' sequences are allowed in // identifiers, so '\' also dispatches to that. if (isIdentifierStart$1(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) { return this.readWord() } return this.getTokenFromCode(code) }; pp$a.fullCharCodeAtPos = function() { var code = this.input.charCodeAt(this.pos); if (code <= 0xd7ff || code >= 0xdc00) { return code } var next = this.input.charCodeAt(this.pos + 1); return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 }; pp$a.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) { for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak$1(this.input, pos, this.pos)) > -1;) { ++this.curLine; pos = this.lineStart = nextBreak; } } if (this.options.onComment) { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition()); } }; pp$a.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$1(ch)) { ch = this.input.charCodeAt(++this.pos); } if (this.options.onComment) { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition()); } }; // Called at the start of the parse and after every token. Skips // whitespace and comments, and. pp$a.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$1.test(String.fromCharCode(ch))) { ++this.pos; } else { break loop } } } }; // Called at the end of every token. Sets `end`, `val`, and // maintains `context` and `exprAllowed`, and skips the space after // the token, so that the next one's `start` will point at the // right position. pp$a.finishToken = function(type, val) { this.end = this.pos; if (this.options.locations) { this.endLoc = this.curPosition(); } var prevType = this.type; this.type = type; this.value = val; this.updateContext(prevType); }; // ### Token reading // This is the function that is called to fetch the next token. It // is somewhat obscure, because it works in character codes rather // than characters, and because operator parsing has been inlined // into it. // // All in the name of speed. // pp$a.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$1$1.ellipsis) } else { ++this.pos; return this.finishToken(types$1$1.dot) } }; pp$a.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$1$1.assign, 2) } return this.finishOp(types$1$1.slash, 1) }; pp$a.readToken_mult_modulo_exp = function(code) { // '%*' var next = this.input.charCodeAt(this.pos + 1); var size = 1; var tokentype = code === 42 ? types$1$1.star : types$1$1.modulo; // exponentiation operator ** and **= if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { ++size; tokentype = types$1$1.starstar; next = this.input.charCodeAt(this.pos + 2); } if (next === 61) { return this.finishOp(types$1$1.assign, size + 1) } return this.finishOp(tokentype, size) }; pp$a.readToken_pipe_amp = function(code) { // '|&' var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (this.options.ecmaVersion >= 12) { var next2 = this.input.charCodeAt(this.pos + 2); if (next2 === 61) { return this.finishOp(types$1$1.assign, 3) } } return this.finishOp(code === 124 ? types$1$1.logicalOR : types$1$1.logicalAND, 2) } if (next === 61) { return this.finishOp(types$1$1.assign, 2) } return this.finishOp(code === 124 ? types$1$1.bitwiseOR : types$1$1.bitwiseAND, 1) }; pp$a.readToken_caret = function() { // '^' var next = this.input.charCodeAt(this.pos + 1); if (next === 61) { return this.finishOp(types$1$1.assign, 2) } return this.finishOp(types$1$1.bitwiseXOR, 1) }; pp$a.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$1.test(this.input.slice(this.lastTokEnd, this.pos)))) { // A `-->` line comment this.skipLineComment(3); this.skipSpace(); return this.nextToken() } return this.finishOp(types$1$1.incDec, 2) } if (next === 61) { return this.finishOp(types$1$1.assign, 2) } return this.finishOp(types$1$1.plusMin, 1) }; pp$a.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$1$1.assign, size + 1) } return this.finishOp(types$1$1.bitShift, size) } if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) { // `/gs; const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; const contextRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i; function esbuildScanPlugin(config, container, depImports, missing, entries) { const seen = new Map(); const resolve = async (id, importer, options) => { const key = id + (importer && path$o$1.dirname(importer)); if (seen.has(key)) { return seen.get(key); } const resolved = await container.resolveId(id, importer && normalizePath$3$1(importer), { ...options, scan: true, }); const res = resolved?.id; seen.set(key, res); return res; }; const include = config.optimizeDeps?.include; const exclude = [ ...(config.optimizeDeps?.exclude || []), '@vite/client', '@vite/env', ]; const externalUnlessEntry = ({ path }) => ({ path, external: !entries.includes(path), }); const doTransformGlobImport = async (contents, id, loader) => { let transpiledContents; // transpile because `transformGlobImport` only expects js if (loader !== 'js') { transpiledContents = (await transform$4(contents, { loader })).code; } else { transpiledContents = contents; } const result = await transformGlobImport(transpiledContents, id, config.root, resolve, config.isProduction); return result?.s.toString() || transpiledContents; }; return { name: 'vite:dep-scan', setup(build) { const scripts = {}; // external urls build.onResolve({ filter: externalRE }, ({ path }) => ({ path, external: true, })); // data urls build.onResolve({ filter: dataUrlRE }, ({ path }) => ({ path, external: true, })); // local scripts (``); preTransformRequest(server, modulePath, base); }; await traverseHtml(html, filename, (node) => { if (!nodeIsElement(node)) { return; } // script tags if (node.nodeName === 'script') { const { src, sourceCodeLocation, isModule } = getScriptInfo(node); if (src) { processNodeUrl(src, sourceCodeLocation, s, config, htmlPath, originalUrl, server); } else if (isModule && node.childNodes.length) { addInlineModule(node, 'js'); } } if (node.nodeName === 'style' && node.childNodes.length) { const children = node.childNodes[0]; styleUrl.push({ start: children.sourceCodeLocation.startOffset, end: children.sourceCodeLocation.endOffset, code: children.value, }); } // elements with [href/src] attrs const assetAttrs = assetAttrsConfig[node.nodeName]; if (assetAttrs) { for (const p of node.attrs) { const attrKey = getAttrKey(p); if (p.value && assetAttrs.includes(attrKey)) { processNodeUrl(p, node.sourceCodeLocation.attrs[attrKey], s, config, htmlPath, originalUrl); } } } }); await Promise.all(styleUrl.map(async ({ start, end, code }, index) => { const url = `${proxyModulePath}?html-proxy&direct&index=${index}.css`; // ensure module in graph after successful load const mod = await moduleGraph.ensureEntryFromUrl(url, false); ensureWatchedFile$1(watcher, mod.file, config.root); const result = await server.pluginContainer.transform(code, mod.id); let content = ''; if (result) { if (result.map) { if (result.map.mappings && !result.map.sourcesContent) { await injectSourcesContent(result.map, proxyModulePath, config.logger); } content = getCodeWithSourcemap('css', result.code, result.map); } else { content = result.code; } } s.overwrite(start, end, content); })); html = s.toString(); return { html, tags: [ { tag: 'script', attrs: { type: 'module', src: path$o$1.posix.join(base, CLIENT_PUBLIC_PATH), }, injectTo: 'head-prepend', }, ], }; }; function indexHtmlMiddleware(server) { // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` return async function viteIndexHtmlMiddleware(req, res, next) { if (res.writableEnded) { return next(); } const url = req.url && cleanUrl$1(req.url); // htmlFallbackMiddleware appends '.html' to URLs if (url?.endsWith('.html') && req.headers['sec-fetch-dest'] !== 'script') { const filename = getHtmlFilename(url, server); if (fs$l__default.existsSync(filename)) { try { let html = await fsp.readFile(filename, 'utf-8'); html = await server.transformIndexHtml(url, html, req.originalUrl); return send$2(req, res, html, 'html', { headers: server.config.server.headers, }); } catch (e) { return next(e); } } } next(); }; } function preTransformRequest(server, url, base) { if (!server.config.server.preTransformRequests) return; url = unwrapId(stripBase(url, base)); // transform all url as non-ssr as html includes client-side assets only server.transformRequest(url).catch((e) => { // Unexpected error, log the issue but avoid an unhandled exception server.config.logger.error(e.message); }); } const logTime = createDebugger$1('vite:time'); function timeMiddleware(root) { // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` return function viteTimeMiddleware(req, res, next) { const start = performance$1.now(); const end = res.end; res.end = (...args) => { logTime?.(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`); return end.call(res, ...args); }; next(); }; } class ModuleNode { /** * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870 */ constructor(url, setIsSelfAccepting = true) { /** * Resolved file system path + query */ this.id = null; this.file = null; this.importers = new Set(); this.importedModules = new Set(); this.acceptedHmrDeps = new Set(); this.acceptedHmrExports = null; this.importedBindings = null; this.transformResult = null; this.ssrTransformResult = null; this.ssrModule = null; this.ssrError = null; this.lastHMRTimestamp = 0; this.lastInvalidationTimestamp = 0; this.url = url; this.type = isDirectCSSRequest(url) ? 'css' : 'js'; if (setIsSelfAccepting) { this.isSelfAccepting = false; } } } class ModuleGraph { constructor(resolveId) { this.resolveId = resolveId; this.urlToModuleMap = new Map(); this.idToModuleMap = new Map(); // a single file may corresponds to multiple modules with different queries this.fileToModulesMap = new Map(); this.safeModulesPath = new Set(); /** * @internal */ this._unresolvedUrlToModuleMap = new Map(); /** * @internal */ this._ssrUnresolvedUrlToModuleMap = new Map(); } async getModuleByUrl(rawUrl, ssr) { // Quick path, if we already have a module for this rawUrl (even without extension) rawUrl = removeImportQuery(removeTimestampQuery(rawUrl)); const mod = this._getUnresolvedUrlToModule(rawUrl, ssr); if (mod) { return mod; } const [url] = await this._resolveUrl(rawUrl, ssr); return this.urlToModuleMap.get(url); } getModuleById(id) { return this.idToModuleMap.get(removeTimestampQuery(id)); } getModulesByFile(file) { return this.fileToModulesMap.get(file); } onFileChange(file) { const mods = this.getModulesByFile(file); if (mods) { const seen = new Set(); mods.forEach((mod) => { this.invalidateModule(mod, seen); }); } } invalidateModule(mod, seen = new Set(), timestamp = Date.now(), isHmr = false) { if (seen.has(mod)) { return; } seen.add(mod); if (isHmr) { mod.lastHMRTimestamp = timestamp; } else { // Save the timestamp for this invalidation, so we can avoid caching the result of possible already started // processing being done for this module mod.lastInvalidationTimestamp = timestamp; } // Don't invalidate mod.info and mod.meta, as they are part of the processing pipeline // Invalidating the transform result is enough to ensure this module is re-processed next time it is requested mod.transformResult = null; mod.ssrTransformResult = null; mod.ssrModule = null; mod.ssrError = null; mod.importers.forEach((importer) => { if (!importer.acceptedHmrDeps.has(mod)) { this.invalidateModule(importer, seen, timestamp, isHmr); } }); } invalidateAll() { const timestamp = Date.now(); const seen = new Set(); this.idToModuleMap.forEach((mod) => { this.invalidateModule(mod, seen, timestamp); }); } /** * Update the module graph based on a module's updated imports information * If there are dependencies that no longer have any importers, they are * returned as a Set. */ async updateModuleInfo(mod, importedModules, importedBindings, acceptedModules, acceptedExports, isSelfAccepting, ssr) { mod.isSelfAccepting = isSelfAccepting; const prevImports = mod.importedModules; let noLongerImported; let resolvePromises = []; let resolveResults = new Array(importedModules.size); let index = 0; // update import graph for (const imported of importedModules) { const nextIndex = index++; if (typeof imported === 'string') { resolvePromises.push(this.ensureEntryFromUrl(imported, ssr).then((dep) => { dep.importers.add(mod); resolveResults[nextIndex] = dep; })); } else { imported.importers.add(mod); resolveResults[nextIndex] = imported; } } if (resolvePromises.length) { await Promise.all(resolvePromises); } const nextImports = (mod.importedModules = new Set(resolveResults)); // remove the importer from deps that were imported but no longer are. prevImports.forEach((dep) => { if (!nextImports.has(dep)) { dep.importers.delete(mod); if (!dep.importers.size) { (noLongerImported || (noLongerImported = new Set())).add(dep); } } }); // update accepted hmr deps resolvePromises = []; resolveResults = new Array(acceptedModules.size); index = 0; for (const accepted of acceptedModules) { const nextIndex = index++; if (typeof accepted === 'string') { resolvePromises.push(this.ensureEntryFromUrl(accepted, ssr).then((dep) => { resolveResults[nextIndex] = dep; })); } else { resolveResults[nextIndex] = accepted; } } if (resolvePromises.length) { await Promise.all(resolvePromises); } mod.acceptedHmrDeps = new Set(resolveResults); // update accepted hmr exports mod.acceptedHmrExports = acceptedExports; mod.importedBindings = importedBindings; return noLongerImported; } async ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true) { return this._ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting); } /** * @internal */ async _ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true, // Optimization, avoid resolving the same url twice if the caller already did it resolved) { // Quick path, if we already have a module for this rawUrl (even without extension) rawUrl = removeImportQuery(removeTimestampQuery(rawUrl)); let mod = this._getUnresolvedUrlToModule(rawUrl, ssr); if (mod) { return mod; } const modPromise = (async () => { const [url, resolvedId, meta] = await this._resolveUrl(rawUrl, ssr, resolved); mod = this.idToModuleMap.get(resolvedId); if (!mod) { mod = new ModuleNode(url, setIsSelfAccepting); if (meta) mod.meta = meta; this.urlToModuleMap.set(url, mod); mod.id = resolvedId; this.idToModuleMap.set(resolvedId, mod); const file = (mod.file = cleanUrl$1(resolvedId)); let fileMappedModules = this.fileToModulesMap.get(file); if (!fileMappedModules) { fileMappedModules = new Set(); this.fileToModulesMap.set(file, fileMappedModules); } fileMappedModules.add(mod); } // multiple urls can map to the same module and id, make sure we register // the url to the existing module in that case else if (!this.urlToModuleMap.has(url)) { this.urlToModuleMap.set(url, mod); } this._setUnresolvedUrlToModule(rawUrl, mod, ssr); return mod; })(); // Also register the clean url to the module, so that we can short-circuit // resolving the same url twice this._setUnresolvedUrlToModule(rawUrl, modPromise, ssr); return modPromise; } // some deps, like a css file referenced via @import, don't have its own // url because they are inlined into the main css import. But they still // need to be represented in the module graph so that they can trigger // hmr in the importing css file. createFileOnlyEntry(file) { file = normalizePath$3$1(file); let fileMappedModules = this.fileToModulesMap.get(file); if (!fileMappedModules) { fileMappedModules = new Set(); this.fileToModulesMap.set(file, fileMappedModules); } const url = `${FS_PREFIX}${file}`; for (const m of fileMappedModules) { if (m.url === url || m.id === file) { return m; } } const mod = new ModuleNode(url); mod.file = file; fileMappedModules.add(mod); return mod; } // for incoming urls, it is important to: // 1. remove the HMR timestamp query (?t=xxxx) and the ?import query // 2. resolve its extension so that urls with or without extension all map to // the same module async resolveUrl(url, ssr) { url = removeImportQuery(removeTimestampQuery(url)); const mod = await this._getUnresolvedUrlToModule(url, ssr); if (mod?.id) { return [mod.url, mod.id, mod.meta]; } return this._resolveUrl(url, ssr); } /** * @internal */ _getUnresolvedUrlToModule(url, ssr) { return (ssr ? this._ssrUnresolvedUrlToModuleMap : this._unresolvedUrlToModuleMap).get(url); } /** * @internal */ _setUnresolvedUrlToModule(url, mod, ssr) { (ssr ? this._ssrUnresolvedUrlToModuleMap : this._unresolvedUrlToModuleMap).set(url, mod); } /** * @internal */ async _resolveUrl(url, ssr, alreadyResolved) { const resolved = alreadyResolved ?? (await this.resolveId(url, !!ssr)); const resolvedId = resolved?.id || url; if (url !== resolvedId && !url.includes('\0') && !url.startsWith(`virtual:`)) { const ext = extname(cleanUrl$1(resolvedId)); if (ext) { const pathname = cleanUrl$1(url); if (!pathname.endsWith(ext)) { url = pathname + ext + url.slice(pathname.length); } } } return [url, resolvedId, resolved?.meta]; } } var isWsl$2$1 = {exports: {}}; const fs$3$1 = require$$0__default__default; let isDocker$2$1; function hasDockerEnv$1() { try { fs$3$1.statSync('/.dockerenv'); return true; } catch (_) { return false; } } function hasDockerCGroup$1() { try { return fs$3$1.readFileSync('/proc/self/cgroup', 'utf8').includes('docker'); } catch (_) { return false; } } var isDocker_1$1 = () => { if (isDocker$2$1 === undefined) { isDocker$2$1 = hasDockerEnv$1() || hasDockerCGroup$1(); } return isDocker$2$1; }; const os$4 = require$$2$1; const fs$2$1 = require$$0__default__default; const isDocker$1$1 = isDocker_1$1; const isWsl$1$1 = () => { if (process.platform !== 'linux') { return false; } if (os$4.release().toLowerCase().includes('microsoft')) { if (isDocker$1$1()) { return false; } return true; } try { return fs$2$1.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ? !isDocker$1$1() : false; } catch (_) { return false; } }; if (process.env.__IS_WSL_TEST__) { isWsl$2$1.exports = isWsl$1$1; } else { isWsl$2$1.exports = isWsl$1$1(); } var isWslExports$1 = isWsl$2$1.exports; var defineLazyProp$1 = (object, propertyName, fn) => { const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true}); Object.defineProperty(object, propertyName, { configurable: true, enumerable: true, get() { const result = fn(); define(result); return result; }, set(value) { define(value); } }); return object; }; const path$3$1 = require$$0$4; const childProcess$3 = require$$2$1$1; const {promises: fs$1$1, constants: fsConstants$1} = require$$0__default__default; const isWsl$3 = isWslExports$1; const isDocker$3 = isDocker_1$1; const defineLazyProperty$1 = defineLazyProp$1; // Path to included `xdg-open`. const localXdgOpenPath$1 = path$3$1.join(__dirname$2, 'xdg-open'); const {platform: platform$1, arch: arch$1} = process; // Podman detection const hasContainerEnv$1 = () => { try { fs$1$1.statSync('/run/.containerenv'); return true; } catch { return false; } }; let cachedResult$1; function isInsideContainer$1() { if (cachedResult$1 === undefined) { cachedResult$1 = hasContainerEnv$1() || isDocker$3(); } return cachedResult$1; } /** Get the mount point for fixed drives in WSL. @inner @returns {string} The mount point. */ const getWslDrivesMountPoint$1 = (() => { // Default value for "root" param // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config const defaultMountPoint = '/mnt/'; let mountPoint; return async function () { if (mountPoint) { // Return memoized mount point value return mountPoint; } const configFilePath = '/etc/wsl.conf'; let isConfigFileExists = false; try { await fs$1$1.access(configFilePath, fsConstants$1.F_OK); isConfigFileExists = true; } catch {} if (!isConfigFileExists) { return defaultMountPoint; } const configContent = await fs$1$1.readFile(configFilePath, {encoding: 'utf8'}); const configMountPoint = /(?.*)/g.exec(configContent); if (!configMountPoint) { return defaultMountPoint; } mountPoint = configMountPoint.groups.mountPoint.trim(); mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`; return mountPoint; }; })(); const pTryEach$1 = async (array, mapper) => { let latestError; for (const item of array) { try { return await mapper(item); // eslint-disable-line no-await-in-loop } catch (error) { latestError = error; } } throw latestError; }; const baseOpen$1 = async options => { options = { wait: false, background: false, newInstance: false, allowNonzeroExitCode: false, ...options }; if (Array.isArray(options.app)) { return pTryEach$1(options.app, singleApp => baseOpen$1({ ...options, app: singleApp })); } let {name: app, arguments: appArguments = []} = options.app || {}; appArguments = [...appArguments]; if (Array.isArray(app)) { return pTryEach$1(app, appName => baseOpen$1({ ...options, app: { name: appName, arguments: appArguments } })); } let command; const cliArguments = []; const childProcessOptions = {}; if (platform$1 === 'darwin') { command = 'open'; if (options.wait) { cliArguments.push('--wait-apps'); } if (options.background) { cliArguments.push('--background'); } if (options.newInstance) { cliArguments.push('--new'); } if (app) { cliArguments.push('-a', app); } } else if (platform$1 === 'win32' || (isWsl$3 && !isInsideContainer$1() && !app)) { const mountPoint = await getWslDrivesMountPoint$1(); command = isWsl$3 ? `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`; cliArguments.push( '-NoProfile', '-NonInteractive', '–ExecutionPolicy', 'Bypass', '-EncodedCommand' ); if (!isWsl$3) { childProcessOptions.windowsVerbatimArguments = true; } const encodedArguments = ['Start']; if (options.wait) { encodedArguments.push('-Wait'); } if (app) { // Double quote with double quotes to ensure the inner quotes are passed through. // Inner quotes are delimited for PowerShell interpretation with backticks. encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList'); if (options.target) { appArguments.unshift(options.target); } } else if (options.target) { encodedArguments.push(`"${options.target}"`); } if (appArguments.length > 0) { appArguments = appArguments.map(arg => `"\`"${arg}\`""`); encodedArguments.push(appArguments.join(',')); } // Using Base64-encoded command, accepted by PowerShell, to allow special characters. options.target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64'); } else { if (app) { command = app; } else { // When bundled by Webpack, there's no actual package file path and no local `xdg-open`. const isBundled = !__dirname$2 || __dirname$2 === '/'; // Check if local `xdg-open` exists and is executable. let exeLocalXdgOpen = false; try { await fs$1$1.access(localXdgOpenPath$1, fsConstants$1.X_OK); exeLocalXdgOpen = true; } catch {} const useSystemXdgOpen = process.versions.electron || platform$1 === 'android' || isBundled || !exeLocalXdgOpen; command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath$1; } if (appArguments.length > 0) { cliArguments.push(...appArguments); } if (!options.wait) { // `xdg-open` will block the process unless stdio is ignored // and it's detached from the parent even if it's unref'd. childProcessOptions.stdio = 'ignore'; childProcessOptions.detached = true; } } if (options.target) { cliArguments.push(options.target); } if (platform$1 === 'darwin' && appArguments.length > 0) { cliArguments.push('--args', ...appArguments); } const subprocess = childProcess$3.spawn(command, cliArguments, childProcessOptions); if (options.wait) { return new Promise((resolve, reject) => { subprocess.once('error', reject); subprocess.once('close', exitCode => { if (!options.allowNonzeroExitCode && exitCode > 0) { reject(new Error(`Exited with code ${exitCode}`)); return; } resolve(subprocess); }); }); } subprocess.unref(); return subprocess; }; const open$1 = (target, options) => { if (typeof target !== 'string') { throw new TypeError('Expected a `target`'); } return baseOpen$1({ ...options, target }); }; const openApp$1 = (name, options) => { if (typeof name !== 'string') { throw new TypeError('Expected a `name`'); } const {arguments: appArguments = []} = options || {}; if (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) { throw new TypeError('Expected `appArguments` as Array type'); } return baseOpen$1({ ...options, app: { name, arguments: appArguments } }); }; function detectArchBinary$1(binary) { if (typeof binary === 'string' || Array.isArray(binary)) { return binary; } const {[arch$1]: archBinary} = binary; if (!archBinary) { throw new Error(`${arch$1} is not supported`); } return archBinary; } function detectPlatformBinary$1({[platform$1]: platformBinary}, {wsl}) { if (wsl && isWsl$3) { return detectArchBinary$1(wsl); } if (!platformBinary) { throw new Error(`${platform$1} is not supported`); } return detectArchBinary$1(platformBinary); } const apps$1 = {}; defineLazyProperty$1(apps$1, 'chrome', () => detectPlatformBinary$1({ darwin: 'google chrome', win32: 'chrome', linux: ['google-chrome', 'google-chrome-stable', 'chromium'] }, { wsl: { ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe', x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'] } })); defineLazyProperty$1(apps$1, 'firefox', () => detectPlatformBinary$1({ darwin: 'firefox', win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe', linux: 'firefox' }, { wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe' })); defineLazyProperty$1(apps$1, 'edge', () => detectPlatformBinary$1({ darwin: 'microsoft edge', win32: 'msedge', linux: ['microsoft-edge', 'microsoft-edge-dev'] }, { wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe' })); open$1.apps = apps$1; open$1.openApp = openApp$1; var open_1 = open$1; var open$1$1 = /*@__PURE__*/getDefaultExportFromCjs$2(open_1); var crossSpawn$1 = {exports: {}}; var windows$2; var hasRequiredWindows$1; function requireWindows$1 () { if (hasRequiredWindows$1) return windows$2; hasRequiredWindows$1 = 1; windows$2 = isexe; isexe.sync = sync; var fs = require$$0__default__default; function checkPathExt (path, options) { var pathext = options.pathExt !== undefined ? options.pathExt : process.env.PATHEXT; if (!pathext) { return true } pathext = pathext.split(';'); if (pathext.indexOf('') !== -1) { return true } for (var i = 0; i < pathext.length; i++) { var p = pathext[i].toLowerCase(); if (p && path.substr(-p.length).toLowerCase() === p) { return true } } return false } function checkStat (stat, path, options) { if (!stat.isSymbolicLink() && !stat.isFile()) { return false } return checkPathExt(path, options) } function isexe (path, options, cb) { fs.stat(path, function (er, stat) { cb(er, er ? false : checkStat(stat, path, options)); }); } function sync (path, options) { return checkStat(fs.statSync(path), path, options) } return windows$2; } var mode$1; var hasRequiredMode$1; function requireMode$1 () { if (hasRequiredMode$1) return mode$1; hasRequiredMode$1 = 1; mode$1 = isexe; isexe.sync = sync; var fs = require$$0__default__default; function isexe (path, options, cb) { fs.stat(path, function (er, stat) { cb(er, er ? false : checkStat(stat, options)); }); } function sync (path, options) { return checkStat(fs.statSync(path), options) } function checkStat (stat, options) { return stat.isFile() && checkMode(stat, options) } function checkMode (stat, options) { var mod = stat.mode; var uid = stat.uid; var gid = stat.gid; var myUid = options.uid !== undefined ? options.uid : process.getuid && process.getuid(); var myGid = options.gid !== undefined ? options.gid : process.getgid && process.getgid(); var u = parseInt('100', 8); var g = parseInt('010', 8); var o = parseInt('001', 8); var ug = u | g; var ret = (mod & o) || (mod & g) && gid === myGid || (mod & u) && uid === myUid || (mod & ug) && myUid === 0; return ret } return mode$1; } var core$1; if (process.platform === 'win32' || commonjsGlobal$2.TESTING_WINDOWS) { core$1 = requireWindows$1(); } else { core$1 = requireMode$1(); } var isexe_1$1 = isexe$1$2; isexe$1$2.sync = sync$b; function isexe$1$2 (path, options, cb) { if (typeof options === 'function') { cb = options; options = {}; } if (!cb) { if (typeof Promise !== 'function') { throw new TypeError('callback not provided') } return new Promise(function (resolve, reject) { isexe$1$2(path, options || {}, function (er, is) { if (er) { reject(er); } else { resolve(is); } }); }) } core$1(path, options || {}, function (er, is) { // ignore EACCES because that just means we aren't allowed to run it if (er) { if (er.code === 'EACCES' || options && options.ignoreErrors) { er = null; is = false; } } cb(er, is); }); } function sync$b (path, options) { // my kingdom for a filtered catch try { return core$1.sync(path, options || {}) } catch (er) { if (options && options.ignoreErrors || er.code === 'EACCES') { return false } else { throw er } } } const isWindows$7 = process.platform === 'win32' || process.env.OSTYPE === 'cygwin' || process.env.OSTYPE === 'msys'; const path$2$1 = require$$0$4; const COLON$1 = isWindows$7 ? ';' : ':'; const isexe$4 = isexe_1$1; const getNotFoundError$2 = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }); const getPathInfo$2 = (cmd, opt) => { const colon = opt.colon || COLON$1; // If it has a slash, then we don't bother searching the pathenv. // just check the file itself, and that's it. const pathEnv = cmd.match(/\//) || isWindows$7 && cmd.match(/\\/) ? [''] : ( [ // windows always checks the cwd first ...(isWindows$7 ? [process.cwd()] : []), ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */ '').split(colon), ] ); const pathExtExe = isWindows$7 ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' : ''; const pathExt = isWindows$7 ? pathExtExe.split(colon) : ['']; if (isWindows$7) { if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') pathExt.unshift(''); } return { pathEnv, pathExt, pathExtExe, } }; const which$1$2 = (cmd, opt, cb) => { if (typeof opt === 'function') { cb = opt; opt = {}; } if (!opt) opt = {}; const { pathEnv, pathExt, pathExtExe } = getPathInfo$2(cmd, opt); const found = []; const step = i => new Promise((resolve, reject) => { if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError$2(cmd)) const ppRaw = pathEnv[i]; const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; const pCmd = path$2$1.join(pathPart, cmd); const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; resolve(subStep(p, i, 0)); }); const subStep = (p, i, ii) => new Promise((resolve, reject) => { if (ii === pathExt.length) return resolve(step(i + 1)) const ext = pathExt[ii]; isexe$4(p + ext, { pathExt: pathExtExe }, (er, is) => { if (!er && is) { if (opt.all) found.push(p + ext); else return resolve(p + ext) } return resolve(subStep(p, i, ii + 1)) }); }); return cb ? step(0).then(res => cb(null, res), cb) : step(0) }; const whichSync$2 = (cmd, opt) => { opt = opt || {}; const { pathEnv, pathExt, pathExtExe } = getPathInfo$2(cmd, opt); const found = []; for (let i = 0; i < pathEnv.length; i ++) { const ppRaw = pathEnv[i]; const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; const pCmd = path$2$1.join(pathPart, cmd); const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; for (let j = 0; j < pathExt.length; j ++) { const cur = p + pathExt[j]; try { const is = isexe$4.sync(cur, { pathExt: pathExtExe }); if (is) { if (opt.all) found.push(cur); else return cur } } catch (ex) {} } } if (opt.all && found.length) return found if (opt.nothrow) return null throw getNotFoundError$2(cmd) }; var which_1$1 = which$1$2; which$1$2.sync = whichSync$2; var pathKey$1$1 = {exports: {}}; const pathKey$2 = (options = {}) => { const environment = options.env || process.env; const platform = options.platform || process.platform; if (platform !== 'win32') { return 'PATH'; } return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; }; pathKey$1$1.exports = pathKey$2; // TODO: Remove this for the next major release pathKey$1$1.exports.default = pathKey$2; var pathKeyExports$1 = pathKey$1$1.exports; const path$1$2 = require$$0$4; const which$3 = which_1$1; const getPathKey$1 = pathKeyExports$1; function resolveCommandAttempt$1(parsed, withoutPathExt) { const env = parsed.options.env || process.env; const cwd = process.cwd(); const hasCustomCwd = parsed.options.cwd != null; // Worker threads do not have process.chdir() const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; // If a custom `cwd` was specified, we need to change the process cwd // because `which` will do stat calls but does not support a custom cwd if (shouldSwitchCwd) { try { process.chdir(parsed.options.cwd); } catch (err) { /* Empty */ } } let resolved; try { resolved = which$3.sync(parsed.command, { path: env[getPathKey$1({ env })], pathExt: withoutPathExt ? path$1$2.delimiter : undefined, }); } catch (e) { /* Empty */ } finally { if (shouldSwitchCwd) { process.chdir(cwd); } } // If we successfully resolved, ensure that an absolute path is returned // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it if (resolved) { resolved = path$1$2.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); } return resolved; } function resolveCommand$1$1(parsed) { return resolveCommandAttempt$1(parsed) || resolveCommandAttempt$1(parsed, true); } var resolveCommand_1$1 = resolveCommand$1$1; var _escape$1 = {}; // See http://www.robvanderwoude.com/escapechars.php const metaCharsRegExp$1 = /([()\][%!^"`<>&|;, *?])/g; function escapeCommand$1(arg) { // Escape meta chars arg = arg.replace(metaCharsRegExp$1, '^$1'); return arg; } function escapeArgument$1(arg, doubleEscapeMetaChars) { // Convert to string arg = `${arg}`; // Algorithm below is based on https://qntm.org/cmd // Sequence of backslashes followed by a double quote: // double up all the backslashes and escape the double quote arg = arg.replace(/(\\*)"/g, '$1$1\\"'); // Sequence of backslashes followed by the end of the string // (which will become a double quote later): // double up all the backslashes arg = arg.replace(/(\\*)$/, '$1$1'); // All other backslashes occur literally // Quote the whole thing: arg = `"${arg}"`; // Escape meta chars arg = arg.replace(metaCharsRegExp$1, '^$1'); // Double escape meta chars if necessary if (doubleEscapeMetaChars) { arg = arg.replace(metaCharsRegExp$1, '^$1'); } return arg; } _escape$1.command = escapeCommand$1; _escape$1.argument = escapeArgument$1; var shebangRegex$1$1 = /^#!(.*)/; const shebangRegex$2 = shebangRegex$1$1; var shebangCommand$1$1 = (string = '') => { const match = string.match(shebangRegex$2); if (!match) { return null; } const [path, argument] = match[0].replace(/#! ?/, '').split(' '); const binary = path.split('/').pop(); if (binary === 'env') { return argument; } return argument ? `${binary} ${argument}` : binary; }; const fs$l = require$$0__default__default; const shebangCommand$2 = shebangCommand$1$1; function readShebang$1$1(command) { // Read the first 150 bytes from the file const size = 150; const buffer = Buffer.alloc(size); let fd; try { fd = fs$l.openSync(command, 'r'); fs$l.readSync(fd, buffer, 0, size, 0); fs$l.closeSync(fd); } catch (e) { /* Empty */ } // Attempt to extract shebang (null is returned if not a shebang) return shebangCommand$2(buffer.toString()); } var readShebang_1$1 = readShebang$1$1; const path$o = require$$0$4; const resolveCommand$2 = resolveCommand_1$1; const escape$1$1 = _escape$1; const readShebang$2 = readShebang_1$1; const isWin$1$1 = process.platform === 'win32'; const isExecutableRegExp$1 = /\.(?:com|exe)$/i; const isCmdShimRegExp$1 = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; function detectShebang$1(parsed) { parsed.file = resolveCommand$2(parsed); const shebang = parsed.file && readShebang$2(parsed.file); if (shebang) { parsed.args.unshift(parsed.file); parsed.command = shebang; return resolveCommand$2(parsed); } return parsed.file; } function parseNonShell$1(parsed) { if (!isWin$1$1) { return parsed; } // Detect & add support for shebangs const commandFile = detectShebang$1(parsed); // We don't need a shell if the command filename is an executable const needsShell = !isExecutableRegExp$1.test(commandFile); // If a shell is required, use cmd.exe and take care of escaping everything correctly // Note that `forceShell` is an hidden option used only in tests if (parsed.options.forceShell || needsShell) { // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, // we need to double escape them const needsDoubleEscapeMetaChars = isCmdShimRegExp$1.test(commandFile); // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) // This is necessary otherwise it will always fail with ENOENT in those cases parsed.command = path$o.normalize(parsed.command); // Escape command & arguments parsed.command = escape$1$1.command(parsed.command); parsed.args = parsed.args.map((arg) => escape$1$1.argument(arg, needsDoubleEscapeMetaChars)); const shellCommand = [parsed.command].concat(parsed.args).join(' '); parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; parsed.command = process.env.comspec || 'cmd.exe'; parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped } return parsed; } function parse$1$2(command, args, options) { // Normalize arguments, similar to nodejs if (args && !Array.isArray(args)) { options = args; args = null; } args = args ? args.slice(0) : []; // Clone array to avoid changing the original options = Object.assign({}, options); // Clone object to avoid changing the original // Build our parsed object const parsed = { command, args, options, file: undefined, original: { command, args, }, }; // Delegate further parsing to shell or non-shell return options.shell ? parsed : parseNonShell$1(parsed); } var parse_1$5 = parse$1$2; const isWin$2 = process.platform === 'win32'; function notFoundError$1(original, syscall) { return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { code: 'ENOENT', errno: 'ENOENT', syscall: `${syscall} ${original.command}`, path: original.command, spawnargs: original.args, }); } function hookChildProcess$1(cp, parsed) { if (!isWin$2) { return; } const originalEmit = cp.emit; cp.emit = function (name, arg1) { // If emitting "exit" event and exit code is 1, we need to check if // the command exists and emit an "error" instead // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 if (name === 'exit') { const err = verifyENOENT$1(arg1, parsed); if (err) { return originalEmit.call(cp, 'error', err); } } return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params }; } function verifyENOENT$1(status, parsed) { if (isWin$2 && status === 1 && !parsed.file) { return notFoundError$1(parsed.original, 'spawn'); } return null; } function verifyENOENTSync$1(status, parsed) { if (isWin$2 && status === 1 && !parsed.file) { return notFoundError$1(parsed.original, 'spawnSync'); } return null; } var enoent$1$1 = { hookChildProcess: hookChildProcess$1, verifyENOENT: verifyENOENT$1, verifyENOENTSync: verifyENOENTSync$1, notFoundError: notFoundError$1, }; const cp$1 = require$$2$1$1; const parse$i = parse_1$5; const enoent$2 = enoent$1$1; function spawn$1(command, args, options) { // Parse the arguments const parsed = parse$i(command, args, options); // Spawn the child process const spawned = cp$1.spawn(parsed.command, parsed.args, parsed.options); // Hook into child process "exit" event to emit an error if the command // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 enoent$2.hookChildProcess(spawned, parsed); return spawned; } function spawnSync$1(command, args, options) { // Parse the arguments const parsed = parse$i(command, args, options); // Spawn the child process const result = cp$1.spawnSync(parsed.command, parsed.args, parsed.options); // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 result.error = result.error || enoent$2.verifyENOENTSync(result.status, parsed); return result; } crossSpawn$1.exports = spawn$1; crossSpawn$1.exports.spawn = spawn$1; crossSpawn$1.exports.sync = spawnSync$1; crossSpawn$1.exports._parse = parse$i; crossSpawn$1.exports._enoent = enoent$2; var crossSpawnExports = crossSpawn$1.exports; var spawn$1$1 = /*@__PURE__*/getDefaultExportFromCjs$2(crossSpawnExports); /** * The following is modified based on source found in * https://github.com/facebook/create-react-app * * MIT Licensed * Copyright (c) 2015-present, Facebook, Inc. * https://github.com/facebook/create-react-app/blob/master/LICENSE * */ /** * Reads the BROWSER environment variable and decides what to do with it. */ function openBrowser(url, opt, logger) { // The browser executable to open. // See https://github.com/sindresorhus/open#app for documentation. const browser = typeof opt === 'string' ? opt : process.env.BROWSER || ''; if (browser.toLowerCase().endsWith('.js')) { executeNodeScript(browser, url, logger); } else if (browser.toLowerCase() !== 'none') { const browserArgs = process.env.BROWSER_ARGS ? process.env.BROWSER_ARGS.split(' ') : []; startBrowserProcess(browser, browserArgs, url); } } function executeNodeScript(scriptPath, url, logger) { const extraArgs = process.argv.slice(2); const child = spawn$1$1(process.execPath, [scriptPath, ...extraArgs, url], { stdio: 'inherit', }); child.on('close', (code) => { if (code !== 0) { logger.error(colors$1$1.red(`\nThe script specified as BROWSER environment variable failed.\n\n${colors$1$1.cyan(scriptPath)} exited with code ${code}.`), { error: null }); } }); } const supportedChromiumBrowsers = [ 'Google Chrome Canary', 'Google Chrome Dev', 'Google Chrome Beta', 'Google Chrome', 'Microsoft Edge', 'Brave Browser', 'Vivaldi', 'Chromium', ]; async function startBrowserProcess(browser, browserArgs, url) { // If we're on OS X, the user hasn't specifically // requested a different browser, we can try opening // a Chromium browser with AppleScript. This lets us reuse an // existing tab when possible instead of creating a new one. const preferredOSXBrowser = browser === 'google chrome' ? 'Google Chrome' : browser; const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' && (!preferredOSXBrowser || supportedChromiumBrowsers.includes(preferredOSXBrowser)); if (shouldTryOpenChromeWithAppleScript) { try { const ps = await execAsync('ps cax'); const openedBrowser = preferredOSXBrowser && ps.includes(preferredOSXBrowser) ? preferredOSXBrowser : supportedChromiumBrowsers.find((b) => ps.includes(b)); if (openedBrowser) { // Try our best to reuse existing tab with AppleScript await execAsync(`osascript openChrome.applescript "${encodeURI(url)}" "${openedBrowser}"`, { cwd: join$2(VITE_PACKAGE_DIR$1, 'bin'), }); return true; } } catch (err) { // Ignore errors } } // Another special case: on OS X, check if BROWSER has been set to "open". // In this case, instead of passing the string `open` to `open` function (which won't work), // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser): // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768 if (process.platform === 'darwin' && browser === 'open') { browser = undefined; } // Fallback to open // (It will always open new tab) try { const options = browser ? { app: { name: browser, arguments: browserArgs } } : {}; open$1$1(url, options).catch(() => { }); // Prevent `unhandledRejection` error. return true; } catch (err) { return false; } } function execAsync(command, options) { return new Promise((resolve, reject) => { exec(command, options, (error, stdout) => { if (error) { reject(error); } else { resolve(stdout.toString()); } }); }); } async function createServer(inlineConfig = {}) { return _createServer(inlineConfig, { ws: true }); } async function _createServer(inlineConfig = {}, options) { const config = await resolveConfig(inlineConfig, 'serve'); const { root, server: serverConfig } = config; const httpsOptions = await resolveHttpsConfig(config.server.https); const { middlewareMode } = serverConfig; const resolvedWatchOptions = resolveChokidarOptions(config, { disableGlobbing: true, ...serverConfig.watch, }); const middlewares = connect$1(); const httpServer = middlewareMode ? null : await resolveHttpServer(serverConfig, middlewares, httpsOptions); const ws = createWebSocketServer(httpServer, config, httpsOptions); if (httpServer) { setClientErrorHandler(httpServer, config.logger); } const watcher = chokidar.watch( // config file dependencies and env file might be outside of root [root, ...config.configFileDependencies, config.envDir], resolvedWatchOptions); const moduleGraph = new ModuleGraph((url, ssr) => container.resolveId(url, undefined, { ssr })); const container = await createPluginContainer(config, moduleGraph, watcher); const closeHttpServer = createServerCloseFn(httpServer); let exitProcess; const server = { config, middlewares, httpServer, watcher, pluginContainer: container, ws, moduleGraph, resolvedUrls: null, ssrTransform(code, inMap, url, originalCode = code) { return ssrTransform(code, inMap, url, originalCode, server.config); }, transformRequest(url, options) { return transformRequest(url, server, options); }, transformIndexHtml: null, async ssrLoadModule(url, opts) { if (isDepsOptimizerEnabled(config, true)) { await initDevSsrDepsOptimizer(config, server); } if (config.legacy?.buildSsrCjsExternalHeuristics) { await updateCjsSsrExternals(server); } return ssrLoadModule(url, server, undefined, undefined, opts?.fixStacktrace); }, ssrFixStacktrace(e) { ssrFixStacktrace(e, moduleGraph); }, ssrRewriteStacktrace(stack) { return ssrRewriteStacktrace(stack, moduleGraph); }, async reloadModule(module) { if (serverConfig.hmr !== false && module.file) { updateModules(module.file, [module], Date.now(), server); } }, async listen(port, isRestart) { await startServer(server, port); if (httpServer) { server.resolvedUrls = await resolveServerUrls(httpServer, config.server, config); if (!isRestart && config.server.open) server.openBrowser(); } return server; }, openBrowser() { const options = server.config.server; const url = server.resolvedUrls?.local[0]; if (url) { const path = typeof options.open === 'string' ? new URL(options.open, url).href : url; openBrowser(path, true, server.config.logger); } else { server.config.logger.warn('No URL available to open in browser'); } }, async close() { if (!middlewareMode) { process.off('SIGTERM', exitProcess); if (process.env.CI !== 'true') { process.stdin.off('end', exitProcess); } } await Promise.allSettled([ watcher.close(), ws.close(), container.close(), getDepsOptimizer(server.config)?.close(), getDepsOptimizer(server.config, true)?.close(), closeHttpServer(), ]); server.resolvedUrls = null; }, printUrls() { if (server.resolvedUrls) { printServerUrls(server.resolvedUrls, serverConfig.host, config.logger.info); } else if (middlewareMode) { throw new Error('cannot print server URLs in middleware mode.'); } else { throw new Error('cannot print server URLs before server.listen is called.'); } }, async restart(forceOptimize) { if (!server._restartPromise) { server._forceOptimizeOnRestart = !!forceOptimize; server._restartPromise = restartServer(server).finally(() => { server._restartPromise = null; server._forceOptimizeOnRestart = false; }); } return server._restartPromise; }, _ssrExternals: null, _restartPromise: null, _importGlobMap: new Map(), _forceOptimizeOnRestart: false, _pendingRequests: new Map(), _fsDenyGlob: picomatch$4$1(config.server.fs.deny, { matchBase: true }), _shortcutsOptions: undefined, }; server.transformIndexHtml = createDevHtmlTransformFn(server); if (!middlewareMode) { exitProcess = async () => { try { await server.close(); } finally { process.exit(); } }; process.once('SIGTERM', exitProcess); if (process.env.CI !== 'true') { process.stdin.on('end', exitProcess); } } const onHMRUpdate = async (file, configOnly) => { if (serverConfig.hmr !== false) { try { await handleHMRUpdate(file, server, configOnly); } catch (err) { ws.send({ type: 'error', err: prepareError(err), }); } } }; const onFileAddUnlink = async (file) => { file = normalizePath$3$1(file); await handleFileAddUnlink(file, server); await onHMRUpdate(file, true); }; watcher.on('change', async (file) => { file = normalizePath$3$1(file); // invalidate module graph cache on file change moduleGraph.onFileChange(file); await onHMRUpdate(file, false); }); watcher.on('add', onFileAddUnlink); watcher.on('unlink', onFileAddUnlink); ws.on('vite:invalidate', async ({ path, message }) => { const mod = moduleGraph.urlToModuleMap.get(path); if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0) { config.logger.info(colors$1$1.yellow(`hmr invalidate `) + colors$1$1.dim(path) + (message ? ` ${message}` : ''), { timestamp: true }); const file = getShortName(mod.file, config.root); updateModules(file, [...mod.importers], mod.lastHMRTimestamp, server, true); } }); if (!middlewareMode && httpServer) { httpServer.once('listening', () => { // update actual port since this may be different from initial value serverConfig.port = httpServer.address().port; }); } // apply server configuration hooks from plugins const postHooks = []; for (const hook of config.getSortedPluginHooks('configureServer')) { postHooks.push(await hook(server)); } // Internal middlewares ------------------------------------------------------ // request timer if (process.env.DEBUG) { middlewares.use(timeMiddleware(root)); } // cors (enabled by default) const { cors } = serverConfig; if (cors !== false) { middlewares.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors)); } // proxy const { proxy } = serverConfig; if (proxy) { middlewares.use(proxyMiddleware(httpServer, proxy, config)); } // base if (config.base !== '/') { middlewares.use(baseMiddleware(server)); } // open in editor support middlewares.use('/__open-in-editor', launchEditorMiddleware$1()); // ping request handler // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` middlewares.use(function viteHMRPingMiddleware(req, res, next) { if (req.headers['accept'] === 'text/x-vite-ping') { res.writeHead(204).end(); } else { next(); } }); // serve static files under /public // this applies before the transform middleware so that these files are served // as-is without transforms. if (config.publicDir) { middlewares.use(servePublicMiddleware(config.publicDir, config.server.headers)); } // main transform middleware middlewares.use(transformMiddleware(server)); // serve static files middlewares.use(serveRawFsMiddleware(server)); middlewares.use(serveStaticMiddleware(root, server)); // html fallback if (config.appType === 'spa' || config.appType === 'mpa') { middlewares.use(htmlFallbackMiddleware(root, config.appType === 'spa')); } // run post config hooks // This is applied before the html middleware so that user middleware can // serve custom content instead of index.html. postHooks.forEach((fn) => fn && fn()); if (config.appType === 'spa' || config.appType === 'mpa') { // transform index.html middlewares.use(indexHtmlMiddleware(server)); // handle 404s // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` middlewares.use(function vite404Middleware(_, res) { res.statusCode = 404; res.end(); }); } // error handler middlewares.use(errorMiddleware(server, middlewareMode)); // httpServer.listen can be called multiple times // when port when using next port number // this code is to avoid calling buildStart multiple times let initingServer; let serverInited = false; const initServer = async () => { if (serverInited) return; if (initingServer) return initingServer; initingServer = (async function () { await container.buildStart({}); // start deps optimizer after all container plugins are ready if (isDepsOptimizerEnabled(config, false)) { await initDepsOptimizer(config, server); } initingServer = undefined; serverInited = true; })(); return initingServer; }; if (!middlewareMode && httpServer) { // overwrite listen to init optimizer before server start const listen = httpServer.listen.bind(httpServer); httpServer.listen = (async (port, ...args) => { try { // ensure ws server started ws.listen(); await initServer(); } catch (e) { httpServer.emit('error', e); return; } return listen(port, ...args); }); } else { if (options.ws) { ws.listen(); } await initServer(); } return server; } async function startServer(server, inlinePort) { const httpServer = server.httpServer; if (!httpServer) { throw new Error('Cannot call server.listen in middleware mode.'); } const options = server.config.server; const port = inlinePort ?? options.port ?? DEFAULT_DEV_PORT; const hostname = await resolveHostname(options.host); await httpServerStart(httpServer, { port, strictPort: options.strictPort, host: hostname.host, logger: server.config.logger, }); } function createServerCloseFn(server) { if (!server) { return () => { }; } let hasListened = false; const openSockets = new Set(); server.on('connection', (socket) => { openSockets.add(socket); socket.on('close', () => { openSockets.delete(socket); }); }); server.once('listening', () => { hasListened = true; }); return () => new Promise((resolve, reject) => { openSockets.forEach((s) => s.destroy()); if (hasListened) { server.close((err) => { if (err) { reject(err); } else { resolve(); } }); } else { resolve(); } }); } function resolvedAllowDir(root, dir) { return normalizePath$3$1(path$o$1.resolve(root, dir)); } function resolveServerOptions(root, raw, logger) { const server = { preTransformRequests: true, ...raw, sourcemapIgnoreList: raw?.sourcemapIgnoreList === false ? () => false : raw?.sourcemapIgnoreList || isInNodeModules, middlewareMode: !!raw?.middlewareMode, }; let allowDirs = server.fs?.allow; const deny = server.fs?.deny || ['.env', '.env.*', '*.{crt,pem}']; if (!allowDirs) { allowDirs = [searchForWorkspaceRoot(root)]; } allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i)); // only push client dir when vite itself is outside-of-root const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR$1); if (!allowDirs.some((dir) => isParentDirectory(dir, resolvedClientDir))) { allowDirs.push(resolvedClientDir); } server.fs = { strict: server.fs?.strict ?? true, allow: allowDirs, deny, }; if (server.origin?.endsWith('/')) { server.origin = server.origin.slice(0, -1); logger.warn(colors$1$1.yellow(`${colors$1$1.bold('(!)')} server.origin should not end with "/". Using "${server.origin}" instead.`)); } return server; } async function restartServer(server) { global.__vite_start_time = performance$1.now(); const { port: prevPort, host: prevHost } = server.config.server; const shortcutsOptions = server._shortcutsOptions; const oldUrls = server.resolvedUrls; let inlineConfig = server.config.inlineConfig; if (server._forceOptimizeOnRestart) { inlineConfig = mergeConfig(inlineConfig, { optimizeDeps: { force: true, }, }); } let newServer = null; try { // delay ws server listen newServer = await _createServer(inlineConfig, { ws: false }); } catch (err) { server.config.logger.error(err.message, { timestamp: true, }); server.config.logger.error('server restart failed', { timestamp: true }); return; } await server.close(); // prevent new server `restart` function from calling newServer._restartPromise = server._restartPromise; Object.assign(server, newServer); const { logger, server: { port, host, middlewareMode }, } = server.config; if (!middlewareMode) { await server.listen(port, true); logger.info('server restarted.', { timestamp: true }); if ((port ?? DEFAULT_DEV_PORT) !== (prevPort ?? DEFAULT_DEV_PORT) || host !== prevHost || diffDnsOrderChange(oldUrls, newServer.resolvedUrls)) { logger.info(''); server.printUrls(); } } else { server.ws.listen(); logger.info('server restarted.', { timestamp: true }); } if (shortcutsOptions) { shortcutsOptions.print = false; bindShortcuts(newServer, shortcutsOptions); } // new server (the current server) can restart now newServer._restartPromise = null; } async function updateCjsSsrExternals(server) { if (!server._ssrExternals) { let knownImports = []; // Important! We use the non-ssr optimized deps to find known imports // Only the explicitly defined deps are optimized during dev SSR, so // we use the generated list from the scanned deps in regular dev. // This is part of the v2 externalization heuristics and it is kept // for backwards compatibility in case user needs to fallback to the // legacy scheme. It may be removed in a future v3 minor. const depsOptimizer = getDepsOptimizer(server.config, false); // non-ssr if (depsOptimizer) { await depsOptimizer.scanProcessing; knownImports = [ ...Object.keys(depsOptimizer.metadata.optimized), ...Object.keys(depsOptimizer.metadata.discovered), ]; } server._ssrExternals = cjsSsrResolveExternals(server.config, knownImports); } } function resolvePreviewOptions(preview, server) { // The preview server inherits every CommonServerOption from the `server` config // except for the port to enable having both the dev and preview servers running // at the same time without extra configuration return { port: preview?.port, strictPort: preview?.strictPort ?? server.strictPort, host: preview?.host ?? server.host, https: preview?.https ?? server.https, open: preview?.open ?? server.open, proxy: preview?.proxy ?? server.proxy, cors: preview?.cors ?? server.cors, headers: preview?.headers ?? server.headers, }; } function resolveSSROptions(ssr, preserveSymlinks, buildSsrCjsExternalHeuristics) { ssr ?? (ssr = {}); const optimizeDeps = ssr.optimizeDeps ?? {}; const format = buildSsrCjsExternalHeuristics ? 'cjs' : 'esm'; const target = 'node'; return { format, target, ...ssr, optimizeDeps: { disabled: true, ...optimizeDeps, esbuildOptions: { preserveSymlinks, ...optimizeDeps.esbuildOptions, }, }, }; } const debug$h = createDebugger$1('vite:config'); const promisifiedRealpath = promisify$5(fs$l__default.realpath); async function resolveConfig(inlineConfig, command, defaultMode = 'development', defaultNodeEnv = 'development') { let config = inlineConfig; let configFileDependencies = []; let mode = inlineConfig.mode || defaultMode; const isNodeEnvSet = !!process.env.NODE_ENV; const packageCache = new Map(); // some dependencies e.g. @vue/compiler-* relies on NODE_ENV for getting // production-specific behavior, so set it early on if (!isNodeEnvSet) { process.env.NODE_ENV = defaultNodeEnv; } const configEnv = { mode, command, ssrBuild: !!config.build?.ssr, }; let { configFile } = config; if (configFile !== false) { const loadResult = await loadConfigFromFile(configEnv, configFile, config.root, config.logLevel); if (loadResult) { config = mergeConfig(loadResult.config, config); configFile = loadResult.path; configFileDependencies = loadResult.dependencies; } } // user config may provide an alternative mode. But --mode has a higher priority mode = inlineConfig.mode || config.mode || mode; configEnv.mode = mode; const filterPlugin = (p) => { if (!p) { return false; } else if (!p.apply) { return true; } else if (typeof p.apply === 'function') { return p.apply({ ...config, mode }, configEnv); } else { return p.apply === command; } }; // Some plugins that aren't intended to work in the bundling of workers (doing post-processing at build time for example). // And Plugins may also have cached that could be corrupted by being used in these extra rollup calls. // So we need to separate the worker plugin from the plugin that vite needs to run. const rawWorkerUserPlugins = (await asyncFlatten(config.worker?.plugins || [])).filter(filterPlugin); // resolve plugins const rawUserPlugins = (await asyncFlatten(config.plugins || [])).filter(filterPlugin); const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawUserPlugins); // run config hooks const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins]; config = await runConfigHook(config, userPlugins, configEnv); // If there are custom commonjsOptions, don't force optimized deps for this test // even if the env var is set as it would interfere with the playground specs. if (!config.build?.commonjsOptions && process.env.VITE_TEST_WITHOUT_PLUGIN_COMMONJS) { config = mergeConfig(config, { optimizeDeps: { disabled: false }, ssr: { optimizeDeps: { disabled: false } }, }); config.build ?? (config.build = {}); config.build.commonjsOptions = { include: [] }; } // Define logger const logger = createLogger$1(config.logLevel, { allowClearScreen: config.clearScreen, customLogger: config.customLogger, }); // resolve root const resolvedRoot = normalizePath$3$1(config.root ? path$o$1.resolve(config.root) : process.cwd()); const clientAlias = [ { find: /^\/?@vite\/env/, replacement: path$o$1.posix.join(FS_PREFIX, normalizePath$3$1(ENV_ENTRY$1)), }, { find: /^\/?@vite\/client/, replacement: path$o$1.posix.join(FS_PREFIX, normalizePath$3$1(CLIENT_ENTRY$1)), }, ]; // resolve alias with internal client alias const resolvedAlias = normalizeAlias(mergeAlias(clientAlias, config.resolve?.alias || [])); const resolveOptions = { mainFields: config.resolve?.mainFields ?? DEFAULT_MAIN_FIELDS, browserField: config.resolve?.browserField ?? true, conditions: config.resolve?.conditions ?? [], extensions: config.resolve?.extensions ?? DEFAULT_EXTENSIONS$2, dedupe: config.resolve?.dedupe ?? [], preserveSymlinks: config.resolve?.preserveSymlinks ?? false, alias: resolvedAlias, }; // load .env files const envDir = config.envDir ? normalizePath$3$1(path$o$1.resolve(resolvedRoot, config.envDir)) : resolvedRoot; const userEnv = inlineConfig.envFile !== false && loadEnv$1(mode, envDir, resolveEnvPrefix(config)); // Note it is possible for user to have a custom mode, e.g. `staging` where // development-like behavior is expected. This is indicated by NODE_ENV=development // loaded from `.staging.env` and set by us as VITE_USER_NODE_ENV const userNodeEnv = process.env.VITE_USER_NODE_ENV; if (!isNodeEnvSet && userNodeEnv) { if (userNodeEnv === 'development') { process.env.NODE_ENV = 'development'; } else { // NODE_ENV=production is not supported as it could break HMR in dev for frameworks like Vue logger.warn(`NODE_ENV=${userNodeEnv} is not supported in the .env file. ` + `Only NODE_ENV=development is supported to create a development build of your project. ` + `If you need to set process.env.NODE_ENV, you can set it in the Vite config instead.`); } } const isProduction = process.env.NODE_ENV === 'production'; // resolve public base url const isBuild = command === 'build'; const relativeBaseShortcut = config.base === '' || config.base === './'; // During dev, we ignore relative base and fallback to '/' // For the SSR build, relative base isn't possible by means // of import.meta.url. const resolvedBase = relativeBaseShortcut ? !isBuild || config.build?.ssr ? '/' : './' : resolveBaseUrl(config.base, isBuild, logger) ?? '/'; const resolvedBuildOptions = resolveBuildOptions(config.build, logger, resolvedRoot); // resolve cache directory const pkgDir = findNearestPackageData(resolvedRoot, packageCache)?.dir; const cacheDir = normalizePath$3$1(config.cacheDir ? path$o$1.resolve(resolvedRoot, config.cacheDir) : pkgDir ? path$o$1.join(pkgDir, `node_modules/.vite`) : path$o$1.join(resolvedRoot, `.vite`)); const assetsFilter = config.assetsInclude && (!Array.isArray(config.assetsInclude) || config.assetsInclude.length) ? createFilter$3(config.assetsInclude) : () => false; // create an internal resolver to be used in special scenarios, e.g. // optimizer & handling css @imports const createResolver = (options) => { let aliasContainer; let resolverContainer; return async (id, importer, aliasOnly, ssr) => { let container; if (aliasOnly) { container = aliasContainer || (aliasContainer = await createPluginContainer({ ...resolved, plugins: [alias$1({ entries: resolved.resolve.alias })], })); } else { container = resolverContainer || (resolverContainer = await createPluginContainer({ ...resolved, plugins: [ alias$1({ entries: resolved.resolve.alias }), resolvePlugin({ ...resolved.resolve, root: resolvedRoot, isProduction, isBuild: command === 'build', ssrConfig: resolved.ssr, asSrc: true, preferRelative: false, tryIndex: true, ...options, idOnly: true, }), ], })); } return (await container.resolveId(id, importer, { ssr, scan: options?.scan, }))?.id; }; }; const { publicDir } = config; const resolvedPublicDir = publicDir !== false && publicDir !== '' ? path$o$1.resolve(resolvedRoot, typeof publicDir === 'string' ? publicDir : 'public') : ''; const server = resolveServerOptions(resolvedRoot, config.server, logger); const ssr = resolveSSROptions(config.ssr, resolveOptions.preserveSymlinks, config.legacy?.buildSsrCjsExternalHeuristics); const middlewareMode = config?.server?.middlewareMode; const optimizeDeps = config.optimizeDeps || {}; const BASE_URL = resolvedBase; // resolve worker let workerConfig = mergeConfig({}, config); const [workerPrePlugins, workerNormalPlugins, workerPostPlugins] = sortUserPlugins(rawWorkerUserPlugins); // run config hooks const workerUserPlugins = [ ...workerPrePlugins, ...workerNormalPlugins, ...workerPostPlugins, ]; workerConfig = await runConfigHook(workerConfig, workerUserPlugins, configEnv); const resolvedWorkerOptions = { format: workerConfig.worker?.format || 'iife', plugins: [], rollupOptions: workerConfig.worker?.rollupOptions || {}, getSortedPlugins: undefined, getSortedPluginHooks: undefined, }; const resolvedConfig = { configFile: configFile ? normalizePath$3$1(configFile) : undefined, configFileDependencies: configFileDependencies.map((name) => normalizePath$3$1(path$o$1.resolve(name))), inlineConfig, root: resolvedRoot, base: resolvedBase.endsWith('/') ? resolvedBase : resolvedBase + '/', rawBase: resolvedBase, resolve: resolveOptions, publicDir: resolvedPublicDir, cacheDir, command, mode, ssr, isWorker: false, mainConfig: null, isProduction, plugins: userPlugins, esbuild: config.esbuild === false ? false : { jsxDev: !isProduction, ...config.esbuild, }, server, build: resolvedBuildOptions, preview: resolvePreviewOptions(config.preview, server), envDir, env: { ...userEnv, BASE_URL, MODE: mode, DEV: !isProduction, PROD: isProduction, }, assetsInclude(file) { return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file); }, logger, packageCache, createResolver, optimizeDeps: { disabled: 'build', ...optimizeDeps, esbuildOptions: { preserveSymlinks: resolveOptions.preserveSymlinks, ...optimizeDeps.esbuildOptions, }, }, worker: resolvedWorkerOptions, appType: config.appType ?? (middlewareMode === 'ssr' ? 'custom' : 'spa'), experimental: { importGlobRestoreExtension: false, hmrPartialAccept: false, ...config.experimental, }, getSortedPlugins: undefined, getSortedPluginHooks: undefined, }; const resolved = { ...config, ...resolvedConfig, }; resolved.plugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins); Object.assign(resolved, createPluginHookUtils(resolved.plugins)); const workerResolved = { ...workerConfig, ...resolvedConfig, isWorker: true, mainConfig: resolved, }; resolvedConfig.worker.plugins = await resolvePlugins(workerResolved, workerPrePlugins, workerNormalPlugins, workerPostPlugins); Object.assign(resolvedConfig.worker, createPluginHookUtils(resolvedConfig.worker.plugins)); // call configResolved hooks await Promise.all([ ...resolved .getSortedPluginHooks('configResolved') .map((hook) => hook(resolved)), ...resolvedConfig.worker .getSortedPluginHooks('configResolved') .map((hook) => hook(workerResolved)), ]); // validate config if (middlewareMode === 'ssr') { logger.warn(colors$1$1.yellow(`Setting server.middlewareMode to 'ssr' is deprecated, set server.middlewareMode to \`true\`${config.appType === 'custom' ? '' : ` and appType to 'custom'`} instead`)); } if (middlewareMode === 'html') { logger.warn(colors$1$1.yellow(`Setting server.middlewareMode to 'html' is deprecated, set server.middlewareMode to \`true\` instead`)); } if (config.server?.force && !isBuild && config.optimizeDeps?.force === undefined) { resolved.optimizeDeps.force = true; logger.warn(colors$1$1.yellow(`server.force is deprecated, use optimizeDeps.force instead`)); } debug$h?.(`using resolved config: %O`, { ...resolved, plugins: resolved.plugins.map((p) => p.name), worker: { ...resolved.worker, plugins: resolved.worker.plugins.map((p) => p.name), }, }); if (config.build?.terserOptions && config.build.minify !== 'terser') { logger.warn(colors$1$1.yellow(`build.terserOptions is specified but build.minify is not set to use Terser. ` + `Note Vite now defaults to use esbuild for minification. If you still ` + `prefer Terser, set build.minify to "terser".`)); } // Check if all assetFileNames have the same reference. // If not, display a warn for user. const outputOption = config.build?.rollupOptions?.output ?? []; // Use isArray to narrow its type to array if (Array.isArray(outputOption)) { const assetFileNamesList = outputOption.map((output) => output.assetFileNames); if (assetFileNamesList.length > 1) { const firstAssetFileNames = assetFileNamesList[0]; const hasDifferentReference = assetFileNamesList.some((assetFileNames) => assetFileNames !== firstAssetFileNames); if (hasDifferentReference) { resolved.logger.warn(colors$1$1.yellow(` assetFileNames isn't equal for every build.rollupOptions.output. A single pattern across all outputs is supported by Vite. `)); } } } return resolved; } /** * Resolve base url. Note that some users use Vite to build for non-web targets like * electron or expects to deploy */ function resolveBaseUrl(base = '/', isBuild, logger) { if (base[0] === '.') { logger.warn(colors$1$1.yellow(colors$1$1.bold(`(!) invalid "base" option: ${base}. The value can only be an absolute ` + `URL, ./, or an empty string.`))); return '/'; } // external URL flag const isExternal = isExternalUrl(base); // no leading slash warn if (!isExternal && base[0] !== '/') { logger.warn(colors$1$1.yellow(colors$1$1.bold(`(!) "base" option should start with a slash.`))); } // parse base when command is serve or base is not External URL if (!isBuild || !isExternal) { base = new URL(base, 'http://vitejs.dev').pathname; // ensure leading slash if (base[0] !== '/') { base = '/' + base; } } return base; } function sortUserPlugins(plugins) { const prePlugins = []; const postPlugins = []; const normalPlugins = []; if (plugins) { plugins.flat().forEach((p) => { if (p.enforce === 'pre') prePlugins.push(p); else if (p.enforce === 'post') postPlugins.push(p); else normalPlugins.push(p); }); } return [prePlugins, normalPlugins, postPlugins]; } async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel) { const start = performance$1.now(); const getTime = () => `${(performance$1.now() - start).toFixed(2)}ms`; let resolvedPath; if (configFile) { // explicit config path is always resolved from cwd resolvedPath = path$o$1.resolve(configFile); } else { // implicit config file loaded from inline root (if present) // otherwise from cwd for (const filename of DEFAULT_CONFIG_FILES) { const filePath = path$o$1.resolve(configRoot, filename); if (!fs$l__default.existsSync(filePath)) continue; resolvedPath = filePath; break; } } if (!resolvedPath) { debug$h?.('no config file found.'); return null; } let isESM = false; if (/\.m[jt]s$/.test(resolvedPath)) { isESM = true; } else if (/\.c[jt]s$/.test(resolvedPath)) { isESM = false; } else { // check package.json for type: "module" and set `isESM` to true try { const pkg = lookupFile(configRoot, ['package.json']); isESM = !!pkg && JSON.parse(fs$l__default.readFileSync(pkg, 'utf-8')).type === 'module'; } catch (e) { } } try { const bundled = await bundleConfigFile(resolvedPath, isESM); const userConfig = await loadConfigFromBundledFile(resolvedPath, bundled.code, isESM); debug$h?.(`bundled config file loaded in ${getTime()}`); const config = await (typeof userConfig === 'function' ? userConfig(configEnv) : userConfig); if (!isObject$2$1(config)) { throw new Error(`config must export or return an object.`); } return { path: normalizePath$3$1(resolvedPath), config, dependencies: bundled.dependencies, }; } catch (e) { createLogger$1(logLevel).error(colors$1$1.red(`failed to load config from ${resolvedPath}`), { error: e }); throw e; } } async function bundleConfigFile(fileName, isESM) { const dirnameVarName = '__vite_injected_original_dirname'; const filenameVarName = '__vite_injected_original_filename'; const importMetaUrlVarName = '__vite_injected_original_import_meta_url'; const result = await build$3({ absWorkingDir: process.cwd(), entryPoints: [fileName], outfile: 'out.js', write: false, target: ['node14.18', 'node16'], platform: 'node', bundle: true, format: isESM ? 'esm' : 'cjs', mainFields: ['main'], sourcemap: 'inline', metafile: true, define: { __dirname: dirnameVarName, __filename: filenameVarName, 'import.meta.url': importMetaUrlVarName, }, plugins: [ { name: 'externalize-deps', setup(build) { const options = { root: path$o$1.dirname(fileName), isBuild: true, isProduction: true, preferRelative: false, tryIndex: true, mainFields: [], browserField: false, conditions: [], overrideConditions: ['node'], dedupe: [], extensions: DEFAULT_EXTENSIONS$2, preserveSymlinks: false, packageCache: new Map(), }; // externalize bare imports build.onResolve({ filter: /^[^.].*/ }, async ({ path: id, importer, kind }) => { if (kind === 'entry-point' || path$o$1.isAbsolute(id) || isBuiltin(id)) { return; } // partial deno support as `npm:` does not work with esbuild if (id.startsWith('npm:')) { return { external: true }; } const isIdESM = isESM || kind === 'dynamic-import'; let idFsPath = tryNodeResolve(id, importer, { ...options, isRequire: !isIdESM }, false)?.id; if (idFsPath && isIdESM) { idFsPath = pathToFileURL(idFsPath).href; } return { path: idFsPath, external: true, }; }); }, }, { name: 'inject-file-scope-variables', setup(build) { build.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => { const contents = await fs$l__default.promises.readFile(args.path, 'utf8'); const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path$o$1.dirname(args.path))};` + `const ${filenameVarName} = ${JSON.stringify(args.path)};` + `const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL(args.path).href)};`; return { loader: args.path.endsWith('ts') ? 'ts' : 'js', contents: injectValues + contents, }; }); }, }, ], }); const { text } = result.outputFiles[0]; return { code: text, dependencies: result.metafile ? Object.keys(result.metafile.inputs) : [], }; } const _require = createRequire$1(import.meta.url); async function loadConfigFromBundledFile(fileName, bundledCode, isESM) { // for esm, before we can register loaders without requiring users to run node // with --experimental-loader themselves, we have to do a hack here: // write it to disk, load it with native Node ESM, then delete the file. if (isESM) { const fileBase = `${fileName}.timestamp-${Date.now()}-${Math.random() .toString(16) .slice(2)}`; const fileNameTmp = `${fileBase}.mjs`; const fileUrl = `${pathToFileURL(fileBase)}.mjs`; await fsp.writeFile(fileNameTmp, bundledCode); try { return (await dynamicImport(fileUrl)).default; } finally { fs$l__default.unlink(fileNameTmp, () => { }); // Ignore errors } } // for cjs, we can register a custom loader via `_require.extensions` else { const extension = path$o$1.extname(fileName); // We don't use fsp.realpath() here because it has the same behaviour as // fs.realpath.native. On some Windows systems, it returns uppercase volume // letters (e.g. "C:\") while the Node.js loader uses lowercase volume letters. // See https://github.com/vitejs/vite/issues/12923 const realFileName = await promisifiedRealpath(fileName); const loaderExt = extension in _require.extensions ? extension : '.js'; const defaultLoader = _require.extensions[loaderExt]; _require.extensions[loaderExt] = (module, filename) => { if (filename === realFileName) { module._compile(bundledCode, filename); } else { defaultLoader(module, filename); } }; // clear cache in case of server restart delete _require.cache[_require.resolve(fileName)]; const raw = _require(fileName); _require.extensions[loaderExt] = defaultLoader; return raw.__esModule ? raw.default : raw; } } async function runConfigHook(config, plugins, configEnv) { let conf = config; for (const p of getSortedPluginsByHook('config', plugins)) { const hook = p.config; const handler = hook && 'handler' in hook ? hook.handler : hook; if (handler) { const res = await handler(conf, configEnv); if (res) { conf = mergeConfig(conf, res); } } } return conf; } function getDepOptimizationConfig(config, ssr) { return ssr ? config.ssr.optimizeDeps : config.optimizeDeps; } function isDepsOptimizerEnabled(config, ssr) { const { command } = config; const { disabled } = getDepOptimizationConfig(config, ssr); return !(disabled === true || (command === 'build' && disabled === 'build') || (command === 'serve' && disabled === 'dev')); } const { version: version$5 } = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url)).toString()); const VERSION = version$5; const VITE_PACKAGE_DIR = resolve$4( // import.meta.url is `dist/node/constants.js` after bundle fileURLToPath(import.meta.url), '../../..'); const CLIENT_ENTRY = resolve$4(VITE_PACKAGE_DIR, 'dist/client/client.mjs'); const ENV_ENTRY = resolve$4(VITE_PACKAGE_DIR, 'dist/client/env.mjs'); const CLIENT_DIR = path$o$1.dirname(CLIENT_ENTRY); const __filename = fileURLToPath(import.meta.url); const __dirname$1 = dirname$1(__filename); const require$1 = createRequire$1(import.meta.url); const __require = require$1; var commonjsGlobal$1 = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs$1 (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var picocolors = {exports: {}}; let tty = require$$0$3__default; let isColorSupported = !("NO_COLOR" in process.env || process.argv.includes("--no-color")) && ("FORCE_COLOR" in process.env || process.argv.includes("--color") || process.platform === "win32" || (tty.isatty(1) && process.env.TERM !== "dumb") || "CI" in process.env); let formatter = (open, close, replace = open) => input => { let string = "" + input; let index = string.indexOf(close, open.length); return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close }; let replaceClose = (string, close, replace, index) => { let start = string.substring(0, index) + replace; let end = string.substring(index + close.length); let nextIndex = end.indexOf(close); return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end }; let createColors = (enabled = isColorSupported) => ({ isColorSupported: enabled, reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String, bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String, dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String, italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String, underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String, inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String, hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String, strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String, black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String, red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String, green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String, yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String, blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String, magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String, cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String, white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String, gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String, bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String, bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String, bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String, bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String, bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String, bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String, bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String, bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String, }); picocolors.exports = createColors(); picocolors.exports.createColors = createColors; var picocolorsExports = picocolors.exports; var colors$1 = /*@__PURE__*/getDefaultExportFromCjs$1(picocolorsExports); var utils$k = {}; const path$n = require$$0$4; const WIN_SLASH$1 = '\\\\/'; const WIN_NO_SLASH$1 = `[^${WIN_SLASH$1}]`; /** * Posix glob regex */ const DOT_LITERAL$1 = '\\.'; const PLUS_LITERAL$1 = '\\+'; const QMARK_LITERAL$1 = '\\?'; const SLASH_LITERAL$1 = '\\/'; const ONE_CHAR$1 = '(?=.)'; const QMARK$1 = '[^/]'; const END_ANCHOR$1 = `(?:${SLASH_LITERAL$1}|$)`; const START_ANCHOR$1 = `(?:^|${SLASH_LITERAL$1})`; const DOTS_SLASH$1 = `${DOT_LITERAL$1}{1,2}${END_ANCHOR$1}`; const NO_DOT$1 = `(?!${DOT_LITERAL$1})`; const NO_DOTS$1 = `(?!${START_ANCHOR$1}${DOTS_SLASH$1})`; const NO_DOT_SLASH$1 = `(?!${DOT_LITERAL$1}{0,1}${END_ANCHOR$1})`; const NO_DOTS_SLASH$1 = `(?!${DOTS_SLASH$1})`; const QMARK_NO_DOT$1 = `[^.${SLASH_LITERAL$1}]`; const STAR$1 = `${QMARK$1}*?`; const POSIX_CHARS$1 = { DOT_LITERAL: DOT_LITERAL$1, PLUS_LITERAL: PLUS_LITERAL$1, QMARK_LITERAL: QMARK_LITERAL$1, SLASH_LITERAL: SLASH_LITERAL$1, ONE_CHAR: ONE_CHAR$1, QMARK: QMARK$1, END_ANCHOR: END_ANCHOR$1, DOTS_SLASH: DOTS_SLASH$1, NO_DOT: NO_DOT$1, NO_DOTS: NO_DOTS$1, NO_DOT_SLASH: NO_DOT_SLASH$1, NO_DOTS_SLASH: NO_DOTS_SLASH$1, QMARK_NO_DOT: QMARK_NO_DOT$1, STAR: STAR$1, START_ANCHOR: START_ANCHOR$1 }; /** * Windows glob regex */ const WINDOWS_CHARS$1 = { ...POSIX_CHARS$1, SLASH_LITERAL: `[${WIN_SLASH$1}]`, QMARK: WIN_NO_SLASH$1, STAR: `${WIN_NO_SLASH$1}*?`, DOTS_SLASH: `${DOT_LITERAL$1}{1,2}(?:[${WIN_SLASH$1}]|$)`, NO_DOT: `(?!${DOT_LITERAL$1})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH$1}])${DOT_LITERAL$1}{1,2}(?:[${WIN_SLASH$1}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL$1}{0,1}(?:[${WIN_SLASH$1}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL$1}{1,2}(?:[${WIN_SLASH$1}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH$1}]`, START_ANCHOR: `(?:^|[${WIN_SLASH$1}])`, END_ANCHOR: `(?:[${WIN_SLASH$1}]|$)` }; /** * POSIX Bracket Regex */ const POSIX_REGEX_SOURCE$1$1 = { 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 constants$6 = { MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1$1, // regular expressions 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, // Replace globs with equivalent patterns to reduce parsing time. REPLACEMENTS: { '***': '*', '**/**': '**', '**/**/**': '**' }, // Digits CHAR_0: 48, /* 0 */ CHAR_9: 57, /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 65, /* A */ CHAR_LOWERCASE_A: 97, /* a */ CHAR_UPPERCASE_Z: 90, /* Z */ CHAR_LOWERCASE_Z: 122, /* z */ CHAR_LEFT_PARENTHESES: 40, /* ( */ CHAR_RIGHT_PARENTHESES: 41, /* ) */ CHAR_ASTERISK: 42, /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: 38, /* & */ CHAR_AT: 64, /* @ */ CHAR_BACKWARD_SLASH: 92, /* \ */ CHAR_CARRIAGE_RETURN: 13, /* \r */ 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, /* \f */ 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, /* \n */ CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ 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, /* \t */ CHAR_UNDERSCORE: 95, /* _ */ CHAR_VERTICAL_LINE: 124, /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ SEP: path$n.sep, /** * Create EXTGLOB_CHARS */ extglobChars(chars) { return { '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, '?': { type: 'qmark', open: '(?:', close: ')?' }, '+': { type: 'plus', open: '(?:', close: ')+' }, '*': { type: 'star', open: '(?:', close: ')*' }, '@': { type: 'at', open: '(?:', close: ')' } }; }, /** * Create GLOB_CHARS */ globChars(win32) { return win32 === true ? WINDOWS_CHARS$1 : POSIX_CHARS$1; } }; (function (exports) { const path = require$$0$4; const win32 = process.platform === 'win32'; const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = constants$6; exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); exports.removeBackslashes = str => { return str.replace(REGEX_REMOVE_BACKSLASH, match => { return match === '\\' ? '' : match; }); }; exports.supportsLookbehinds = () => { const segs = process.version.slice(1).split('.').map(Number); if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { return true; } return false; }; exports.isWindows = options => { if (options && typeof options.windows === 'boolean') { return options.windows; } return win32 === true || path.sep === '\\'; }; exports.escapeLast = (input, char, lastIdx) => { const idx = input.lastIndexOf(char, lastIdx); if (idx === -1) return input; if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); return `${input.slice(0, idx)}\\${input.slice(idx)}`; }; exports.removePrefix = (input, state = {}) => { let output = input; if (output.startsWith('./')) { output = output.slice(2); state.prefix = './'; } return output; }; exports.wrapOutput = (input, state = {}, options = {}) => { const prepend = options.contains ? '' : '^'; const append = options.contains ? '' : '$'; let output = `${prepend}(?:${input})${append}`; if (state.negated === true) { output = `(?:^(?!${output}).*$)`; } return output; }; } (utils$k)); const utils$j = utils$k; const { CHAR_ASTERISK: CHAR_ASTERISK$1, /* * */ CHAR_AT: CHAR_AT$1, /* @ */ CHAR_BACKWARD_SLASH: CHAR_BACKWARD_SLASH$1, /* \ */ CHAR_COMMA: CHAR_COMMA$1, /* , */ CHAR_DOT: CHAR_DOT$1, /* . */ CHAR_EXCLAMATION_MARK: CHAR_EXCLAMATION_MARK$1, /* ! */ CHAR_FORWARD_SLASH: CHAR_FORWARD_SLASH$1, /* / */ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ CHAR_PLUS: CHAR_PLUS$1, /* + */ CHAR_QUESTION_MARK: CHAR_QUESTION_MARK$1, /* ? */ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */ } = constants$6; const isPathSeparator$1 = code => { return code === CHAR_FORWARD_SLASH$1 || code === CHAR_BACKWARD_SLASH$1; }; const depth$1 = token => { if (token.isPrefix !== true) { token.depth = token.isGlobstar ? Infinity : 1; } }; /** * Quickly scans a glob pattern and returns an object with a handful of * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). * * ```js * const pm = require('picomatch'); * console.log(pm.scan('foo/bar/*.js')); * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } * ``` * @param {String} `str` * @param {Object} `options` * @return {Object} Returns an object with tokens and regex source string. * @api public */ const scan$2 = (input, options) => { const opts = options || {}; const length = input.length - 1; const scanToEnd = opts.parts === true || opts.scanToEnd === true; const slashes = []; const tokens = []; const parts = []; let str = input; let index = -1; let start = 0; let lastIndex = 0; let isBrace = false; let isBracket = false; let isGlob = false; let isExtglob = false; let isGlobstar = false; let braceEscaped = false; let backslashes = false; let negated = false; let negatedExtglob = false; let finished = false; let braces = 0; let prev; let code; let token = { value: '', depth: 0, isGlob: false }; const eos = () => index >= length; const peek = () => str.charCodeAt(index + 1); const advance = () => { prev = code; return str.charCodeAt(++index); }; while (index < length) { code = advance(); let next; if (code === CHAR_BACKWARD_SLASH$1) { backslashes = token.backslashes = true; code = advance(); if (code === CHAR_LEFT_CURLY_BRACE$1) { braceEscaped = true; } continue; } if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) { braces++; while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH$1) { backslashes = token.backslashes = true; advance(); continue; } if (code === CHAR_LEFT_CURLY_BRACE$1) { braces++; continue; } if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (braceEscaped !== true && code === CHAR_COMMA$1) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_RIGHT_CURLY_BRACE$1) { braces--; if (braces === 0) { braceEscaped = false; isBrace = token.isBrace = true; finished = true; break; } } } if (scanToEnd === true) { continue; } break; } if (code === CHAR_FORWARD_SLASH$1) { slashes.push(index); tokens.push(token); token = { value: '', depth: 0, isGlob: false }; if (finished === true) continue; if (prev === CHAR_DOT$1 && index === (start + 1)) { start += 2; continue; } lastIndex = index + 1; continue; } if (opts.noext !== true) { const isExtglobChar = code === CHAR_PLUS$1 || code === CHAR_AT$1 || code === CHAR_ASTERISK$1 || code === CHAR_QUESTION_MARK$1 || code === CHAR_EXCLAMATION_MARK$1; if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) { isGlob = token.isGlob = true; isExtglob = token.isExtglob = true; finished = true; if (code === CHAR_EXCLAMATION_MARK$1 && index === start) { negatedExtglob = true; } if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH$1) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES$1) { isGlob = token.isGlob = true; finished = true; break; } } continue; } break; } } if (code === CHAR_ASTERISK$1) { if (prev === CHAR_ASTERISK$1) isGlobstar = token.isGlobstar = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_QUESTION_MARK$1) { isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_LEFT_SQUARE_BRACKET$1) { while (eos() !== true && (next = advance())) { if (next === CHAR_BACKWARD_SLASH$1) { backslashes = token.backslashes = true; advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { isBracket = token.isBracket = true; isGlob = token.isGlob = true; finished = true; break; } } if (scanToEnd === true) { continue; } break; } if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK$1 && index === start) { negated = token.negated = true; start++; continue; } if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) { isGlob = token.isGlob = true; if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_LEFT_PARENTHESES$1) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES$1) { finished = true; break; } } continue; } break; } if (isGlob === true) { finished = true; if (scanToEnd === true) { continue; } break; } } if (opts.noext === true) { isExtglob = false; isGlob = false; } let base = str; let prefix = ''; let glob = ''; if (start > 0) { prefix = str.slice(0, start); str = str.slice(start); lastIndex -= start; } if (base && isGlob === true && lastIndex > 0) { base = str.slice(0, lastIndex); glob = str.slice(lastIndex); } else if (isGlob === true) { base = ''; glob = str; } else { base = str; } if (base && base !== '' && base !== '/' && base !== str) { if (isPathSeparator$1(base.charCodeAt(base.length - 1))) { base = base.slice(0, -1); } } if (opts.unescape === true) { if (glob) glob = utils$j.removeBackslashes(glob); if (base && backslashes === true) { base = utils$j.removeBackslashes(base); } } const state = { prefix, input, start, base, glob, isBrace, isBracket, isGlob, isExtglob, isGlobstar, negated, negatedExtglob }; if (opts.tokens === true) { state.maxDepth = 0; if (!isPathSeparator$1(code)) { tokens.push(token); } state.tokens = tokens; } if (opts.parts === true || opts.tokens === true) { let prevIndex; for (let idx = 0; idx < slashes.length; idx++) { const n = prevIndex ? prevIndex + 1 : start; const i = slashes[idx]; const value = input.slice(n, i); if (opts.tokens) { if (idx === 0 && start !== 0) { tokens[idx].isPrefix = true; tokens[idx].value = prefix; } else { tokens[idx].value = value; } depth$1(tokens[idx]); state.maxDepth += tokens[idx].depth; } if (idx !== 0 || value !== '') { parts.push(value); } prevIndex = i; } if (prevIndex && prevIndex + 1 < input.length) { const value = input.slice(prevIndex + 1); parts.push(value); if (opts.tokens) { tokens[tokens.length - 1].value = value; depth$1(tokens[tokens.length - 1]); state.maxDepth += tokens[tokens.length - 1].depth; } } state.slashes = slashes; state.parts = parts; } return state; }; var scan_1$1 = scan$2; const constants$5 = constants$6; const utils$i = utils$k; /** * Constants */ const { MAX_LENGTH: MAX_LENGTH$1, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$2, REGEX_NON_SPECIAL_CHARS: REGEX_NON_SPECIAL_CHARS$1, REGEX_SPECIAL_CHARS_BACKREF: REGEX_SPECIAL_CHARS_BACKREF$1, REPLACEMENTS: REPLACEMENTS$1 } = constants$5; /** * Helpers */ const expandRange$1 = (args, options) => { if (typeof options.expandRange === 'function') { return options.expandRange(...args, options); } args.sort(); const value = `[${args.join('-')}]`; return value; }; /** * Create the message for a syntax error */ const syntaxError$1 = (type, char) => { return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; }; /** * Parse the given input string. * @param {String} input * @param {Object} options * @return {Object} */ const parse$h = (input, options) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } input = REPLACEMENTS$1[input] || input; const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; let len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } const bos = { type: 'bos', value: '', output: opts.prepend || '' }; const tokens = [bos]; const capture = opts.capture ? '' : '?:'; const win32 = utils$i.isWindows(options); // create constants based on platform, for windows or posix const PLATFORM_CHARS = constants$5.globChars(win32); const EXTGLOB_CHARS = constants$5.extglobChars(PLATFORM_CHARS); const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS; const globstar = opts => { return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const nodot = opts.dot ? '' : NO_DOT; const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; let star = opts.bash === true ? globstar(opts) : STAR; if (opts.capture) { star = `(${star})`; } // minimatch options support if (typeof opts.noext === 'boolean') { opts.noextglob = opts.noext; } const state = { input, index: -1, start: 0, dot: opts.dot === true, consumed: '', output: '', prefix: '', backtrack: false, negated: false, brackets: 0, braces: 0, parens: 0, quotes: 0, globstar: false, tokens }; input = utils$i.removePrefix(input, state); len = input.length; const extglobs = []; const braces = []; const stack = []; let prev = bos; let value; /** * Tokenizing helpers */ const eos = () => state.index === len - 1; const peek = state.peek = (n = 1) => input[state.index + n]; const advance = state.advance = () => input[++state.index] || ''; const remaining = () => input.slice(state.index + 1); const consume = (value = '', num = 0) => { state.consumed += value; state.index += num; }; const append = token => { state.output += token.output != null ? token.output : token.value; consume(token.value); }; const negate = () => { let count = 1; while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { advance(); state.start++; count++; } if (count % 2 === 0) { return false; } state.negated = true; state.start++; return true; }; const increment = type => { state[type]++; stack.push(type); }; const decrement = type => { state[type]--; stack.pop(); }; /** * Push tokens onto the tokens array. This helper speeds up * tokenizing by 1) helping us avoid backtracking as much as possible, * and 2) helping us avoid creating extra tokens when consecutive * characters are plain text. This improves performance and simplifies * lookbehinds. */ const push = tok => { if (prev.type === 'globstar') { const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { state.output = state.output.slice(0, -prev.output.length); prev.type = 'star'; prev.value = '*'; prev.output = star; state.output += prev.output; } } if (extglobs.length && tok.type !== 'paren') { extglobs[extglobs.length - 1].inner += tok.value; } if (tok.value || tok.output) append(tok); if (prev && prev.type === 'text' && tok.type === 'text') { prev.value += tok.value; prev.output = (prev.output || '') + tok.value; return; } tok.prev = prev; tokens.push(tok); prev = tok; }; const extglobOpen = (type, value) => { const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; token.prev = prev; token.parens = state.parens; token.output = state.output; const output = (opts.capture ? '(' : '') + token.open; increment('parens'); push({ type, value, output: state.output ? '' : ONE_CHAR }); push({ type: 'paren', extglob: true, value: advance(), output }); extglobs.push(token); }; const extglobClose = token => { let output = token.close + (opts.capture ? ')' : ''); let rest; if (token.type === 'negate') { let extglobStar = star; if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { extglobStar = globstar(opts); } if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { output = token.close = `)$))${extglobStar}`; } if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. // In this case, we need to parse the string and use it in the output of the original pattern. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. // // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. const expression = parse$h(rest, { ...options, fastpaths: false }).output; output = token.close = `)${expression})${extglobStar})`; } if (token.prev.type === 'bos') { state.negatedExtglob = true; } } push({ type: 'paren', extglob: true, value, output }); decrement('parens'); }; /** * Fast paths */ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { let backslashes = false; let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF$1, (m, esc, chars, first, rest, index) => { if (first === '\\') { backslashes = true; return m; } if (first === '?') { if (esc) { return esc + first + (rest ? QMARK.repeat(rest.length) : ''); } if (index === 0) { return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); } return QMARK.repeat(chars.length); } if (first === '.') { return DOT_LITERAL.repeat(chars.length); } if (first === '*') { if (esc) { return esc + first + (rest ? star : ''); } return star; } return esc ? m : `\\${m}`; }); if (backslashes === true) { if (opts.unescape === true) { output = output.replace(/\\/g, ''); } else { output = output.replace(/\\+/g, m => { return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); }); } } if (output === input && opts.contains === true) { state.output = input; return state; } state.output = utils$i.wrapOutput(output, state, options); return state; } /** * Tokenize input until we reach end-of-string */ while (!eos()) { value = advance(); if (value === '\u0000') { continue; } /** * Escaped characters */ if (value === '\\') { const next = peek(); if (next === '/' && opts.bash !== true) { continue; } if (next === '.' || next === ';') { continue; } if (!next) { value += '\\'; push({ type: 'text', value }); continue; } // collapse slashes to reduce potential for exploits const match = /^\\+/.exec(remaining()); let slashes = 0; if (match && match[0].length > 2) { slashes = match[0].length; state.index += slashes; if (slashes % 2 !== 0) { value += '\\'; } } if (opts.unescape === true) { value = advance(); } else { value += advance(); } if (state.brackets === 0) { push({ type: 'text', value }); continue; } } /** * If we're inside a regex character class, continue * until we reach the closing bracket. */ if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { if (opts.posix !== false && value === ':') { const inner = prev.value.slice(1); if (inner.includes('[')) { prev.posix = true; if (inner.includes(':')) { const idx = prev.value.lastIndexOf('['); const pre = prev.value.slice(0, idx); const rest = prev.value.slice(idx + 2); const posix = POSIX_REGEX_SOURCE$2[rest]; if (posix) { prev.value = pre + posix; state.backtrack = true; advance(); if (!bos.output && tokens.indexOf(prev) === 1) { bos.output = ONE_CHAR; } continue; } } } } if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { value = `\\${value}`; } if (value === ']' && (prev.value === '[' || prev.value === '[^')) { value = `\\${value}`; } if (opts.posix === true && value === '!' && prev.value === '[') { value = '^'; } prev.value += value; append({ value }); continue; } /** * If we're inside a quoted string, continue * until we reach the closing double quote. */ if (state.quotes === 1 && value !== '"') { value = utils$i.escapeRegex(value); prev.value += value; append({ value }); continue; } /** * Double quotes */ if (value === '"') { state.quotes = state.quotes === 1 ? 0 : 1; if (opts.keepQuotes === true) { push({ type: 'text', value }); } continue; } /** * Parentheses */ if (value === '(') { increment('parens'); push({ type: 'paren', value }); continue; } if (value === ')') { if (state.parens === 0 && opts.strictBrackets === true) { throw new SyntaxError(syntaxError$1('opening', '(')); } const extglob = extglobs[extglobs.length - 1]; if (extglob && state.parens === extglob.parens + 1) { extglobClose(extglobs.pop()); continue; } push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); decrement('parens'); continue; } /** * Square brackets */ if (value === '[') { if (opts.nobracket === true || !remaining().includes(']')) { if (opts.nobracket !== true && opts.strictBrackets === true) { throw new SyntaxError(syntaxError$1('closing', ']')); } value = `\\${value}`; } else { increment('brackets'); } push({ type: 'bracket', value }); continue; } if (value === ']') { if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { push({ type: 'text', value, output: `\\${value}` }); continue; } if (state.brackets === 0) { if (opts.strictBrackets === true) { throw new SyntaxError(syntaxError$1('opening', '[')); } push({ type: 'text', value, output: `\\${value}` }); continue; } decrement('brackets'); const prevValue = prev.value.slice(1); if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { value = `/${value}`; } prev.value += value; append({ value }); // when literal brackets are explicitly disabled // assume we should match with a regex character class if (opts.literalBrackets === false || utils$i.hasRegexChars(prevValue)) { continue; } const escaped = utils$i.escapeRegex(prev.value); state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled // assume we should escape the brackets to match literal characters if (opts.literalBrackets === true) { state.output += escaped; prev.value = escaped; continue; } // when the user specifies nothing, try to match both prev.value = `(${capture}${escaped}|${prev.value})`; state.output += prev.value; continue; } /** * Braces */ if (value === '{' && opts.nobrace !== true) { increment('braces'); const open = { type: 'brace', value, output: '(', outputIndex: state.output.length, tokensIndex: state.tokens.length }; braces.push(open); push(open); continue; } if (value === '}') { const brace = braces[braces.length - 1]; if (opts.nobrace === true || !brace) { push({ type: 'text', value, output: value }); continue; } let output = ')'; if (brace.dots === true) { const arr = tokens.slice(); const range = []; for (let i = arr.length - 1; i >= 0; i--) { tokens.pop(); if (arr[i].type === 'brace') { break; } if (arr[i].type !== 'dots') { range.unshift(arr[i].value); } } output = expandRange$1(range, opts); state.backtrack = true; } if (brace.comma !== true && brace.dots !== true) { const out = state.output.slice(0, brace.outputIndex); const toks = state.tokens.slice(brace.tokensIndex); brace.value = brace.output = '\\{'; value = output = '\\}'; state.output = out; for (const t of toks) { state.output += (t.output || t.value); } } push({ type: 'brace', value, output }); decrement('braces'); braces.pop(); continue; } /** * Pipes */ if (value === '|') { if (extglobs.length > 0) { extglobs[extglobs.length - 1].conditions++; } push({ type: 'text', value }); continue; } /** * Commas */ if (value === ',') { let output = value; const brace = braces[braces.length - 1]; if (brace && stack[stack.length - 1] === 'braces') { brace.comma = true; output = '|'; } push({ type: 'comma', value, output }); continue; } /** * Slashes */ if (value === '/') { // if the beginning of the glob is "./", advance the start // to the current index, and don't add the "./" characters // to the state. This greatly simplifies lookbehinds when // checking for BOS characters like "!" and "." (not "./") if (prev.type === 'dot' && state.index === state.start + 1) { state.start = state.index + 1; state.consumed = ''; state.output = ''; tokens.pop(); prev = bos; // reset "prev" to the first token continue; } push({ type: 'slash', value, output: SLASH_LITERAL }); continue; } /** * Dots */ if (value === '.') { if (state.braces > 0 && prev.type === 'dot') { if (prev.value === '.') prev.output = DOT_LITERAL; const brace = braces[braces.length - 1]; prev.type = 'dots'; prev.output += value; prev.value += value; brace.dots = true; continue; } if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { push({ type: 'text', value, output: DOT_LITERAL }); continue; } push({ type: 'dot', value, output: DOT_LITERAL }); continue; } /** * Question marks */ if (value === '?') { const isGroup = prev && prev.value === '('; if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('qmark', value); continue; } if (prev && prev.type === 'paren') { const next = peek(); let output = value; if (next === '<' && !utils$i.supportsLookbehinds()) { throw new Error('Node.js v10 or higher is required for regex lookbehinds'); } if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { output = `\\${value}`; } push({ type: 'text', value, output }); continue; } if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { push({ type: 'qmark', value, output: QMARK_NO_DOT }); continue; } push({ type: 'qmark', value, output: QMARK }); continue; } /** * Exclamation */ if (value === '!') { if (opts.noextglob !== true && peek() === '(') { if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { extglobOpen('negate', value); continue; } } if (opts.nonegate !== true && state.index === 0) { negate(); continue; } } /** * Plus */ if (value === '+') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('plus', value); continue; } if ((prev && prev.value === '(') || opts.regex === false) { push({ type: 'plus', value, output: PLUS_LITERAL }); continue; } if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { push({ type: 'plus', value }); continue; } push({ type: 'plus', value: PLUS_LITERAL }); continue; } /** * Plain text */ if (value === '@') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { push({ type: 'at', extglob: true, value, output: '' }); continue; } push({ type: 'text', value }); continue; } /** * Plain text */ if (value !== '*') { if (value === '$' || value === '^') { value = `\\${value}`; } const match = REGEX_NON_SPECIAL_CHARS$1.exec(remaining()); if (match) { value += match[0]; state.index += match[0].length; } push({ type: 'text', value }); continue; } /** * Stars */ if (prev && (prev.type === 'globstar' || prev.star === true)) { prev.type = 'star'; prev.star = true; prev.value += value; prev.output = star; state.backtrack = true; state.globstar = true; consume(value); continue; } let rest = remaining(); if (opts.noextglob !== true && /^\([^?]/.test(rest)) { extglobOpen('star', value); continue; } if (prev.type === 'star') { if (opts.noglobstar === true) { consume(value); continue; } const prior = prev.prev; const before = prior.prev; const isStart = prior.type === 'slash' || prior.type === 'bos'; const afterStar = before && (before.type === 'star' || before.type === 'globstar'); if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { push({ type: 'star', value, output: '' }); continue; } const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { push({ type: 'star', value, output: '' }); continue; } // strip consecutive `/**/` while (rest.slice(0, 3) === '/**') { const after = input[state.index + 4]; if (after && after !== '/') { break; } rest = rest.slice(3); consume('/**', 3); } if (prior.type === 'bos' && eos()) { prev.type = 'globstar'; prev.value += value; prev.output = globstar(opts); state.output = prev.output; state.globstar = true; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); prev.value += value; state.globstar = true; state.output += prior.output + prev.output; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { const end = rest[1] !== void 0 ? '|$' : ''; state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; prev.value += value; state.output += prior.output + prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } if (prior.type === 'bos' && rest[0] === '/') { prev.type = 'globstar'; prev.value += value; prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; state.output = prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } // remove single star from output state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar prev.type = 'globstar'; prev.output = globstar(opts); prev.value += value; // reset output with globstar state.output += prev.output; state.globstar = true; consume(value); continue; } const token = { type: 'star', value, output: star }; if (opts.bash === true) { token.output = '.*?'; if (prev.type === 'bos' || prev.type === 'slash') { token.output = nodot + token.output; } push(token); continue; } if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { token.output = value; push(token); continue; } if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { if (prev.type === 'dot') { state.output += NO_DOT_SLASH; prev.output += NO_DOT_SLASH; } else if (opts.dot === true) { state.output += NO_DOTS_SLASH; prev.output += NO_DOTS_SLASH; } else { state.output += nodot; prev.output += nodot; } if (peek() !== '*') { state.output += ONE_CHAR; prev.output += ONE_CHAR; } } push(token); } while (state.brackets > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ']')); state.output = utils$i.escapeLast(state.output, '['); decrement('brackets'); } while (state.parens > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ')')); state.output = utils$i.escapeLast(state.output, '('); decrement('parens'); } while (state.braces > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', '}')); state.output = utils$i.escapeLast(state.output, '{'); decrement('braces'); } if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); } // rebuild the output if we had to backtrack at any point if (state.backtrack === true) { state.output = ''; for (const token of state.tokens) { state.output += token.output != null ? token.output : token.value; if (token.suffix) { state.output += token.suffix; } } } return state; }; /** * Fast paths for creating regular expressions for common glob patterns. * This can significantly speed up processing and has very little downside * impact when none of the fast paths match. */ parse$h.fastpaths = (input, options) => { const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; const len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } input = REPLACEMENTS$1[input] || input; const win32 = utils$i.isWindows(options); // create constants based on platform, for windows or posix const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants$5.globChars(win32); const nodot = opts.dot ? NO_DOTS : NO_DOT; const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; const capture = opts.capture ? '' : '?:'; const state = { negated: false, prefix: '' }; let star = opts.bash === true ? '.*?' : STAR; if (opts.capture) { star = `(${star})`; } const globstar = opts => { if (opts.noglobstar === true) return star; return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const create = str => { switch (str) { case '*': return `${nodot}${ONE_CHAR}${star}`; case '.*': return `${DOT_LITERAL}${ONE_CHAR}${star}`; case '*.*': return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '*/*': return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; case '**': return nodot + globstar(opts); case '**/*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; case '**/*.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '**/.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; default: { const match = /^(.*?)\.(\w+)$/.exec(str); if (!match) return; const source = create(match[1]); if (!source) return; return source + DOT_LITERAL + match[2]; } } }; const output = utils$i.removePrefix(input, state); let source = create(output); if (source && opts.strictSlashes !== true) { source += `${SLASH_LITERAL}?`; } return source; }; var parse_1$3 = parse$h; const path$m = require$$0$4; const scan$1$1 = scan_1$1; const parse$g = parse_1$3; const utils$h = utils$k; const constants$4 = constants$6; const isObject$4 = val => val && typeof val === 'object' && !Array.isArray(val); /** * Creates a matcher function from one or more glob patterns. The * returned function takes a string to match as its first argument, * and returns true if the string is a match. The returned matcher * function also takes a boolean as the second argument that, when true, * returns an object with additional information. * * ```js * const picomatch = require('picomatch'); * // picomatch(glob[, options]); * * const isMatch = picomatch('*.!(*a)'); * console.log(isMatch('a.a')); //=> false * console.log(isMatch('a.b')); //=> true * ``` * @name picomatch * @param {String|Array} `globs` One or more glob patterns. * @param {Object=} `options` * @return {Function=} Returns a matcher function. * @api public */ const picomatch$5 = (glob, options, returnState = false) => { if (Array.isArray(glob)) { const fns = glob.map(input => picomatch$5(input, options, returnState)); const arrayMatcher = str => { for (const isMatch of fns) { const state = isMatch(str); if (state) return state; } return false; }; return arrayMatcher; } const isState = isObject$4(glob) && glob.tokens && glob.input; if (glob === '' || (typeof glob !== 'string' && !isState)) { throw new TypeError('Expected pattern to be a non-empty string'); } const opts = options || {}; const posix = utils$h.isWindows(options); const regex = isState ? picomatch$5.compileRe(glob, options) : picomatch$5.makeRe(glob, options, false, true); const state = regex.state; delete regex.state; let isIgnored = () => false; if (opts.ignore) { const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; isIgnored = picomatch$5(opts.ignore, ignoreOpts, returnState); } const matcher = (input, returnObject = false) => { const { isMatch, match, output } = picomatch$5.test(input, regex, options, { glob, posix }); const result = { glob, state, regex, posix, input, output, match, isMatch }; if (typeof opts.onResult === 'function') { opts.onResult(result); } if (isMatch === false) { result.isMatch = false; return returnObject ? result : false; } if (isIgnored(input)) { if (typeof opts.onIgnore === 'function') { opts.onIgnore(result); } result.isMatch = false; return returnObject ? result : false; } if (typeof opts.onMatch === 'function') { opts.onMatch(result); } return returnObject ? result : true; }; if (returnState) { matcher.state = state; } return matcher; }; /** * Test `input` with the given `regex`. This is used by the main * `picomatch()` function to test the input string. * * ```js * const picomatch = require('picomatch'); * // picomatch.test(input, regex[, options]); * * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } * ``` * @param {String} `input` String to test. * @param {RegExp} `regex` * @return {Object} Returns an object with matching info. * @api public */ picomatch$5.test = (input, regex, options, { glob, posix } = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected input to be a string'); } if (input === '') { return { isMatch: false, output: '' }; } const opts = options || {}; const format = opts.format || (posix ? utils$h.toPosixSlashes : null); let match = input === glob; let output = (match && format) ? format(input) : input; if (match === false) { output = format ? format(input) : input; match = output === glob; } if (match === false || opts.capture === true) { if (opts.matchBase === true || opts.basename === true) { match = picomatch$5.matchBase(input, regex, options, posix); } else { match = regex.exec(output); } } return { isMatch: Boolean(match), match, output }; }; /** * Match the basename of a filepath. * * ```js * const picomatch = require('picomatch'); * // picomatch.matchBase(input, glob[, options]); * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true * ``` * @param {String} `input` String to test. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). * @return {Boolean} * @api public */ picomatch$5.matchBase = (input, glob, options, posix = utils$h.isWindows(options)) => { const regex = glob instanceof RegExp ? glob : picomatch$5.makeRe(glob, options); return regex.test(path$m.basename(input)); }; /** * Returns true if **any** of the given glob `patterns` match the specified `string`. * * ```js * const picomatch = require('picomatch'); * // picomatch.isMatch(string, patterns[, options]); * * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true * console.log(picomatch.isMatch('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). * @return {Boolean} Returns true if any patterns match `str` * @api public */ picomatch$5.isMatch = (str, patterns, options) => picomatch$5(patterns, options)(str); /** * Parse a glob pattern to create the source string for a regular * expression. * * ```js * const picomatch = require('picomatch'); * const result = picomatch.parse(pattern[, options]); * ``` * @param {String} `pattern` * @param {Object} `options` * @return {Object} Returns an object with useful properties and output to be used as a regex source string. * @api public */ picomatch$5.parse = (pattern, options) => { if (Array.isArray(pattern)) return pattern.map(p => picomatch$5.parse(p, options)); return parse$g(pattern, { ...options, fastpaths: false }); }; /** * Scan a glob pattern to separate the pattern into segments. * * ```js * const picomatch = require('picomatch'); * // picomatch.scan(input[, options]); * * const result = picomatch.scan('!./foo/*.js'); * console.log(result); * { prefix: '!./', * input: '!./foo/*.js', * start: 3, * base: 'foo', * glob: '*.js', * isBrace: false, * isBracket: false, * isGlob: true, * isExtglob: false, * isGlobstar: false, * negated: true } * ``` * @param {String} `input` Glob pattern to scan. * @param {Object} `options` * @return {Object} Returns an object with * @api public */ picomatch$5.scan = (input, options) => scan$1$1(input, options); /** * Compile a regular expression from the `state` object returned by the * [parse()](#parse) method. * * @param {Object} `state` * @param {Object} `options` * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. * @return {RegExp} * @api public */ picomatch$5.compileRe = (state, options, returnOutput = false, returnState = false) => { if (returnOutput === true) { return state.output; } const opts = options || {}; const prepend = opts.contains ? '' : '^'; const append = opts.contains ? '' : '$'; let source = `${prepend}(?:${state.output})${append}`; if (state && state.negated === true) { source = `^(?!${source}).*$`; } const regex = picomatch$5.toRegex(source, options); if (returnState === true) { regex.state = state; } return regex; }; /** * Create a regular expression from a parsed glob pattern. * * ```js * const picomatch = require('picomatch'); * const state = picomatch.parse('*.js'); * // picomatch.compileRe(state[, options]); * * console.log(picomatch.compileRe(state)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `state` The object returned from the `.parse` method. * @param {Object} `options` * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. * @return {RegExp} Returns a regex created from the given pattern. * @api public */ picomatch$5.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { if (!input || typeof input !== 'string') { throw new TypeError('Expected a non-empty string'); } let parsed = { negated: false, fastpaths: true }; if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { parsed.output = parse$g.fastpaths(input, options); } if (!parsed.output) { parsed = parse$g(input, options); } return picomatch$5.compileRe(parsed, options, returnOutput, returnState); }; /** * Create a regular expression from the given regex source string. * * ```js * const picomatch = require('picomatch'); * // picomatch.toRegex(source[, options]); * * const { output } = picomatch.parse('*.js'); * console.log(picomatch.toRegex(output)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `source` Regular expression source string. * @param {Object} `options` * @return {RegExp} * @api public */ picomatch$5.toRegex = (source, options) => { try { const opts = options || {}; return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); } catch (err) { if (options && options.debug === true) throw err; return /$^/; } }; /** * Picomatch constants. * @return {Object} */ picomatch$5.constants = constants$4; /** * Expose "picomatch" */ var picomatch_1$1 = picomatch$5; var picomatch$3 = picomatch_1$1; var picomatch$4 = /*@__PURE__*/getDefaultExportFromCjs$1(picomatch$3); // Helper since Typescript can't detect readonly arrays with Array.isArray function isArray$2(arg) { return Array.isArray(arg); } function ensureArray$2(thing) { if (isArray$2(thing)) return thing; if (thing == null) return []; return [thing]; } const normalizePath$5 = function normalizePath(filename) { return filename.split(win32$1.sep).join(posix$2.sep); }; function getMatcherString$1(id, resolutionBase) { if (resolutionBase === false || isAbsolute$3(id) || id.startsWith('*')) { return normalizePath$5(id); } // resolve('') is valid and will default to process.cwd() const basePath = normalizePath$5(resolve$5(resolutionBase || '')) // escape all possible (posix + win) path characters that might interfere with regex .replace(/[-^$*+?.()|[\]{}]/g, '\\$&'); // Note that we use posix.join because: // 1. the basePath has been normalized to use / // 2. the incoming glob (id) matcher, also uses / // otherwise Node will force backslash (\) on windows return posix$2.join(basePath, normalizePath$5(id)); } const createFilter$1 = function createFilter(include, exclude, options) { const resolutionBase = options && options.resolve; const getMatcher = (id) => id instanceof RegExp ? id : { test: (what) => { // this refactor is a tad overly verbose but makes for easy debugging const pattern = getMatcherString$1(id, resolutionBase); const fn = picomatch$4(pattern, { dot: true }); const result = fn(what); return result; } }; const includeMatchers = ensureArray$2(include).map(getMatcher); const excludeMatchers = ensureArray$2(exclude).map(getMatcher); return function result(id) { if (typeof id !== 'string') return false; if (/\0/.test(id)) return false; const pathId = normalizePath$5(id); for (let i = 0; i < excludeMatchers.length; ++i) { const matcher = excludeMatchers[i]; if (matcher.test(pathId)) return false; } for (let i = 0; i < includeMatchers.length; ++i) { const matcher = includeMatchers[i]; if (matcher.test(pathId)) return true; } return !includeMatchers.length; }; }; const reservedWords$1 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'; const builtins$1 = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'; const forbiddenIdentifiers$1 = new Set(`${reservedWords$1} ${builtins$1}`.split(' ')); forbiddenIdentifiers$1.add(''); var old$1 = {}; // 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 pathModule = require$$0$4; var isWindows$6 = process.platform === 'win32'; var fs$k = require$$0__default__default; // JavaScript implementation of realpath, ported from node pre-v6 var DEBUG$1 = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. var callback; if (DEBUG$1) { var backtrace = new Error; callback = debugCallback; } else callback = missingCallback; return callback; function debugCallback(err) { if (err) { backtrace.message = err.message; err = backtrace; missingCallback(err); } } function missingCallback(err) { if (err) { if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs else if (!process.noDeprecation) { var msg = 'fs: missing callback ' + (err.stack || err.message); if (process.traceDeprecation) console.trace(msg); else console.error(msg); } } } } function maybeCallback(cb) { return typeof cb === 'function' ? cb : rethrow(); } // Regexp that finds the next partion of a (partial) path // result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] if (isWindows$6) { var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; } else { var nextPartRe = /(.*?)(?:[\/]+|$)/g; } // Regex to find the device root, including trailing slash. E.g. 'c:\\'. if (isWindows$6) { var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; } else { var splitRootRe = /^[\/]*/; } old$1.realpathSync = function realpathSync(p, cache) { // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return cache[p]; } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows$6 && !knownHard[base]) { fs$k.lstatSync(base); knownHard[base] = true; } } // walk down the path, swapping out linked pathparts for their real // values // NB: p.length changes. while (pos < p.length) { // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { continue; } var resolvedLink; if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // some known symbolic link. no need to stat again. resolvedLink = cache[base]; } else { var stat = fs$k.lstatSync(base); if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; continue; } // read the link if it wasn't read before // dev/ino always return 0 on windows, so skip the check. var linkTarget = null; if (!isWindows$6) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { linkTarget = seenLinks[id]; } } if (linkTarget === null) { fs$k.statSync(base); linkTarget = fs$k.readlinkSync(base); } resolvedLink = pathModule.resolve(previous, linkTarget); // track this, if given a cache. if (cache) cache[base] = resolvedLink; if (!isWindows$6) seenLinks[id] = linkTarget; } // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } if (cache) cache[original] = p; return p; }; old$1.realpath = function realpath(p, cache, cb) { if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return process.nextTick(cb.bind(null, null, cache[p])); } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows$6 && !knownHard[base]) { fs$k.lstat(base, function(err) { if (err) return cb(err); knownHard[base] = true; LOOP(); }); } else { process.nextTick(LOOP); } } // walk down the path, swapping out linked pathparts for their real // values function LOOP() { // stop if scanned past end of path if (pos >= p.length) { if (cache) cache[original] = p; return cb(null, p); } // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { return process.nextTick(LOOP); } if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // known symbolic link. no need to stat again. return gotResolvedLink(cache[base]); } return fs$k.lstat(base, gotStat); } function gotStat(err, stat) { if (err) return cb(err); // if not a symlink, skip to the next path part if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; return process.nextTick(LOOP); } // stat & read the link if not read before // call gotTarget as soon as the link target is known // dev/ino always return 0 on windows, so skip the check. if (!isWindows$6) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { return gotTarget(null, seenLinks[id], base); } } fs$k.stat(base, function(err) { if (err) return cb(err); fs$k.readlink(base, function(err, target) { if (!isWindows$6) seenLinks[id] = target; gotTarget(err, target); }); }); } function gotTarget(err, target, base) { if (err) return cb(err); var resolvedLink = pathModule.resolve(previous, target); if (cache) cache[base] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } }; var fs_realpath = realpath$2; realpath$2.realpath = realpath$2; realpath$2.sync = realpathSync; realpath$2.realpathSync = realpathSync; realpath$2.monkeypatch = monkeypatch; realpath$2.unmonkeypatch = unmonkeypatch; var fs$j = require$$0__default__default; var origRealpath = fs$j.realpath; var origRealpathSync = fs$j.realpathSync; var version$4 = process.version; var ok = /^v[0-5]\./.test(version$4); var old = old$1; function newError (er) { return er && er.syscall === 'realpath' && ( er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG' ) } function realpath$2 (p, cache, cb) { if (ok) { return origRealpath(p, cache, cb) } if (typeof cache === 'function') { cb = cache; cache = null; } origRealpath(p, cache, function (er, result) { if (newError(er)) { old.realpath(p, cache, cb); } else { cb(er, result); } }); } function realpathSync (p, cache) { if (ok) { return origRealpathSync(p, cache) } try { return origRealpathSync(p, cache) } catch (er) { if (newError(er)) { return old.realpathSync(p, cache) } else { throw er } } } function monkeypatch () { fs$j.realpath = realpath$2; fs$j.realpathSync = realpathSync; } function unmonkeypatch () { fs$j.realpath = origRealpath; fs$j.realpathSync = origRealpathSync; } const isWindows$5 = typeof process === 'object' && process && process.platform === 'win32'; var path$k = isWindows$5 ? { sep: '\\' } : { sep: '/' }; var balancedMatch = balanced$1; function balanced$1(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r = range$1(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced$1.range = range$1; function range$1(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { if(a===b) { return [ai, bi]; } begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 1); } else if (begs.length == 1) { result = [ begs.pop(), bi ]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [ left, right ]; } } return result; } var balanced = balancedMatch; var braceExpansion = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split('\\\\').join(escSlash) .split('\\{').join(escOpen) .split('\\}').join(escClose) .split('\\,').join(escComma) .split('\\.').join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join('\\') .split(escOpen).join('{') .split(escClose).join('}') .split(escComma).join(',') .split(escPeriod).join('.'); } // Basically just str.split(","), but handling cases // where we have nested braced sections, which should be // treated as individual members, like {a,{b,c},d} function parseCommaParts(str) { if (!str) return ['']; var parts = []; var m = balanced('{', '}', str); if (!m) return str.split(','); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(','); p[p.length-1] += '{' + body + '}'; var postParts = parseCommaParts(post); if (post.length) { p[p.length-1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } function expandTop(str) { if (!str) return []; // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, // but a{},b}c will be expanded to [a}c,abc]. // One could argue that this is a bug in Bash, but since the goal of // this module is to match Bash's rules, we escape a leading {} if (str.substr(0, 2) === '{}') { str = '\\{\\}' + str.substr(2); } return expand$4(escapeBraces(str), true).map(unescapeBraces); } function embrace(str) { return '{' + str + '}'; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand$4(str, isTop) { var expansions = []; var m = balanced('{', '}', str); if (!m) return [str]; // no need to expand pre, since it is guaranteed to be free of brace-sets var pre = m.pre; var post = m.post.length ? expand$4(m.post, false) : ['']; if (/\$$/.test(m.pre)) { for (var k = 0; k < post.length; k++) { var expansion = pre+ '{' + m.body + '}' + post[k]; expansions.push(expansion); } } else { var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} if (m.post.match(/,.*\}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand$4(str); } return [str]; } var n; if (isSequence) { n = m.body.split(/\.\./); } else { n = parseCommaParts(m.body); if (n.length === 1) { // x{{a,b}}y ==> x{a}y x{b}y n = expand$4(n[0], false).map(embrace); if (n.length === 1) { return post.map(function(p) { return m.pre + n[0] + p; }); } } } // at this point, n is the parts, and we know it's not a comma set // with a single entry. var N; if (isSequence) { var x = numeric(n[0]); var y = numeric(n[1]); var width = Math.max(n[0].length, n[1].length); var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === '\\') c = ''; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join('0'); if (i < 0) c = '-' + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = []; for (var j = 0; j < n.length; j++) { N.push.apply(N, expand$4(n[j], false)); } } for (var j = 0; j < N.length; j++) { for (var k = 0; k < post.length; k++) { var expansion = pre + N[j] + post[k]; if (!isTop || isSequence || expansion) expansions.push(expansion); } } } return expansions; } const minimatch$1 = minimatch_1 = (p, pattern, options = {}) => { assertValidPattern(pattern); // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { return false } return new Minimatch$1(pattern, options).match(p) }; var minimatch_1 = minimatch$1; const path$j = path$k; minimatch$1.sep = path$j.sep; const GLOBSTAR$2 = Symbol('globstar **'); minimatch$1.GLOBSTAR = GLOBSTAR$2; const expand$3 = braceExpansion; const plTypes = { '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, '?': { open: '(?:', close: ')?' }, '+': { open: '(?:', close: ')+' }, '*': { open: '(?:', close: ')*' }, '@': { open: '(?:', close: ')' } }; // any single thing other than / // don't need to escape / when using new RegExp() const qmark = '[^/]'; // * => any number of characters const star = qmark + '*?'; // ** when dots are allowed. Anything goes, except .. and . // not (^ or / followed by one or two dots followed by $ or /), // followed by anything, any number of times. const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; // not a ^ or / followed by a dot, // followed by anything, any number of times. const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; // "abc" -> { a:true, b:true, c:true } const charSet = s => s.split('').reduce((set, c) => { set[c] = true; return set }, {}); // characters that need to be escaped in RegExp. const reSpecials = charSet('().*{}+?[]^$\\!'); // characters that indicate we have to add the pattern start const addPatternStartSet = charSet('[.('); // normalizes slashes. const slashSplit = /\/+/; minimatch$1.filter = (pattern, options = {}) => (p, i, list) => minimatch$1(p, pattern, options); const ext = (a, b = {}) => { const t = {}; Object.keys(a).forEach(k => t[k] = a[k]); Object.keys(b).forEach(k => t[k] = b[k]); return t }; minimatch$1.defaults = def => { if (!def || typeof def !== 'object' || !Object.keys(def).length) { return minimatch$1 } const orig = minimatch$1; const m = (p, pattern, options) => orig(p, pattern, ext(def, options)); m.Minimatch = class Minimatch extends orig.Minimatch { constructor (pattern, options) { super(pattern, ext(def, options)); } }; m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch; m.filter = (pattern, options) => orig.filter(pattern, ext(def, options)); m.defaults = options => orig.defaults(ext(def, options)); m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options)); m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options)); m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options)); return m }; // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac // a{0..3}d -> a0d a1d a2d a3d // a{b,c{d,e}f}g -> abg acdfg acefg // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg // // Invalid sets are not expanded. // a{2..}b -> a{2..}b // a{b}c -> a{b}c minimatch$1.braceExpand = (pattern, options) => braceExpand(pattern, options); const braceExpand = (pattern, options = {}) => { assertValidPattern(pattern); // Thanks to Yeting Li for // improving this regexp to avoid a ReDOS vulnerability. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { // shortcut. no need to expand. return [pattern] } return expand$3(pattern) }; const MAX_PATTERN_LENGTH = 1024 * 64; const assertValidPattern = pattern => { if (typeof pattern !== 'string') { throw new TypeError('invalid pattern') } if (pattern.length > MAX_PATTERN_LENGTH) { throw new TypeError('pattern is too long') } }; // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full // pattern, split on '/', and then turned into a regular expression. // A regexp is made at the end which joins each array with an // escaped /, and another full one which joins each regexp with |. // // Following the lead of Bash 4.1, note that "**" only has special meaning // when it is the *only* thing in a path portion. Otherwise, any series // of * is equivalent to a single *. Globstar behavior is enabled by // default, and can be disabled by setting options.noglobstar. const SUBPARSE = Symbol('subparse'); minimatch$1.makeRe = (pattern, options) => new Minimatch$1(pattern, options || {}).makeRe(); minimatch$1.match = (list, pattern, options = {}) => { const mm = new Minimatch$1(pattern, options); list = list.filter(f => mm.match(f)); if (mm.options.nonull && !list.length) { list.push(pattern); } return list }; // replace stuff like \* with * const globUnescape = s => s.replace(/\\(.)/g, '$1'); const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); let Minimatch$1 = class Minimatch { constructor (pattern, options) { assertValidPattern(pattern); if (!options) options = {}; this.options = options; this.set = []; this.pattern = pattern; this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; if (this.windowsPathsNoEscape) { this.pattern = this.pattern.replace(/\\/g, '/'); } this.regexp = null; this.negate = false; this.comment = false; this.empty = false; this.partial = !!options.partial; // make the set of regexps etc. this.make(); } debug () {} make () { const pattern = this.pattern; const options = this.options; // empty patterns and comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { this.comment = true; return } if (!pattern) { this.empty = true; return } // step 1: figure out negation, etc. this.parseNegate(); // step 2: expand braces let set = this.globSet = this.braceExpand(); if (options.debug) this.debug = (...args) => console.error(...args); this.debug(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion // matching patterns. // These will be regexps, except in the case of "**", which is // set to the GLOBSTAR object for globstar behavior, // and will not contain any / characters set = this.globParts = set.map(s => s.split(slashSplit)); this.debug(this.pattern, set); // glob --> regexps set = set.map((s, si, set) => s.map(this.parse, this)); this.debug(this.pattern, set); // filter out everything that didn't compile properly. set = set.filter(s => s.indexOf(false) === -1); this.debug(this.pattern, set); this.set = set; } parseNegate () { if (this.options.nonegate) return const pattern = this.pattern; let negate = false; let negateOffset = 0; for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) { negate = !negate; negateOffset++; } if (negateOffset) this.pattern = pattern.substr(negateOffset); this.negate = negate; } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. matchOne (file, pattern, partial) { var options = this.options; this.debug('matchOne', { 'this': this, file: file, pattern: pattern }); this.debug('matchOne', file.length, pattern.length); for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length ; (fi < fl) && (pi < pl) ; fi++, pi++) { this.debug('matchOne loop'); var p = pattern[pi]; var f = file[fi]; this.debug(pattern, p, f); // should be impossible. // some invalid regexp stuff in the set. /* istanbul ignore if */ if (p === false) return false if (p === GLOBSTAR$2) { this.debug('GLOBSTAR', [pattern, p, f]); // "**" // a/**/b/**/c would match the following: // a/b/x/y/z/c // a/x/y/z/b/c // a/b/x/b/x/c // a/b/c // To do this, take the rest of the pattern after // the **, and see if it would match the file remainder. // If so, return success. // If not, the ** "swallows" a segment, and try again. // This is recursively awful. // // a/**/b/**/c matching a/b/x/y/z/c // - a matches a // - doublestar // - matchOne(b/x/y/z/c, b/**/c) // - b matches b // - doublestar // - matchOne(x/y/z/c, c) -> no // - matchOne(y/z/c, c) -> no // - matchOne(z/c, c) -> no // - matchOne(c, c) yes, hit var fr = fi; var pr = pi + 1; if (pr === pl) { this.debug('** at the end'); // a ** at the end will just swallow the rest. // We have found a match. // however, it will not swallow /.x, unless // options.dot is set. // . and .. are *never* matched by **, for explosively // exponential reasons. for (; fi < fl; fi++) { if (file[fi] === '.' || file[fi] === '..' || (!options.dot && file[fi].charAt(0) === '.')) return false } return true } // ok, let's see if we can swallow whatever we can. while (fr < fl) { var swallowee = file[fr]; this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); // XXX remove this slice. Just pass the start index. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { this.debug('globstar found match!', fr, fl, swallowee); // found a match. return true } else { // can't swallow "." or ".." ever. // can only swallow ".foo" when explicitly asked. if (swallowee === '.' || swallowee === '..' || (!options.dot && swallowee.charAt(0) === '.')) { this.debug('dot detected!', file, fr, pattern, pr); break } // ** swallows a segment, and continue. this.debug('globstar swallow a segment, and continue'); fr++; } } // no match was found. // However, in partial mode, we can't say this is necessarily over. // If there's more *pattern* left, then /* istanbul ignore if */ if (partial) { // ran out of file this.debug('\n>>> no match, partial?', file, fr, pattern, pr); if (fr === fl) return true } return false } // something other than ** // non-magic patterns just have to match exactly // patterns with magic have been turned into regexps. var hit; if (typeof p === 'string') { hit = f === p; this.debug('string match', p, f, hit); } else { hit = f.match(p); this.debug('pattern match', p, f, hit); } if (!hit) return false } // Note: ending in / means that we'll get a final "" // at the end of the pattern. This can only match a // corresponding "" at the end of the file. // If the file ends in /, then it can only match a // a pattern that ends in /, unless the pattern just // doesn't have any more for it. But, a/b/ should *not* // match "a/b/*", even though "" matches against the // [^/]*? pattern, except in partial mode, where it might // simply not be reached yet. // However, a/b/ should still satisfy a/* // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. // an exact hit! return true } else if (fi === fl) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial } else /* istanbul ignore else */ if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ return (fi === fl - 1) && (file[fi] === '') } // should be unreachable. /* istanbul ignore next */ throw new Error('wtf?') } braceExpand () { return braceExpand(this.pattern, this.options) } parse (pattern, isSub) { assertValidPattern(pattern); const options = this.options; // shortcuts if (pattern === '**') { if (!options.noglobstar) return GLOBSTAR$2 else pattern = '*'; } if (pattern === '') return '' let re = ''; let hasMagic = !!options.nocase; let escaping = false; // ? => one single character const patternListStack = []; const negativeLists = []; let stateChar; let inClass = false; let reClassStart = -1; let classStart = -1; let cs; let pl; let sp; // . and .. never match anything that doesn't start with ., // even when options.dot is set. const patternStart = pattern.charAt(0) === '.' ? '' // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)'; const clearStateChar = () => { if (stateChar) { // we had some state-tracking character // that wasn't consumed by this pass. switch (stateChar) { case '*': re += star; hasMagic = true; break case '?': re += qmark; hasMagic = true; break default: re += '\\' + stateChar; break } this.debug('clearStateChar %j %j', stateChar, re); stateChar = false; } }; for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) { this.debug('%s\t%s %s %j', pattern, i, re, c); // skip over any that are escaped. if (escaping) { /* istanbul ignore next - completely not allowed, even escaped. */ if (c === '/') { return false } if (reSpecials[c]) { re += '\\'; } re += c; escaping = false; continue } switch (c) { /* istanbul ignore next */ case '/': { // Should already be path-split by now. return false } case '\\': clearStateChar(); escaping = true; continue // the various stateChar values // for the "extglob" stuff. case '?': case '*': case '+': case '@': case '!': this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); // all of those are literals inside a class, except that // the glob [!a] means [^a] in regexp if (inClass) { this.debug(' in class'); if (c === '!' && i === classStart + 1) c = '^'; re += c; continue } // if we already have a stateChar, then it means // that there was something like ** or +? in there. // Handle the stateChar, then proceed with this one. this.debug('call clearStateChar %j', stateChar); clearStateChar(); stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing. // just clear the statechar *now*, rather than even diving into // the patternList stuff. if (options.noext) clearStateChar(); continue case '(': if (inClass) { re += '('; continue } if (!stateChar) { re += '\\('; continue } patternListStack.push({ type: stateChar, start: i - 1, reStart: re.length, open: plTypes[stateChar].open, close: plTypes[stateChar].close }); // negation is (?:(?!js)[^/]*) re += stateChar === '!' ? '(?:(?!(?:' : '(?:'; this.debug('plType %j %j', stateChar, re); stateChar = false; continue case ')': if (inClass || !patternListStack.length) { re += '\\)'; continue } clearStateChar(); hasMagic = true; pl = patternListStack.pop(); // negation is (?:(?!js)[^/]*) // The others are (?:) re += pl.close; if (pl.type === '!') { negativeLists.push(pl); } pl.reEnd = re.length; continue case '|': if (inClass || !patternListStack.length) { re += '\\|'; continue } clearStateChar(); re += '|'; continue // these are mostly the same in regexp and glob case '[': // swallow any state-tracking char before the [ clearStateChar(); if (inClass) { re += '\\' + c; continue } inClass = true; classStart = i; reClassStart = re.length; re += c; continue case ']': // a right bracket shall lose its special // meaning and represent itself in // a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 if (i === classStart + 1 || !inClass) { re += '\\' + c; continue } // handle the case where we left a class open. // "[z-a]" is valid, equivalent to "\[z-a\]" // split where the last [ was, make sure we don't have // an invalid re. if so, re-walk the contents of the // would-be class to re-translate any characters that // were passed through as-is // TODO: It would probably be faster to determine this // without a try/catch and a new RegExp, but it's tricky // to do safely. For now, this is safe and works. cs = pattern.substring(classStart + 1, i); // finish up the class. hasMagic = true; inClass = false; re += c; continue default: // swallow any state char that wasn't consumed clearStateChar(); if (reSpecials[c] && !(c === '^' && inClass)) { re += '\\'; } re += c; break } // switch } // for // handle the case where we left a class open. // "[abc" is valid, equivalent to "\[abc" if (inClass) { // split where the last [ was, and escape it // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is cs = pattern.substr(classStart + 1); sp = this.parse(cs, SUBPARSE); re = re.substr(0, reClassStart) + '\\[' + sp[0]; hasMagic = hasMagic || sp[1]; } // handle the case where we had a +( thing at the *end* // of the pattern. // each pattern list stack adds 3 chars, and we need to go through // and escape any | chars that were passed through as-is for the regexp. // Go through and escape them, taking care not to double-escape any // | chars that were already escaped. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { let tail; tail = re.slice(pl.reStart + pl.open.length); this.debug('setting tail', re, pl); // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => { /* istanbul ignore else - should already be done */ if (!$2) { // the | isn't already escaped, so escape it. $2 = '\\'; } // need to escape all those slashes *again*, without escaping the // one that we need for escaping the | character. As it works out, // escaping an even number of slashes can be done by simply repeating // it exactly after itself. That's why this trick works. // // I am sorry that you have to see this. return $1 + $1 + $2 + '|' }); this.debug('tail=%j\n %s', tail, tail, pl, re); const t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type; hasMagic = true; re = re.slice(0, pl.reStart) + t + '\\(' + tail; } // handle trailing things that only matter at the very end. clearStateChar(); if (escaping) { // trailing \\ re += '\\\\'; } // only need to apply the nodot start if the re starts with // something that could conceivably capture a dot const addPatternStart = addPatternStartSet[re.charAt(0)]; // Hack to work around lack of negative lookbehind in JS // A pattern like: *.!(x).!(y|z) needs to ensure that a name // like 'a.xyz.yz' doesn't match. So, the first negative // lookahead, has to look ALL the way ahead, to the end of // the pattern. for (let n = negativeLists.length - 1; n > -1; n--) { const nl = negativeLists[n]; const nlBefore = re.slice(0, nl.reStart); const nlFirst = re.slice(nl.reStart, nl.reEnd - 8); let nlAfter = re.slice(nl.reEnd); const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter; // Handle nested stuff like *(*.js|!(*.json)), where open parens // mean that we should *not* include the ) in the bit that is considered // "after" the negated section. const openParensBefore = nlBefore.split('(').length - 1; let cleanAfter = nlAfter; for (let i = 0; i < openParensBefore; i++) { cleanAfter = cleanAfter.replace(/\)[+*?]?/, ''); } nlAfter = cleanAfter; const dollar = nlAfter === '' && isSub !== SUBPARSE ? '$' : ''; re = nlBefore + nlFirst + nlAfter + dollar + nlLast; } // if the re is not "" at this point, then we need to make sure // it doesn't match against an empty path part. // Otherwise a/* will match a/, which it should not. if (re !== '' && hasMagic) { re = '(?=.)' + re; } if (addPatternStart) { re = patternStart + re; } // parsing just a piece of a larger pattern. if (isSub === SUBPARSE) { return [re, hasMagic] } // skip the regexp for non-magical patterns // unescape anything in it, though, so that it'll be // an exact match against a file etc. if (!hasMagic) { return globUnescape(pattern) } const flags = options.nocase ? 'i' : ''; try { return Object.assign(new RegExp('^' + re + '$', flags), { _glob: pattern, _src: re, }) } catch (er) /* istanbul ignore next - should be impossible */ { // If it was an invalid regular expression, then it can't match // anything. This trick looks for a character after the end of // the string, which is of course impossible, except in multi-line // mode, but it's not a /m regex. return new RegExp('$.') } } makeRe () { if (this.regexp || this.regexp === false) return this.regexp // at this point, this.set is a 2d array of partial // pattern strings, or "**". // // It's better to use .match(). This function shouldn't // be used, really, but it's pretty convenient sometimes, // when you just want to work with a regex. const set = this.set; if (!set.length) { this.regexp = false; return this.regexp } const options = this.options; const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot; const flags = options.nocase ? 'i' : ''; // coalesce globstars and regexpify non-globstar patterns // if it's the only item, then we just do one twoStar // if it's the first, and there are more, prepend (\/|twoStar\/)? to next // if it's the last, append (\/twoStar|) to previous // if it's in the middle, append (\/|\/twoStar\/) to previous // then filter out GLOBSTAR symbols let re = set.map(pattern => { pattern = pattern.map(p => typeof p === 'string' ? regExpEscape(p) : p === GLOBSTAR$2 ? GLOBSTAR$2 : p._src ).reduce((set, p) => { if (!(set[set.length - 1] === GLOBSTAR$2 && p === GLOBSTAR$2)) { set.push(p); } return set }, []); pattern.forEach((p, i) => { if (p !== GLOBSTAR$2 || pattern[i-1] === GLOBSTAR$2) { return } if (i === 0) { if (pattern.length > 1) { pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1]; } else { pattern[i] = twoStar; } } else if (i === pattern.length - 1) { pattern[i-1] += '(?:\\\/|' + twoStar + ')?'; } else { pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1]; pattern[i+1] = GLOBSTAR$2; } }); return pattern.filter(p => p !== GLOBSTAR$2).join('/') }).join('|'); // must match entire pattern // ending in a * or ** will make it less strict. re = '^(?:' + re + ')$'; // can match anything, as long as it's not this. if (this.negate) re = '^(?!' + re + ').*$'; try { this.regexp = new RegExp(re, flags); } catch (ex) /* istanbul ignore next - should be impossible */ { this.regexp = false; } return this.regexp } match (f, partial = this.partial) { this.debug('match', f, this.pattern); // short-circuit in the case of busted things. // comments, etc. if (this.comment) return false if (this.empty) return f === '' if (f === '/' && partial) return true const options = this.options; // windows: need to use /, not \ if (path$j.sep !== '/') { f = f.split(path$j.sep).join('/'); } // treat the test path as a set of pathparts. f = f.split(slashSplit); this.debug(this.pattern, 'split', f); // just ONE of the pattern sets in this.set needs to match // in order for it to be valid. If negating, then just one // match means that we have failed. // Either way, return on the first hit. const set = this.set; this.debug(this.pattern, 'set', set); // Find the basename of the path by looking for the last non-empty segment let filename; for (let i = f.length - 1; i >= 0; i--) { filename = f[i]; if (filename) break } for (let i = 0; i < set.length; i++) { const pattern = set[i]; let file = f; if (options.matchBase && pattern.length === 1) { file = [filename]; } const hit = this.matchOne(file, pattern, partial); if (hit) { if (options.flipNegate) return true return !this.negate } } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.flipNegate) return false return this.negate } static defaults (def) { return minimatch$1.defaults(def).Minimatch } }; minimatch$1.Minimatch = Minimatch$1; var inherits = {exports: {}}; var inherits_browser = {exports: {}}; var hasRequiredInherits_browser; function requireInherits_browser () { if (hasRequiredInherits_browser) return inherits_browser.exports; hasRequiredInherits_browser = 1; if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module inherits_browser.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); } }; } else { // old school shim for old browsers inherits_browser.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } }; } return inherits_browser.exports; } try { var util$2 = require$1('util'); /* istanbul ignore next */ if (typeof util$2.inherits !== 'function') throw ''; inherits.exports = util$2.inherits; } catch (e) { /* istanbul ignore next */ inherits.exports = requireInherits_browser(); } var inheritsExports = inherits.exports; var common$c = {}; common$c.setopts = setopts; common$c.ownProp = ownProp; common$c.makeAbs = makeAbs; common$c.finish = finish; common$c.mark = mark; common$c.isIgnored = isIgnored; common$c.childrenIgnored = childrenIgnored; function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } var fs$i = require$$0__default__default; var path$i = require$$0$4; var minimatch = minimatch_1; var isAbsolute = require$$0$4.isAbsolute; var Minimatch = minimatch.Minimatch; function alphasort (a, b) { return a.localeCompare(b, 'en') } function setupIgnores (self, options) { self.ignore = options.ignore || []; if (!Array.isArray(self.ignore)) self.ignore = [self.ignore]; if (self.ignore.length) { self.ignore = self.ignore.map(ignoreMap); } } // ignore patterns are always in dot:true mode. function ignoreMap (pattern) { var gmatcher = null; if (pattern.slice(-3) === '/**') { var gpattern = pattern.replace(/(\/\*\*)+$/, ''); gmatcher = new Minimatch(gpattern, { dot: true }); } return { matcher: new Minimatch(pattern, { dot: true }), gmatcher: gmatcher } } function setopts (self, pattern, options) { if (!options) options = {}; // base-matching: just use globstar for that. if (options.matchBase && -1 === pattern.indexOf("/")) { if (options.noglobstar) { throw new Error("base matching requires globstar") } pattern = "**/" + pattern; } self.silent = !!options.silent; self.pattern = pattern; self.strict = options.strict !== false; self.realpath = !!options.realpath; self.realpathCache = options.realpathCache || Object.create(null); self.follow = !!options.follow; self.dot = !!options.dot; self.mark = !!options.mark; self.nodir = !!options.nodir; if (self.nodir) self.mark = true; self.sync = !!options.sync; self.nounique = !!options.nounique; self.nonull = !!options.nonull; self.nosort = !!options.nosort; self.nocase = !!options.nocase; self.stat = !!options.stat; self.noprocess = !!options.noprocess; self.absolute = !!options.absolute; self.fs = options.fs || fs$i; self.maxLength = options.maxLength || Infinity; self.cache = options.cache || Object.create(null); self.statCache = options.statCache || Object.create(null); self.symlinks = options.symlinks || Object.create(null); setupIgnores(self, options); self.changedCwd = false; var cwd = process.cwd(); if (!ownProp(options, "cwd")) self.cwd = path$i.resolve(cwd); else { self.cwd = path$i.resolve(options.cwd); self.changedCwd = self.cwd !== cwd; } self.root = options.root || path$i.resolve(self.cwd, "/"); self.root = path$i.resolve(self.root); // TODO: is an absolute `cwd` supposed to be resolved against `root`? // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd); self.nomount = !!options.nomount; if (process.platform === "win32") { self.root = self.root.replace(/\\/g, "/"); self.cwd = self.cwd.replace(/\\/g, "/"); self.cwdAbs = self.cwdAbs.replace(/\\/g, "/"); } // disable comments and negation in Minimatch. // Note that they are not supported in Glob itself anyway. options.nonegate = true; options.nocomment = true; // always treat \ in patterns as escapes, not path separators options.allowWindowsEscape = true; self.minimatch = new Minimatch(pattern, options); self.options = self.minimatch.options; } function finish (self) { var nou = self.nounique; var all = nou ? [] : Object.create(null); for (var i = 0, l = self.matches.length; i < l; i ++) { var matches = self.matches[i]; if (!matches || Object.keys(matches).length === 0) { if (self.nonull) { // do like the shell, and spit out the literal glob var literal = self.minimatch.globSet[i]; if (nou) all.push(literal); else all[literal] = true; } } else { // had matches var m = Object.keys(matches); if (nou) all.push.apply(all, m); else m.forEach(function (m) { all[m] = true; }); } } if (!nou) all = Object.keys(all); if (!self.nosort) all = all.sort(alphasort); // at *some* point we statted all of these if (self.mark) { for (var i = 0; i < all.length; i++) { all[i] = self._mark(all[i]); } if (self.nodir) { all = all.filter(function (e) { var notDir = !(/\/$/.test(e)); var c = self.cache[e] || self.cache[makeAbs(self, e)]; if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c); return notDir }); } } if (self.ignore.length) all = all.filter(function(m) { return !isIgnored(self, m) }); self.found = all; } function mark (self, p) { var abs = makeAbs(self, p); var c = self.cache[abs]; var m = p; if (c) { var isDir = c === 'DIR' || Array.isArray(c); var slash = p.slice(-1) === '/'; if (isDir && !slash) m += '/'; else if (!isDir && slash) m = m.slice(0, -1); if (m !== p) { var mabs = makeAbs(self, m); self.statCache[mabs] = self.statCache[abs]; self.cache[mabs] = self.cache[abs]; } } return m } // lotta situps... function makeAbs (self, f) { var abs = f; if (f.charAt(0) === '/') { abs = path$i.join(self.root, f); } else if (isAbsolute(f) || f === '') { abs = f; } else if (self.changedCwd) { abs = path$i.resolve(self.cwd, f); } else { abs = path$i.resolve(f); } if (process.platform === 'win32') abs = abs.replace(/\\/g, '/'); return abs } // Return true, if pattern ends with globstar '**', for the accompanying parent directory. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents function isIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) }) } function childrenIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return !!(item.gmatcher && item.gmatcher.match(path)) }) } var sync$9; var hasRequiredSync; function requireSync () { if (hasRequiredSync) return sync$9; hasRequiredSync = 1; sync$9 = globSync; globSync.GlobSync = GlobSync; var rp = fs_realpath; var minimatch = minimatch_1; requireGlob().Glob; var path = require$$0$4; var assert = require$$5; var isAbsolute = require$$0$4.isAbsolute; var common = common$c; var setopts = common.setopts; var ownProp = common.ownProp; var childrenIgnored = common.childrenIgnored; var isIgnored = common.isIgnored; function globSync (pattern, options) { if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') return new GlobSync(pattern, options).found } function GlobSync (pattern, options) { if (!pattern) throw new Error('must provide pattern') if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') if (!(this instanceof GlobSync)) return new GlobSync(pattern, options) setopts(this, pattern, options); if (this.noprocess) return this var n = this.minimatch.set.length; this.matches = new Array(n); for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false); } this._finish(); } GlobSync.prototype._finish = function () { assert.ok(this instanceof GlobSync); if (this.realpath) { var self = this; this.matches.forEach(function (matchset, index) { var set = self.matches[index] = Object.create(null); for (var p in matchset) { try { p = self._makeAbs(p); var real = rp.realpathSync(p, self.realpathCache); set[real] = true; } catch (er) { if (er.syscall === 'stat') set[self._makeAbs(p)] = true; else throw er } } }); } common.finish(this); }; GlobSync.prototype._process = function (pattern, index, inGlobStar) { assert.ok(this instanceof GlobSync); // Get the first [n] parts of pattern that are all strings. var n = 0; while (typeof pattern[n] === 'string') { n ++; } // now n is the index of the first one that is *not* a string. // See if there's anything else var prefix; switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index); return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null; break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/'); break } var remain = pattern.slice(n); // get the list of entries. var read; if (prefix === null) read = '.'; else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) { return typeof p === 'string' ? p : '[*]' }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix; read = prefix; } else read = prefix; var abs = this._makeAbs(read); //if ignored, skip processing if (childrenIgnored(this, read)) return var isGlobStar = remain[0] === minimatch.GLOBSTAR; if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar); else this._processReaddir(prefix, read, abs, remain, index, inGlobStar); }; GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar); // if the abs isn't a dir, then nothing can match! if (!entries) return // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0]; var negate = !!this.minimatch.negate; var rawGlob = pn._glob; var dotOk = this.dot || rawGlob.charAt(0) === '.'; var matchedEntries = []; for (var i = 0; i < entries.length; i++) { var e = entries[i]; if (e.charAt(0) !== '.' || dotOk) { var m; if (negate && !prefix) { m = !e.match(pn); } else { m = e.match(pn); } if (m) matchedEntries.push(e); } } var len = matchedEntries.length; // If there are no matched entries, then nothing matches. if (len === 0) return // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; if (prefix) { if (prefix.slice(-1) !== '/') e = prefix + '/' + e; else e = prefix + e; } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e); } this._emitMatch(index, e); } // This was the last one, and no stats were needed return } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift(); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; var newPattern; if (prefix) newPattern = [prefix, e]; else newPattern = [e]; this._process(newPattern.concat(remain), index, inGlobStar); } }; GlobSync.prototype._emitMatch = function (index, e) { if (isIgnored(this, e)) return var abs = this._makeAbs(e); if (this.mark) e = this._mark(e); if (this.absolute) { e = abs; } if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs]; if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true; if (this.stat) this._stat(e); }; GlobSync.prototype._readdirInGlobStar = function (abs) { // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false) var entries; var lstat; try { lstat = this.fs.lstatSync(abs); } catch (er) { if (er.code === 'ENOENT') { // lstat failed, doesn't exist return null } } var isSym = lstat && lstat.isSymbolicLink(); this.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE'; else entries = this._readdir(abs, false); return entries }; GlobSync.prototype._readdir = function (abs, inGlobStar) { if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs) if (ownProp(this.cache, abs)) { var c = this.cache[abs]; if (!c || c === 'FILE') return null if (Array.isArray(c)) return c } try { return this._readdirEntries(abs, this.fs.readdirSync(abs)) } catch (er) { this._readdirError(abs, er); return null } }; GlobSync.prototype._readdirEntries = function (abs, entries) { // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i]; if (abs === '/') e = abs + e; else e = abs + '/' + e; this.cache[e] = true; } } this.cache[abs] = entries; // mark and cache dir-ness return entries }; GlobSync.prototype._readdirError = function (f, er) { // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f); this.cache[abs] = 'FILE'; if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd); error.path = this.cwd; error.code = er.code; throw error } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false; break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false; if (this.strict) throw er if (!this.silent) console.error('glob error', er); break } }; GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar); // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1); var gspref = prefix ? [ prefix ] : []; var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false); var len = entries.length; var isSym = this.symlinks[abs]; // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return for (var i = 0; i < len; i++) { var e = entries[i]; if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar); this._process(instead, index, true); var below = gspref.concat(entries[i], remain); this._process(below, index, true); } }; GlobSync.prototype._processSimple = function (prefix, index) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var exists = this._stat(prefix); if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results if (!exists) return if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix); if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix); } else { prefix = path.resolve(this.root, prefix); if (trail) prefix += '/'; } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match this._emitMatch(index, prefix); }; // Returns either 'DIR', 'FILE', or false GlobSync.prototype._stat = function (f) { var abs = this._makeAbs(f); var needDir = f.slice(-1) === '/'; if (f.length > this.maxLength) return false if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs]; if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return c if (needDir && c === 'FILE') return false // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var stat = this.statCache[abs]; if (!stat) { var lstat; try { lstat = this.fs.lstatSync(abs); } catch (er) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false; return false } } if (lstat && lstat.isSymbolicLink()) { try { stat = this.fs.statSync(abs); } catch (er) { stat = lstat; } } else { stat = lstat; } } this.statCache[abs] = stat; var c = true; if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE'; this.cache[abs] = this.cache[abs] || c; if (needDir && c === 'FILE') return false return c }; GlobSync.prototype._mark = function (p) { return common.mark(this, p) }; GlobSync.prototype._makeAbs = function (f) { return common.makeAbs(this, f) }; return sync$9; } // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. // This makes sure that own properties are retained, so that // decorations and such are not lost along the way. var wrappy_1 = wrappy$2; function wrappy$2 (fn, cb) { if (fn && cb) return wrappy$2(fn)(cb) if (typeof fn !== 'function') throw new TypeError('need wrapper function') Object.keys(fn).forEach(function (k) { wrapper[k] = fn[k]; }); return wrapper function wrapper() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } var ret = fn.apply(this, args); var cb = args[args.length-1]; if (typeof ret === 'function' && ret !== cb) { Object.keys(cb).forEach(function (k) { ret[k] = cb[k]; }); } return ret } } var once$2 = {exports: {}}; var wrappy$1 = wrappy_1; once$2.exports = wrappy$1(once$1); once$2.exports.strict = wrappy$1(onceStrict); once$1.proto = once$1(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once$1(this) }, configurable: true }); Object.defineProperty(Function.prototype, 'onceStrict', { value: function () { return onceStrict(this) }, configurable: true }); }); function once$1 (fn) { var f = function () { if (f.called) return f.value f.called = true; return f.value = fn.apply(this, arguments) }; f.called = false; return f } function onceStrict (fn) { var f = function () { if (f.called) throw new Error(f.onceError) f.called = true; return f.value = fn.apply(this, arguments) }; var name = fn.name || 'Function wrapped with `once`'; f.onceError = name + " shouldn't be called more than once"; f.called = false; return f } var onceExports = once$2.exports; var wrappy = wrappy_1; var reqs = Object.create(null); var once = onceExports; var inflight_1 = wrappy(inflight); function inflight (key, cb) { if (reqs[key]) { reqs[key].push(cb); return null } else { reqs[key] = [cb]; return makeres(key) } } function makeres (key) { return once(function RES () { var cbs = reqs[key]; var len = cbs.length; var args = slice$1(arguments); // XXX It's somewhat ambiguous whether a new callback added in this // pass should be queued for later execution if something in the // list of callbacks throws, or if it should just be discarded. // However, it's such an edge case that it hardly matters, and either // choice is likely as surprising as the other. // As it happens, we do go ahead and schedule it for later execution. try { for (var i = 0; i < len; i++) { cbs[i].apply(null, args); } } finally { if (cbs.length > len) { // added more in the interim. // de-zalgo, just in case, but don't call again. cbs.splice(0, len); process.nextTick(function () { RES.apply(null, args); }); } else { delete reqs[key]; } } }) } function slice$1 (args) { var length = args.length; var array = []; for (var i = 0; i < length; i++) array[i] = args[i]; return array } var glob_1; var hasRequiredGlob; function requireGlob () { if (hasRequiredGlob) return glob_1; hasRequiredGlob = 1; // Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. glob_1 = glob; var rp = fs_realpath; var minimatch = minimatch_1; var inherits = inheritsExports; var EE = require$$0$5.EventEmitter; var path = require$$0$4; var assert = require$$5; var isAbsolute = require$$0$4.isAbsolute; var globSync = requireSync(); var common = common$c; var setopts = common.setopts; var ownProp = common.ownProp; var inflight = inflight_1; var childrenIgnored = common.childrenIgnored; var isIgnored = common.isIgnored; var once = onceExports; function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {}; if (!options) options = {}; if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return globSync(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = globSync; var GlobSync = glob.GlobSync = globSync.GlobSync; // old api surface glob.glob = glob; function extend (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin } glob.hasMagic = function (pattern, options_) { var options = extend({}, options_); options.noprocess = true; var g = new Glob(pattern, options); var set = g.minimatch.set; if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false }; glob.Glob = Glob; inherits(Glob, EE); function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options; options = null; } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options); this._didRealPath = false; // process each pattern in the minimatch set var n = this.minimatch.set.length; // The matches are stored as {: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n); if (typeof cb === 'function') { cb = once(cb); this.on('error', cb); this.on('end', function (matches) { cb(null, matches); }); } var self = this; this._processing = 0; this._emitQueue = []; this._processQueue = []; this.paused = false; if (this.noprocess) return this if (n === 0) return done() var sync = true; for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done); } sync = false; function done () { --self._processing; if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish(); }); } else { self._finish(); } } } } Glob.prototype._finish = function () { assert(this instanceof Glob); if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.finish(this); this.emit('end', this.found); }; Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true; var n = this.matches.length; if (n === 0) return this._finish() var self = this; for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next); function next () { if (--n === 0) self._finish(); } }; Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index]; if (!matchset) return cb() var found = Object.keys(matchset); var self = this; var n = found.length; if (n === 0) return cb() var set = this.matches[index] = Object.create(null); found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p); rp.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true; else if (er.syscall === 'stat') set[p] = true; else self.emit('error', er); // srsly wtf right here if (--n === 0) { self.matches[index] = set; cb(); } }); }); }; Glob.prototype._mark = function (p) { return common.mark(this, p) }; Glob.prototype._makeAbs = function (f) { return common.makeAbs(this, f) }; Glob.prototype.abort = function () { this.aborted = true; this.emit('abort'); }; Glob.prototype.pause = function () { if (!this.paused) { this.paused = true; this.emit('pause'); } }; Glob.prototype.resume = function () { if (this.paused) { this.emit('resume'); this.paused = false; if (this._emitQueue.length) { var eq = this._emitQueue.slice(0); this._emitQueue.length = 0; for (var i = 0; i < eq.length; i ++) { var e = eq[i]; this._emitMatch(e[0], e[1]); } } if (this._processQueue.length) { var pq = this._processQueue.slice(0); this._processQueue.length = 0; for (var i = 0; i < pq.length; i ++) { var p = pq[i]; this._processing--; this._process(p[0], p[1], p[2], p[3]); } } } }; Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert(this instanceof Glob); assert(typeof cb === 'function'); if (this.aborted) return this._processing++; if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]); return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0; while (typeof pattern[n] === 'string') { n ++; } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix; switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb); return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null; break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/'); break } var remain = pattern.slice(n); // get the list of entries. var read; if (prefix === null) read = '.'; else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) { return typeof p === 'string' ? p : '[*]' }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix; read = prefix; } else read = prefix; var abs = this._makeAbs(read); //if ignored, skip _processing if (childrenIgnored(this, read)) return cb() var isGlobStar = remain[0] === minimatch.GLOBSTAR; if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb); else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb); }; Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this; this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }); }; Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0]; var negate = !!this.minimatch.negate; var rawGlob = pn._glob; var dotOk = this.dot || rawGlob.charAt(0) === '.'; var matchedEntries = []; for (var i = 0; i < entries.length; i++) { var e = entries[i]; if (e.charAt(0) !== '.' || dotOk) { var m; if (negate && !prefix) { m = !e.match(pn); } else { m = e.match(pn); } if (m) matchedEntries.push(e); } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length; // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; if (prefix) { if (prefix !== '/') e = prefix + '/' + e; else e = prefix + e; } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e); } this._emitMatch(index, e); } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift(); for (var i = 0; i < len; i ++) { var e = matchedEntries[i]; if (prefix) { if (prefix !== '/') e = prefix + '/' + e; else e = prefix + e; } this._process([e].concat(remain), index, inGlobStar, cb); } cb(); }; Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored(this, e)) return if (this.paused) { this._emitQueue.push([index, e]); return } var abs = isAbsolute(e) ? e : this._makeAbs(e); if (this.mark) e = this._mark(e); if (this.absolute) e = abs; if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs]; if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true; var st = this.statCache[abs]; if (st) this.emit('stat', e, st); this.emit('match', e); }; Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs; var self = this; var lstatcb = inflight(lstatkey, lstatcb_); if (lstatcb) self.fs.lstat(abs, lstatcb); function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink(); self.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE'; cb(); } else self._readdir(abs, false, cb); } }; Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb); if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs]; if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this; self.fs.readdir(abs, readdirCb(this, abs, cb)); }; function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb); else self._readdirEntries(abs, entries, cb); } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i]; if (abs === '/') e = abs + e; else e = abs + '/' + e; this.cache[e] = true; } } this.cache[abs] = entries; return cb(null, entries) }; Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f); this.cache[abs] = 'FILE'; if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd); error.path = this.cwd; error.code = er.code; this.emit('error', error); this.abort(); } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false; break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false; if (this.strict) { this.emit('error', er); // If the error is handled, then we abort // if not, we threw out of here this.abort(); } if (!this.silent) console.error('glob error', er); break } return cb() }; Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this; this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb); }); }; Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1); var gspref = prefix ? [ prefix ] : []; var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb); var isSym = this.symlinks[abs]; var len = entries.length; // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i]; if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar); this._process(instead, index, true, cb); var below = gspref.concat(entries[i], remain); this._process(below, index, true, cb); } cb(); }; Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this; this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb); }); }; Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix); if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix); } else { prefix = path.resolve(this.root, prefix); if (trail) prefix += '/'; } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match this._emitMatch(index, prefix); cb(); }; // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f); var needDir = f.slice(-1) === '/'; if (f.length > this.maxLength) return cb() if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs]; if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var stat = this.statCache[abs]; if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE'; if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this; var statcb = inflight('stat\0' + abs, lstatcb_); if (statcb) self.fs.lstat(abs, statcb); function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return self.fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb); else self._stat2(f, abs, er, stat, cb); }) } else { self._stat2(f, abs, er, lstat, cb); } } }; Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false; return cb() } var needDir = f.slice(-1) === '/'; this.statCache[abs] = stat; if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true; if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE'; this.cache[abs] = this.cache[abs] || c; if (needDir && c === 'FILE') return cb() return cb(null, c, stat) }; return glob_1; } requireGlob(); const chars$2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; const intToChar$1 = new Uint8Array(64); // 64 possible chars. const charToInt$1 = new Uint8Array(128); // z is 122 in ASCII for (let i = 0; i < chars$2.length; i++) { const c = chars$2.charCodeAt(i); intToChar$1[i] = c; charToInt$1[c] = i; } const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; const intToChar$2 = new Uint8Array(64); // 64 possible chars. const charToInt$2 = new Uint8Array(128); // z is 122 in ASCII for (let i = 0; i < chars$1.length; i++) { const c = chars$1.charCodeAt(i); intToChar$2[i] = c; charToInt$2[c] = i; } var UrlType$1; (function (UrlType) { UrlType[UrlType["Empty"] = 1] = "Empty"; UrlType[UrlType["Hash"] = 2] = "Hash"; UrlType[UrlType["Query"] = 3] = "Query"; UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; UrlType[UrlType["Absolute"] = 7] = "Absolute"; })(UrlType$1 || (UrlType$1 = {})); var src$2 = {exports: {}}; var browser$3 = {exports: {}}; /** * Helpers. */ var ms$1; var hasRequiredMs$1; function requireMs$1 () { if (hasRequiredMs$1) return ms$1; hasRequiredMs$1 = 1; var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ ms$1 = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + 'd'; } if (msAbs >= h) { return Math.round(ms / h) + 'h'; } if (msAbs >= m) { return Math.round(ms / m) + 'm'; } if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, 'day'); } if (msAbs >= h) { return plural(ms, msAbs, h, 'hour'); } if (msAbs >= m) { return plural(ms, msAbs, m, 'minute'); } if (msAbs >= s) { return plural(ms, msAbs, s, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } return ms$1; } var common$b; var hasRequiredCommon$1; function requireCommon$1 () { if (hasRequiredCommon$1) return common$b; hasRequiredCommon$1 = 1; /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = requireMs$1(); createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; let i; const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); const len = split.length; for (i = 0; i < len; i++) { if (!split[i]) { // ignore empty strings continue; } namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } let i; let len; for (i = 0, len = createDebug.skips.length; i < len; i++) { if (createDebug.skips[i].test(name)) { return false; } } for (i = 0, len = createDebug.names.length; i < len; i++) { if (createDebug.names[i].test(name)) { return true; } } return false; } /** * Convert regexp to namespace * * @param {RegExp} regxep * @return {String} namespace * @api private */ function toNamespace(regexp) { return regexp.toString() .substring(2, regexp.toString().length - 2) .replace(/\.\*\?$/, '*'); } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } common$b = setup; return common$b; } /* eslint-env browser */ var hasRequiredBrowser$1; function requireBrowser$1 () { if (hasRequiredBrowser$1) return browser$3.exports; hasRequiredBrowser$1 = 1; (function (module, exports) { /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = requireCommon$1()(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; } (browser$3, browser$3.exports)); return browser$3.exports; } var node$1 = {exports: {}}; /** * Module dependencies. */ var hasRequiredNode$1; function requireNode$1 () { if (hasRequiredNode$1) return node$1.exports; hasRequiredNode$1 = 1; (function (module, exports) { const tty = require$$0$3__default; const util = require$$0$6; /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.destroy = util.deprecate( () => {}, 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' ); /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = require$1('supports-color'); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.format()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util.format(...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = requireCommon$1()(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; } (node$1, node$1.exports)); return node$1.exports; } /** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { src$2.exports = requireBrowser$1(); } else { src$2.exports = requireNode$1(); } var srcExports$1 = src$2.exports; var debug$g = /*@__PURE__*/getDefaultExportFromCjs$1(srcExports$1); let pnp$1; if (process.versions.pnp) { try { pnp$1 = createRequire$1(import.meta.url)('pnpapi'); } catch { } } const createFilter$2 = createFilter$1; const windowsSlashRE = /\\/g; function slash$1(p) { return p.replace(windowsSlashRE, '/'); } //TODO: revisit later to see if the edge case that "compiling using node v12 code to be run in node v16 in the server" is what we intend to support. const builtins$2 = new Set([ ...builtinModules$1, 'assert/strict', 'diagnostics_channel', 'dns/promises', 'fs/promises', 'path/posix', 'path/win32', 'readline/promises', 'stream/consumers', 'stream/promises', 'stream/web', 'timers/promises', 'util/types', 'wasi', ]); // Some runtimes like Bun injects namespaced modules here, which is not a node builtin [...builtins$2].filter((id) => !id.includes(':')); // TODO: use import() const _require$3 = createRequire$1(import.meta.url); // set in bin/vite.js const filter$1 = process.env.VITE_DEBUG_FILTER; const DEBUG = process.env.DEBUG; function createDebugger(namespace, options = {}) { const log = debug$g(namespace); const { onlyWhenFocused } = options; let enabled = log.enabled; if (enabled && onlyWhenFocused) { const ns = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace; enabled = !!DEBUG?.includes(ns); } if (enabled) { return (...args) => { if (!filter$1 || args.some((a) => a?.includes?.(filter$1))) { log(...args); } }; } } function testCaseInsensitiveFS() { if (!CLIENT_ENTRY.endsWith('client.mjs')) { throw new Error(`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`); } if (!fs$l__default.existsSync(CLIENT_ENTRY)) { throw new Error('cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: ' + CLIENT_ENTRY); } return fs$l__default.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs')); } testCaseInsensitiveFS(); const isWindows$4 = os$3$1.platform() === 'win32'; function normalizePath$3(id) { return path$o$1.posix.normalize(isWindows$4 ? slash$1(id) : id); } function tryStatSync(file) { try { return fs$l__default.statSync(file, { throwIfNoEntry: false }); } catch { // Ignore errors } } // `fs.realpathSync.native` resolves differently in Windows network drive, // causing file read errors. skip for now. // https://github.com/nodejs/node/issues/37737 isWindows$4 ? windowsSafeRealPathSync : fs$l__default.realpathSync.native; // Based on https://github.com/larrybahr/windows-network-drive // MIT License, Copyright (c) 2017 Larry Bahr const windowsNetworkMap = new Map(); const parseNetUseRE = /^(\w+)? +(\w:) +([^ ]+)\s/; let firstSafeRealPathSyncRun = false; function windowsSafeRealPathSync(path) { if (!firstSafeRealPathSyncRun) { optimizeSafeRealPathSync(); firstSafeRealPathSyncRun = true; } return fs$l__default.realpathSync(path); } function optimizeSafeRealPathSync() { // Skip if using Node <16.18 due to MAX_PATH issue: https://github.com/vitejs/vite/issues/12931 const nodeVersion = process.versions.node.split('.').map(Number); if (nodeVersion[0] < 16 || (nodeVersion[0] === 16 && nodeVersion[1] < 18)) { fs$l__default.realpathSync; return; } // Check the availability `fs.realpathSync.native` // in Windows virtual and RAM disks that bypass the Volume Mount Manager, in programs such as imDisk // get the error EISDIR: illegal operation on a directory try { fs$l__default.realpathSync.native(path$o$1.resolve('./')); } catch (error) { if (error.message.includes('EISDIR: illegal operation on a directory')) { fs$l__default.realpathSync; return; } } exec('net use', (error, stdout) => { if (error) return; const lines = stdout.split('\n'); // OK Y: \\NETWORKA\Foo Microsoft Windows Network // OK Z: \\NETWORKA\Bar Microsoft Windows Network for (const line of lines) { const m = line.match(parseNetUseRE); if (m) windowsNetworkMap.set(m[3], m[2]); } if (windowsNetworkMap.size === 0) { fs$l__default.realpathSync.native; } }); } function arraify$1(target) { return Array.isArray(target) ? target : [target]; } // @ts-expect-error jest only exists when running Jest const usingDynamicImport = typeof jest === 'undefined'; /** * Dynamically import files. It will make sure it's not being compiled away by TS/Rollup. * * As a temporary workaround for Jest's lack of stable ESM support, we fallback to require * if we're in a Jest environment. * See https://github.com/vitejs/vite/pull/5197#issuecomment-938054077 * * @param file File path to import. */ usingDynamicImport ? new Function('file', 'return import(file)') : _require$3; path$o$1.dirname(fileURLToPath(import.meta.url)); [ { name: 'Assets', color: colors$1.green }, { name: 'CSS', color: colors$1.magenta }, { name: 'JS', color: colors$1.cyan }, ]; require$$0$4.sep; new RegExp("\\" + require$$0$4.posix.sep, "g"); new RegExp("\\" + require$$0$4.sep, "g"); var DEFAULT_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts"]; `\\.(?:${DEFAULT_EXTENSIONS.map((ext) => ext.substring(1)).join( "|" )})`; new Function("path", "return import(path).then(m => m.default)"); createDebugger('vite:esbuild'); var dist$1 = {}; var __importDefault$1 = (commonjsGlobal$1 && commonjsGlobal$1.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(dist$1, "__esModule", { value: true }); dist$1.Worker = void 0; const os_1 = __importDefault$1(require$$2$1); const worker_threads_1 = require$$1; class Worker { constructor(fn, options = {}) { this.code = genWorkerCode(fn); this.max = options.max || Math.max(1, os_1.default.cpus().length - 1); this.pool = []; this.idlePool = []; this.queue = []; } async run(...args) { const worker = await this._getAvailableWorker(); return new Promise((resolve, reject) => { worker.currentResolve = resolve; worker.currentReject = reject; worker.postMessage(args); }); } stop() { this.pool.forEach((w) => w.unref()); this.queue.forEach(([_, reject]) => reject(new Error('Main worker pool stopped before a worker was available.'))); this.pool = []; this.idlePool = []; this.queue = []; } async _getAvailableWorker() { // has idle one? if (this.idlePool.length) { return this.idlePool.shift(); } // can spawn more? if (this.pool.length < this.max) { const worker = new worker_threads_1.Worker(this.code, { eval: true }); worker.on('message', (res) => { worker.currentResolve && worker.currentResolve(res); worker.currentResolve = null; this._assignDoneWorker(worker); }); worker.on('error', (err) => { worker.currentReject && worker.currentReject(err); worker.currentReject = null; }); worker.on('exit', (code) => { const i = this.pool.indexOf(worker); if (i > -1) this.pool.splice(i, 1); if (code !== 0 && worker.currentReject) { worker.currentReject(new Error(`Wroker stopped with non-0 exit code ${code}`)); worker.currentReject = null; } }); this.pool.push(worker); return worker; } // no one is available, we have to wait let resolve; let reject; const onWorkerAvailablePromise = new Promise((r, rj) => { resolve = r; reject = rj; }); this.queue.push([resolve, reject]); return onWorkerAvailablePromise; } _assignDoneWorker(worker) { // someone's waiting already? if (this.queue.length) { const [resolve] = this.queue.shift(); resolve(worker); return; } // take a rest. this.idlePool.push(worker); } } dist$1.Worker = Worker; function genWorkerCode(fn) { return ` const doWork = ${fn.toString()} const { parentPort } = require('worker_threads') parentPort.on('message', async (args) => { const res = await doWork(...args) parentPort.postMessage(res) }) `; } Buffer$1.from('version https://git-lfs.github.com'); /* es-module-lexer 1.3.0 */ 1===new Uint8Array(new Uint16Array([1]).buffer)[0];WebAssembly.compile((E="AGFzbQEAAAABKghgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gAn9/AAMvLgABAQICAgICAgICAgICAgICAgIAAwMDBAQAAAADAAAAAAMDAAUGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUGw8gALfwBBsPIACwdwEwZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAmFpAAgCaWQACQJpcAAKAmVzAAsCZWUADANlbHMADQNlbGUADgJyaQAPAnJlABABZgARBXBhcnNlABILX19oZWFwX2Jhc2UDAQqsPS5oAQF/QQAgADYC9AlBACgC0AkiASAAQQF0aiIAQQA7AQBBACAAQQJqIgA2AvgJQQAgADYC/AlBAEEANgLUCUEAQQA2AuQJQQBBADYC3AlBAEEANgLYCUEAQQA2AuwJQQBBADYC4AkgAQufAQEDf0EAKALkCSEEQQBBACgC/AkiBTYC5AlBACAENgLoCUEAIAVBIGo2AvwJIARBHGpB1AkgBBsgBTYCAEEAKALICSEEQQAoAsQJIQYgBSABNgIAIAUgADYCCCAFIAIgAkECakEAIAYgA0YbIAQgA0YbNgIMIAUgAzYCFCAFQQA2AhAgBSACNgIEIAVBADYCHCAFQQAoAsQJIANGOgAYC1YBAX9BACgC7AkiBEEQakHYCSAEG0EAKAL8CSIENgIAQQAgBDYC7AlBACAEQRRqNgL8CSAEQQA2AhAgBCADNgIMIAQgAjYCCCAEIAE2AgQgBCAANgIACwgAQQAoAoAKCxUAQQAoAtwJKAIAQQAoAtAJa0EBdQseAQF/QQAoAtwJKAIEIgBBACgC0AlrQQF1QX8gABsLFQBBACgC3AkoAghBACgC0AlrQQF1Cx4BAX9BACgC3AkoAgwiAEEAKALQCWtBAXVBfyAAGwseAQF/QQAoAtwJKAIQIgBBACgC0AlrQQF1QX8gABsLOwEBfwJAQQAoAtwJKAIUIgBBACgCxAlHDQBBfw8LAkAgAEEAKALICUcNAEF+DwsgAEEAKALQCWtBAXULCwBBACgC3AktABgLFQBBACgC4AkoAgBBACgC0AlrQQF1CxUAQQAoAuAJKAIEQQAoAtAJa0EBdQseAQF/QQAoAuAJKAIIIgBBACgC0AlrQQF1QX8gABsLHgEBf0EAKALgCSgCDCIAQQAoAtAJa0EBdUF/IAAbCyUBAX9BAEEAKALcCSIAQRxqQdQJIAAbKAIAIgA2AtwJIABBAEcLJQEBf0EAQQAoAuAJIgBBEGpB2AkgABsoAgAiADYC4AkgAEEARwsIAEEALQCECgvmDAEGfyMAQYDQAGsiACQAQQBBAToAhApBAEEAKALMCTYCjApBAEEAKALQCUF+aiIBNgKgCkEAIAFBACgC9AlBAXRqIgI2AqQKQQBBADsBhgpBAEEAOwGICkEAQQA6AJAKQQBBADYCgApBAEEAOgDwCUEAIABBgBBqNgKUCkEAIAA2ApgKQQBBADoAnAoCQAJAAkACQANAQQAgAUECaiIDNgKgCiABIAJPDQECQCADLwEAIgJBd2pBBUkNAAJAAkACQAJAAkAgAkGbf2oOBQEICAgCAAsgAkEgRg0EIAJBL0YNAyACQTtGDQIMBwtBAC8BiAoNASADEBNFDQEgAUEEakGCCEEKEC0NARAUQQAtAIQKDQFBAEEAKAKgCiIBNgKMCgwHCyADEBNFDQAgAUEEakGMCEEKEC0NABAVC0EAQQAoAqAKNgKMCgwBCwJAIAEvAQQiA0EqRg0AIANBL0cNBBAWDAELQQEQFwtBACgCpAohAkEAKAKgCiEBDAALC0EAIQIgAyEBQQAtAPAJDQIMAQtBACABNgKgCkEAQQA6AIQKCwNAQQAgAUECaiIDNgKgCgJAAkACQAJAAkACQAJAAkACQCABQQAoAqQKTw0AIAMvAQAiAkF3akEFSQ0IAkACQAJAAkACQAJAAkACQAJAAkAgAkFgag4KEhEGEREREQUBAgALAkACQAJAAkAgAkGgf2oOCgsUFAMUARQUFAIACyACQYV/ag4DBRMGCQtBAC8BiAoNEiADEBNFDRIgAUEEakGCCEEKEC0NEhAUDBILIAMQE0UNESABQQRqQYwIQQoQLQ0REBUMEQsgAxATRQ0QIAEpAARC7ICEg7COwDlSDRAgAS8BDCIDQXdqIgFBF0sNDkEBIAF0QZ+AgARxRQ0ODA8LQQBBAC8BiAoiAUEBajsBiApBACgClAogAUEDdGoiAUEBNgIAIAFBACgCjAo2AgQMDwtBAC8BiAoiAkUNC0EAIAJBf2oiBDsBiApBAC8BhgoiAkUNDiACQQJ0QQAoApgKakF8aigCACIFKAIUQQAoApQKIARB//8DcUEDdGooAgRHDQ4CQCAFKAIEDQAgBSADNgIEC0EAIAJBf2o7AYYKIAUgAUEEajYCDAwOCwJAQQAoAowKIgEvAQBBKUcNAEEAKALkCSIDRQ0AIAMoAgQgAUcNAEEAQQAoAugJIgM2AuQJAkAgA0UNACADQQA2AhwMAQtBAEEANgLUCQtBAEEALwGICiIDQQFqOwGICkEAKAKUCiADQQN0aiIDQQZBAkEALQCcChs2AgAgAyABNgIEQQBBADoAnAoMDQtBAC8BiAoiAUUNCUEAIAFBf2oiATsBiApBACgClAogAUH//wNxQQN0aigCAEEERg0EDAwLQScQGAwLC0EiEBgMCgsgAkEvRw0JAkACQCABLwEEIgFBKkYNACABQS9HDQEQFgwMC0EBEBcMCwsCQAJAQQAoAowKIgEvAQAiAxAZRQ0AAkACQCADQVVqDgQACAEDCAsgAUF+ai8BAEErRg0GDAcLIAFBfmovAQBBLUYNBQwGCwJAIANB/QBGDQAgA0EpRw0FQQAoApQKQQAvAYgKQQN0aigCBBAaRQ0FDAYLQQAoApQKQQAvAYgKQQN0aiICKAIEEBsNBSACKAIAQQZGDQUMBAsgAUF+ai8BAEFQakH//wNxQQpJDQMMBAtBACgClApBAC8BiAoiAUEDdCIDakEAKAKMCjYCBEEAIAFBAWo7AYgKQQAoApQKIANqQQM2AgALEBwMBwtBAC0A8AlBAC8BhgpBAC8BiApyckUhAgwJCyABEB0NACADRQ0AIANBL0ZBAC0AkApBAEdxDQAgAUF+aiEBQQAoAtAJIQICQANAIAFBAmoiBCACTQ0BQQAgATYCjAogAS8BACEDIAFBfmoiBCEBIAMQHkUNAAsgBEECaiEEC0EBIQUgA0H//wNxEB9FDQEgBEF+aiEBAkADQCABQQJqIgMgAk0NAUEAIAE2AowKIAEvAQAhAyABQX5qIgQhASADEB8NAAsgBEECaiEDCyADECBFDQEQIUEAQQA6AJAKDAULECFBACEFC0EAIAU6AJAKDAMLECJBACECDAULIANBoAFHDQELQQBBAToAnAoLQQBBACgCoAo2AowKC0EAKAKgCiEBDAALCyAAQYDQAGokACACCxoAAkBBACgC0AkgAEcNAEEBDwsgAEF+ahAjC/IKAQZ/QQBBACgCoAoiAEEMaiIBNgKgCkEAKALsCSECQQEQJyEDAkACQAJAAkACQAJAAkACQAJAQQAoAqAKIgQgAUcNACADECZFDQELAkACQAJAAkACQAJAAkAgA0EqRg0AIANB+wBHDQFBACAEQQJqNgKgCkEBECchBEEAKAKgCiEFA0ACQAJAIARB//8DcSIDQSJGDQAgA0EnRg0AIAMQKhpBACgCoAohAwwBCyADEBhBAEEAKAKgCkECaiIDNgKgCgtBARAnGgJAIAUgAxArIgRBLEcNAEEAQQAoAqAKQQJqNgKgCkEBECchBAtBACgCoAohAyAEQf0ARg0DIAMgBUYNDyADIQUgA0EAKAKkCk0NAAwPCwtBACAEQQJqNgKgCkEBECcaQQAoAqAKIgMgAxArGgwCC0EAQQA6AIQKAkACQAJAAkACQAJAIANBn39qDgwCCwQBCwMLCwsLCwUACyADQfYARg0EDAoLQQAgBEEOaiIDNgKgCgJAAkACQEEBECdBn39qDgYAEgISEgESC0EAKAKgCiIFKQACQvOA5IPgjcAxUg0RIAUvAQoQH0UNEUEAIAVBCmo2AqAKQQAQJxoLQQAoAqAKIgVBAmpBoghBDhAtDRAgBS8BECICQXdqIgFBF0sNDUEBIAF0QZ+AgARxRQ0NDA4LQQAoAqAKIgUpAAJC7ICEg7COwDlSDQ8gBS8BCiICQXdqIgFBF00NBgwKC0EAIARBCmo2AqAKQQAQJxpBACgCoAohBAtBACAEQRBqNgKgCgJAQQEQJyIEQSpHDQBBAEEAKAKgCkECajYCoApBARAnIQQLQQAoAqAKIQMgBBAqGiADQQAoAqAKIgQgAyAEEAJBAEEAKAKgCkF+ajYCoAoPCwJAIAQpAAJC7ICEg7COwDlSDQAgBC8BChAeRQ0AQQAgBEEKajYCoApBARAnIQRBACgCoAohAyAEECoaIANBACgCoAoiBCADIAQQAkEAQQAoAqAKQX5qNgKgCg8LQQAgBEEEaiIENgKgCgtBACAEQQZqNgKgCkEAQQA6AIQKQQEQJyEEQQAoAqAKIQMgBBAqIQRBACgCoAohAiAEQd//A3EiAUHbAEcNA0EAIAJBAmo2AqAKQQEQJyEFQQAoAqAKIQNBACEEDAQLQQAgA0ECajYCoAoLQQEQJyEEQQAoAqAKIQMCQCAEQeYARw0AIANBAmpBnAhBBhAtDQBBACADQQhqNgKgCiAAQQEQJxApIAJBEGpB2AkgAhshAwNAIAMoAgAiA0UNBSADQgA3AgggA0EQaiEDDAALC0EAIANBfmo2AqAKDAMLQQEgAXRBn4CABHFFDQMMBAtBASEECwNAAkACQCAEDgIAAQELIAVB//8DcRAqGkEBIQQMAQsCQAJAQQAoAqAKIgQgA0YNACADIAQgAyAEEAJBARAnIQQCQCABQdsARw0AIARBIHJB/QBGDQQLQQAoAqAKIQMCQCAEQSxHDQBBACADQQJqNgKgCkEBECchBUEAKAKgCiEDIAVBIHJB+wBHDQILQQAgA0F+ajYCoAoLIAFB2wBHDQJBACACQX5qNgKgCg8LQQAhBAwACwsPCyACQaABRg0AIAJB+wBHDQQLQQAgBUEKajYCoApBARAnIgVB+wBGDQMMAgsCQCACQVhqDgMBAwEACyACQaABRw0CC0EAIAVBEGo2AqAKAkBBARAnIgVBKkcNAEEAQQAoAqAKQQJqNgKgCkEBECchBQsgBUEoRg0BC0EAKAKgCiEBIAUQKhpBACgCoAoiBSABTQ0AIAQgAyABIAUQAkEAQQAoAqAKQX5qNgKgCg8LIAQgA0EAQQAQAkEAIARBDGo2AqAKDwsQIgvUBgEEf0EAQQAoAqAKIgBBDGoiATYCoAoCQAJAAkACQAJAAkACQAJAAkACQEEBECciAkFZag4IBAIBBAEBAQMACyACQSJGDQMgAkH7AEYNBAtBACgCoAogAUcNAkEAIABBCmo2AqAKDwtBACgClApBAC8BiAoiAkEDdGoiAUEAKAKgCjYCBEEAIAJBAWo7AYgKIAFBBTYCAEEAKAKMCi8BAEEuRg0DQQBBACgCoAoiAUECajYCoApBARAnIQIgAEEAKAKgCkEAIAEQAUEAQQAvAYYKIgFBAWo7AYYKQQAoApgKIAFBAnRqQQAoAuQJNgIAAkAgAkEiRg0AIAJBJ0YNAEEAQQAoAqAKQX5qNgKgCg8LIAIQGEEAQQAoAqAKQQJqIgI2AqAKAkACQAJAQQEQJ0FXag4EAQICAAILQQBBACgCoApBAmo2AqAKQQEQJxpBACgC5AkiASACNgIEIAFBAToAGCABQQAoAqAKIgI2AhBBACACQX5qNgKgCg8LQQAoAuQJIgEgAjYCBCABQQE6ABhBAEEALwGICkF/ajsBiAogAUEAKAKgCkECajYCDEEAQQAvAYYKQX9qOwGGCg8LQQBBACgCoApBfmo2AqAKDwtBAEEAKAKgCkECajYCoApBARAnQe0ARw0CQQAoAqAKIgJBAmpBlghBBhAtDQICQEEAKAKMCiIBECgNACABLwEAQS5GDQMLIAAgACACQQhqQQAoAsgJEAEPC0EALwGICg0CQQAoAqAKIQJBACgCpAohAwNAIAIgA08NBQJAAkAgAi8BACIBQSdGDQAgAUEiRw0BCyAAIAEQKQ8LQQAgAkECaiICNgKgCgwACwtBACgCoAohAkEALwGICg0CAkADQAJAAkACQCACQQAoAqQKTw0AQQEQJyICQSJGDQEgAkEnRg0BIAJB/QBHDQJBAEEAKAKgCkECajYCoAoLQQEQJyEBQQAoAqAKIQICQCABQeYARw0AIAJBAmpBnAhBBhAtDQgLQQAgAkEIajYCoApBARAnIgJBIkYNAyACQSdGDQMMBwsgAhAYC0EAQQAoAqAKQQJqIgI2AqAKDAALCyAAIAIQKQsPC0EAQQAoAqAKQX5qNgKgCg8LQQAgAkF+ajYCoAoPCxAiC0cBA39BACgCoApBAmohAEEAKAKkCiEBAkADQCAAIgJBfmogAU8NASACQQJqIQAgAi8BAEF2ag4EAQAAAQALC0EAIAI2AqAKC5gBAQN/QQBBACgCoAoiAUECajYCoAogAUEGaiEBQQAoAqQKIQIDQAJAAkACQCABQXxqIAJPDQAgAUF+ai8BACEDAkACQCAADQAgA0EqRg0BIANBdmoOBAIEBAIECyADQSpHDQMLIAEvAQBBL0cNAkEAIAFBfmo2AqAKDAELIAFBfmohAQtBACABNgKgCg8LIAFBAmohAQwACwuIAQEEf0EAKAKgCiEBQQAoAqQKIQICQAJAA0AgASIDQQJqIQEgAyACTw0BIAEvAQAiBCAARg0CAkAgBEHcAEYNACAEQXZqDgQCAQECAQsgA0EEaiEBIAMvAQRBDUcNACADQQZqIAEgAy8BBkEKRhshAQwACwtBACABNgKgChAiDwtBACABNgKgCgtsAQF/AkACQCAAQV9qIgFBBUsNAEEBIAF0QTFxDQELIABBRmpB//8DcUEGSQ0AIABBKUcgAEFYakH//wNxQQdJcQ0AAkAgAEGlf2oOBAEAAAEACyAAQf0ARyAAQYV/akH//wNxQQRJcQ8LQQELLgEBf0EBIQECQCAAQZYJQQUQJA0AIABBoAlBAxAkDQAgAEGmCUECECQhAQsgAQuDAQECf0EBIQECQAJAAkACQAJAAkAgAC8BACICQUVqDgQFBAQBAAsCQCACQZt/ag4EAwQEAgALIAJBKUYNBCACQfkARw0DIABBfmpBsglBBhAkDwsgAEF+ai8BAEE9Rg8LIABBfmpBqglBBBAkDwsgAEF+akG+CUEDECQPC0EAIQELIAEL3gEBBH9BACgCoAohAEEAKAKkCiEBAkACQAJAA0AgACICQQJqIQAgAiABTw0BAkACQAJAIAAvAQAiA0Gkf2oOBQIDAwMBAAsgA0EkRw0CIAIvAQRB+wBHDQJBACACQQRqIgA2AqAKQQBBAC8BiAoiAkEBajsBiApBACgClAogAkEDdGoiAkEENgIAIAIgADYCBA8LQQAgADYCoApBAEEALwGICkF/aiIAOwGICkEAKAKUCiAAQf//A3FBA3RqKAIAQQNHDQMMBAsgAkEEaiEADAALC0EAIAA2AqAKCxAiCwu0AwECf0EAIQECQAJAAkACQAJAAkACQAJAAkACQCAALwEAQZx/ag4UAAECCQkJCQMJCQQFCQkGCQcJCQgJCwJAAkAgAEF+ai8BAEGXf2oOBAAKCgEKCyAAQXxqQboIQQIQJA8LIABBfGpBvghBAxAkDwsCQAJAAkAgAEF+ai8BAEGNf2oOAwABAgoLAkAgAEF8ai8BACICQeEARg0AIAJB7ABHDQogAEF6akHlABAlDwsgAEF6akHjABAlDwsgAEF8akHECEEEECQPCyAAQXxqQcwIQQYQJA8LIABBfmovAQBB7wBHDQYgAEF8ai8BAEHlAEcNBgJAIABBemovAQAiAkHwAEYNACACQeMARw0HIABBeGpB2AhBBhAkDwsgAEF4akHkCEECECQPCyAAQX5qQegIQQQQJA8LQQEhASAAQX5qIgBB6QAQJQ0EIABB8AhBBRAkDwsgAEF+akHkABAlDwsgAEF+akH6CEEHECQPCyAAQX5qQYgJQQQQJA8LAkAgAEF+ai8BACICQe8ARg0AIAJB5QBHDQEgAEF8akHuABAlDwsgAEF8akGQCUEDECQhAQsgAQs0AQF/QQEhAQJAIABBd2pB//8DcUEFSQ0AIABBgAFyQaABRg0AIABBLkcgABAmcSEBCyABCzABAX8CQAJAIABBd2oiAUEXSw0AQQEgAXRBjYCABHENAQsgAEGgAUYNAEEADwtBAQtOAQJ/QQAhAQJAAkAgAC8BACICQeUARg0AIAJB6wBHDQEgAEF+akHoCEEEECQPCyAAQX5qLwEAQfUARw0AIABBfGpBzAhBBhAkIQELIAELcAECfwJAAkADQEEAQQAoAqAKIgBBAmoiATYCoAogAEEAKAKkCk8NAQJAAkACQCABLwEAIgFBpX9qDgIBAgALAkAgAUF2ag4EBAMDBAALIAFBL0cNAgwECxAsGgwBC0EAIABBBGo2AqAKDAALCxAiCws1AQF/QQBBAToA8AlBACgCoAohAEEAQQAoAqQKQQJqNgKgCkEAIABBACgC0AlrQQF1NgKACgtDAQJ/QQEhAQJAIAAvAQAiAkF3akH//wNxQQVJDQAgAkGAAXJBoAFGDQBBACEBIAIQJkUNACACQS5HIAAQKHIPCyABC0YBA39BACEDAkAgACACQQF0IgJrIgRBAmoiAEEAKALQCSIFSQ0AIAAgASACEC0NAAJAIAAgBUcNAEEBDwsgBBAjIQMLIAMLPQECf0EAIQICQEEAKALQCSIDIABLDQAgAC8BACABRw0AAkAgAyAARw0AQQEPCyAAQX5qLwEAEB4hAgsgAgtoAQJ/QQEhAQJAAkAgAEFfaiICQQVLDQBBASACdEExcQ0BCyAAQfj/A3FBKEYNACAAQUZqQf//A3FBBkkNAAJAIABBpX9qIgJBA0sNACACQQFHDQELIABBhX9qQf//A3FBBEkhAQsgAQucAQEDf0EAKAKgCiEBAkADQAJAAkAgAS8BACICQS9HDQACQCABLwECIgFBKkYNACABQS9HDQQQFgwCCyAAEBcMAQsCQAJAIABFDQAgAkF3aiIBQRdLDQFBASABdEGfgIAEcUUNAQwCCyACEB9FDQMMAQsgAkGgAUcNAgtBAEEAKAKgCiIDQQJqIgE2AqAKIANBACgCpApJDQALCyACCzEBAX9BACEBAkAgAC8BAEEuRw0AIABBfmovAQBBLkcNACAAQXxqLwEAQS5GIQELIAELiQQBAX8CQCABQSJGDQAgAUEnRg0AECIPC0EAKAKgCiECIAEQGCAAIAJBAmpBACgCoApBACgCxAkQAUEAQQAoAqAKQQJqNgKgCgJAAkACQAJAQQAQJyIBQeEARg0AIAFB9wBGDQFBACgCoAohAQwCC0EAKAKgCiIBQQJqQbAIQQoQLQ0BQQYhAAwCC0EAKAKgCiIBLwECQekARw0AIAEvAQRB9ABHDQBBBCEAIAEvAQZB6ABGDQELQQAgAUF+ajYCoAoPC0EAIAEgAEEBdGo2AqAKAkBBARAnQfsARg0AQQAgATYCoAoPC0EAKAKgCiICIQADQEEAIABBAmo2AqAKAkACQAJAQQEQJyIAQSJGDQAgAEEnRw0BQScQGEEAQQAoAqAKQQJqNgKgCkEBECchAAwCC0EiEBhBAEEAKAKgCkECajYCoApBARAnIQAMAQsgABAqIQALAkAgAEE6Rg0AQQAgATYCoAoPC0EAQQAoAqAKQQJqNgKgCgJAQQEQJyIAQSJGDQAgAEEnRg0AQQAgATYCoAoPCyAAEBhBAEEAKAKgCkECajYCoAoCQAJAQQEQJyIAQSxGDQAgAEH9AEYNAUEAIAE2AqAKDwtBAEEAKAKgCkECajYCoApBARAnQf0ARg0AQQAoAqAKIQAMAQsLQQAoAuQJIgEgAjYCECABQQAoAqAKQQJqNgIMC20BAn8CQAJAA0ACQCAAQf//A3EiAUF3aiICQRdLDQBBASACdEGfgIAEcQ0CCyABQaABRg0BIAAhAiABECYNAkEAIQJBAEEAKAKgCiIAQQJqNgKgCiAALwECIgANAAwCCwsgACECCyACQf//A3ELqwEBBH8CQAJAQQAoAqAKIgIvAQAiA0HhAEYNACABIQQgACEFDAELQQAgAkEEajYCoApBARAnIQJBACgCoAohBQJAAkAgAkEiRg0AIAJBJ0YNACACECoaQQAoAqAKIQQMAQsgAhAYQQBBACgCoApBAmoiBDYCoAoLQQEQJyEDQQAoAqAKIQILAkAgAiAFRg0AIAUgBEEAIAAgACABRiICG0EAIAEgAhsQAgsgAwtyAQR/QQAoAqAKIQBBACgCpAohAQJAAkADQCAAQQJqIQIgACABTw0BAkACQCACLwEAIgNBpH9qDgIBBAALIAIhACADQXZqDgQCAQECAQsgAEEEaiEADAALC0EAIAI2AqAKECJBAA8LQQAgAjYCoApB3QALSQEDf0EAIQMCQCACRQ0AAkADQCAALQAAIgQgAS0AACIFRw0BIAFBAWohASAAQQFqIQAgAkF/aiICDQAMAgsLIAQgBWshAwsgAwsL4gECAEGACAvEAQAAeABwAG8AcgB0AG0AcABvAHIAdABlAHQAYQByAG8AbQB1AG4AYwB0AGkAbwBuAHMAcwBlAHIAdAB2AG8AeQBpAGUAZABlAGwAZQBjAG8AbgB0AGkAbgBpAG4AcwB0AGEAbgB0AHkAYgByAGUAYQByAGUAdAB1AHIAZABlAGIAdQBnAGcAZQBhAHcAYQBpAHQAaAByAHcAaABpAGwAZQBmAG8AcgBpAGYAYwBhAHQAYwBmAGkAbgBhAGwAbABlAGwAcwAAQcQJCxABAAAAAgAAAAAEAAAwOQAA","undefined"!=typeof Buffer?Buffer.from(E,"base64"):Uint8Array.from(atob(E),(A=>A.charCodeAt(0))))).then(WebAssembly.instantiate).then((({exports:A})=>{}));var E; var convertSourceMap$1 = {}; (function (exports) { Object.defineProperty(exports, 'commentRegex', { get: function getCommentRegex () { // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data. return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg; } }); Object.defineProperty(exports, 'mapFileCommentRegex', { get: function getMapFileCommentRegex () { // Matches sourceMappingURL in either // or /* comment styles. return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg; } }); var decodeBase64; if (typeof Buffer !== 'undefined') { if (typeof Buffer.from === 'function') { decodeBase64 = decodeBase64WithBufferFrom; } else { decodeBase64 = decodeBase64WithNewBuffer; } } else { decodeBase64 = decodeBase64WithAtob; } function decodeBase64WithBufferFrom(base64) { return Buffer.from(base64, 'base64').toString(); } function decodeBase64WithNewBuffer(base64) { if (typeof value === 'number') { throw new TypeError('The value to decode must not be of type number.'); } return new Buffer(base64, 'base64').toString(); } function decodeBase64WithAtob(base64) { return decodeURIComponent(escape(atob(base64))); } function stripComment(sm) { return sm.split(',').pop(); } function readFromFileMap(sm, read) { var r = exports.mapFileCommentRegex.exec(sm); // for some odd reason //# .. captures in 1 and /* .. */ in 2 var filename = r[1] || r[2]; try { var sm = read(filename); if (sm != null && typeof sm.catch === 'function') { return sm.catch(throwError); } else { return sm; } } catch (e) { throwError(e); } function throwError(e) { throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack); } } function Converter (sm, opts) { opts = opts || {}; if (opts.hasComment) { sm = stripComment(sm); } if (opts.encoding === 'base64') { sm = decodeBase64(sm); } else if (opts.encoding === 'uri') { sm = decodeURIComponent(sm); } if (opts.isJSON || opts.encoding) { sm = JSON.parse(sm); } this.sourcemap = sm; } Converter.prototype.toJSON = function (space) { return JSON.stringify(this.sourcemap, null, space); }; if (typeof Buffer !== 'undefined') { if (typeof Buffer.from === 'function') { Converter.prototype.toBase64 = encodeBase64WithBufferFrom; } else { Converter.prototype.toBase64 = encodeBase64WithNewBuffer; } } else { Converter.prototype.toBase64 = encodeBase64WithBtoa; } function encodeBase64WithBufferFrom() { var json = this.toJSON(); return Buffer.from(json, 'utf8').toString('base64'); } function encodeBase64WithNewBuffer() { var json = this.toJSON(); if (typeof json === 'number') { throw new TypeError('The json to encode must not be of type number.'); } return new Buffer(json, 'utf8').toString('base64'); } function encodeBase64WithBtoa() { var json = this.toJSON(); return btoa(unescape(encodeURIComponent(json))); } Converter.prototype.toURI = function () { var json = this.toJSON(); return encodeURIComponent(json); }; Converter.prototype.toComment = function (options) { var encoding, content, data; if (options != null && options.encoding === 'uri') { encoding = ''; content = this.toURI(); } else { encoding = ';base64'; content = this.toBase64(); } data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content; return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; }; // returns copy instead of original Converter.prototype.toObject = function () { return JSON.parse(this.toJSON()); }; Converter.prototype.addProperty = function (key, value) { if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead'); return this.setProperty(key, value); }; Converter.prototype.setProperty = function (key, value) { this.sourcemap[key] = value; return this; }; Converter.prototype.getProperty = function (key) { return this.sourcemap[key]; }; exports.fromObject = function (obj) { return new Converter(obj); }; exports.fromJSON = function (json) { return new Converter(json, { isJSON: true }); }; exports.fromURI = function (uri) { return new Converter(uri, { encoding: 'uri' }); }; exports.fromBase64 = function (base64) { return new Converter(base64, { encoding: 'base64' }); }; exports.fromComment = function (comment) { var m, encoding; comment = comment .replace(/^\/\*/g, '//') .replace(/\*\/$/g, ''); m = exports.commentRegex.exec(comment); encoding = m && m[4] || 'uri'; return new Converter(comment, { encoding: encoding, hasComment: true }); }; function makeConverter(sm) { return new Converter(sm, { isJSON: true }); } exports.fromMapFileComment = function (comment, read) { if (typeof read === 'string') { throw new Error( 'String directory paths are no longer supported with `fromMapFileComment`\n' + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' ) } var sm = readFromFileMap(comment, read); if (sm != null && typeof sm.then === 'function') { return sm.then(makeConverter); } else { return makeConverter(sm); } }; // Finds last sourcemap comment in file or returns null if none was found exports.fromSource = function (content) { var m = content.match(exports.commentRegex); return m ? exports.fromComment(m.pop()) : null; }; // Finds last sourcemap comment in file or returns null if none was found exports.fromMapFileSource = function (content, read) { if (typeof read === 'string') { throw new Error( 'String directory paths are no longer supported with `fromMapFileSource`\n' + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' ) } var m = content.match(exports.mapFileCommentRegex); return m ? exports.fromMapFileComment(m.pop(), read) : null; }; exports.removeComments = function (src) { return src.replace(exports.commentRegex, ''); }; exports.removeMapFileComments = function (src) { return src.replace(exports.mapFileCommentRegex, ''); }; exports.generateMapFileComment = function (file, options) { var data = 'sourceMappingURL=' + file; return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; }; } (convertSourceMap$1)); createDebugger('vite:sourcemap', { onlyWhenFocused: true, }); var tasks = {}; var utils$g = {}; var array$1 = {}; Object.defineProperty(array$1, "__esModule", { value: true }); array$1.splitWhen = array$1.flatten = void 0; function flatten$1(items) { return items.reduce((collection, item) => [].concat(collection, item), []); } array$1.flatten = flatten$1; function splitWhen(items, predicate) { const result = [[]]; let groupIndex = 0; for (const item of items) { if (predicate(item)) { groupIndex++; result[groupIndex] = []; } else { result[groupIndex].push(item); } } return result; } array$1.splitWhen = splitWhen; var errno$1 = {}; Object.defineProperty(errno$1, "__esModule", { value: true }); errno$1.isEnoentCodeError = void 0; function isEnoentCodeError(error) { return error.code === 'ENOENT'; } errno$1.isEnoentCodeError = isEnoentCodeError; var fs$h = {}; Object.defineProperty(fs$h, "__esModule", { value: true }); fs$h.createDirentFromStats = void 0; let DirentFromStats$1 = class DirentFromStats { constructor(name, stats) { this.name = name; this.isBlockDevice = stats.isBlockDevice.bind(stats); this.isCharacterDevice = stats.isCharacterDevice.bind(stats); this.isDirectory = stats.isDirectory.bind(stats); this.isFIFO = stats.isFIFO.bind(stats); this.isFile = stats.isFile.bind(stats); this.isSocket = stats.isSocket.bind(stats); this.isSymbolicLink = stats.isSymbolicLink.bind(stats); } }; function createDirentFromStats$1(name, stats) { return new DirentFromStats$1(name, stats); } fs$h.createDirentFromStats = createDirentFromStats$1; var path$h = {}; Object.defineProperty(path$h, "__esModule", { value: true }); path$h.convertPosixPathToPattern = path$h.convertWindowsPathToPattern = path$h.convertPathToPattern = path$h.escapePosixPath = path$h.escapeWindowsPath = path$h.escape = path$h.removeLeadingDotSegment = path$h.makeAbsolute = path$h.unixify = void 0; const os$3 = require$$2$1; const path$g = require$$0$4; const IS_WINDOWS_PLATFORM = os$3.platform() === 'win32'; const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ /** * All non-escaped special characters. * Posix: ()*?[\]{|}, !+@ before (, ! at the beginning, \\ before non-special characters. * Windows: (){}, !+@ before (, ! at the beginning. */ const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g; const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([(){}]|^!|[!+@](?=\())/g; /** * The device path (\\.\ or \\?\). * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths */ const DOS_DEVICE_PATH_RE = /^\\\\([.?])/; /** * All backslashes except those escaping special characters. * Windows: !()+@{} * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions */ const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@{}])/g; /** * Designed to work only with simple paths: `dir\\file`. */ function unixify(filepath) { return filepath.replace(/\\/g, '/'); } path$h.unixify = unixify; function makeAbsolute(cwd, filepath) { return path$g.resolve(cwd, filepath); } path$h.makeAbsolute = makeAbsolute; function removeLeadingDotSegment(entry) { // We do not use `startsWith` because this is 10x slower than current implementation for some cases. // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with if (entry.charAt(0) === '.') { const secondCharactery = entry.charAt(1); if (secondCharactery === '/' || secondCharactery === '\\') { return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); } } return entry; } path$h.removeLeadingDotSegment = removeLeadingDotSegment; path$h.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath; function escapeWindowsPath(pattern) { return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); } path$h.escapeWindowsPath = escapeWindowsPath; function escapePosixPath(pattern) { return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); } path$h.escapePosixPath = escapePosixPath; path$h.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern; function convertWindowsPathToPattern(filepath) { return escapeWindowsPath(filepath) .replace(DOS_DEVICE_PATH_RE, '//$1') .replace(WINDOWS_BACKSLASHES_RE, '/'); } path$h.convertWindowsPathToPattern = convertWindowsPathToPattern; function convertPosixPathToPattern(filepath) { return escapePosixPath(filepath); } path$h.convertPosixPathToPattern = convertPosixPathToPattern; var pattern$1 = {}; /*! * is-extglob * * Copyright (c) 2014-2016, Jon Schlinkert. * Licensed under the MIT License. */ var isExtglob$1 = function isExtglob(str) { if (typeof str !== 'string' || str === '') { return false; } var match; while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { if (match[2]) return true; str = str.slice(match.index + match[0].length); } return false; }; /*! * is-glob * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. */ var isExtglob = isExtglob$1; var chars$3 = { '{': '}', '(': ')', '[': ']'}; var strictCheck = function(str) { if (str[0] === '!') { return true; } var index = 0; var pipeIndex = -2; var closeSquareIndex = -2; var closeCurlyIndex = -2; var closeParenIndex = -2; var backSlashIndex = -2; while (index < str.length) { if (str[index] === '*') { return true; } if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) { return true; } if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') { if (closeSquareIndex < index) { closeSquareIndex = str.indexOf(']', index); } if (closeSquareIndex > index) { if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { return true; } backSlashIndex = str.indexOf('\\', index); if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { return true; } } } if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') { closeCurlyIndex = str.indexOf('}', index); if (closeCurlyIndex > index) { backSlashIndex = str.indexOf('\\', index); if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) { return true; } } } if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') { closeParenIndex = str.indexOf(')', index); if (closeParenIndex > index) { backSlashIndex = str.indexOf('\\', index); if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { return true; } } } if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') { if (pipeIndex < index) { pipeIndex = str.indexOf('|', index); } if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') { closeParenIndex = str.indexOf(')', pipeIndex); if (closeParenIndex > pipeIndex) { backSlashIndex = str.indexOf('\\', pipeIndex); if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { return true; } } } } if (str[index] === '\\') { var open = str[index + 1]; index += 2; var close = chars$3[open]; if (close) { var n = str.indexOf(close, index); if (n !== -1) { index = n + 1; } } if (str[index] === '!') { return true; } } else { index++; } } return false; }; var relaxedCheck = function(str) { if (str[0] === '!') { return true; } var index = 0; while (index < str.length) { if (/[*?{}()[\]]/.test(str[index])) { return true; } if (str[index] === '\\') { var open = str[index + 1]; index += 2; var close = chars$3[open]; if (close) { var n = str.indexOf(close, index); if (n !== -1) { index = n + 1; } } if (str[index] === '!') { return true; } } else { index++; } } return false; }; var isGlob$2 = function isGlob(str, options) { if (typeof str !== 'string' || str === '') { return false; } if (isExtglob(str)) { return true; } var check = strictCheck; // optionally relax check if (options && options.strict === false) { check = relaxedCheck; } return check(str); }; var isGlob$1 = isGlob$2; var pathPosixDirname = require$$0$4.posix.dirname; var isWin32 = require$$2$1.platform() === 'win32'; var slash = '/'; var backslash = /\\/g; var enclosure = /[\{\[].*[\}\]]$/; var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; /** * @param {string} str * @param {Object} opts * @param {boolean} [opts.flipBackslashes=true] * @returns {string} */ var globParent$2 = function globParent(str, opts) { var options = Object.assign({ flipBackslashes: true }, opts); // flip windows path separators if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { str = str.replace(backslash, slash); } // special case for strings ending in enclosure containing path separator if (enclosure.test(str)) { str += slash; } // preserves full path in case of trailing path separator str += 'a'; // remove path parts that are globby do { str = pathPosixDirname(str); } while (isGlob$1(str) || globby.test(str)); // remove escape chars and return result return str.replace(escaped, '$1'); }; var utils$f = {}; (function (exports) { exports.isInteger = num => { if (typeof num === 'number') { return Number.isInteger(num); } if (typeof num === 'string' && num.trim() !== '') { return Number.isInteger(Number(num)); } return false; }; /** * Find a node of the given type */ exports.find = (node, type) => node.nodes.find(node => node.type === type); /** * Find a node of the given type */ exports.exceedsLimit = (min, max, step = 1, limit) => { if (limit === false) return false; if (!exports.isInteger(min) || !exports.isInteger(max)) return false; return ((Number(max) - Number(min)) / Number(step)) >= limit; }; /** * Escape the given node with '\\' before node.value */ exports.escapeNode = (block, n = 0, type) => { let node = block.nodes[n]; if (!node) return; if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { if (node.escaped !== true) { node.value = '\\' + node.value; node.escaped = true; } } }; /** * Returns true if the given brace node should be enclosed in literal braces */ exports.encloseBrace = node => { if (node.type !== 'brace') return false; if ((node.commas >> 0 + node.ranges >> 0) === 0) { node.invalid = true; return true; } return false; }; /** * Returns true if a brace node is invalid. */ exports.isInvalidBrace = block => { if (block.type !== 'brace') return false; if (block.invalid === true || block.dollar) return true; if ((block.commas >> 0 + block.ranges >> 0) === 0) { block.invalid = true; return true; } if (block.open !== true || block.close !== true) { block.invalid = true; return true; } return false; }; /** * Returns true if a node is an open or close node */ exports.isOpenOrClose = node => { if (node.type === 'open' || node.type === 'close') { return true; } return node.open === true || node.close === true; }; /** * Reduce an array of text nodes. */ exports.reduce = nodes => nodes.reduce((acc, node) => { if (node.type === 'text') acc.push(node.value); if (node.type === 'range') node.type = 'text'; return acc; }, []); /** * Flatten an array */ exports.flatten = (...args) => { const result = []; const flat = arr => { for (let i = 0; i < arr.length; i++) { let ele = arr[i]; Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele); } return result; }; flat(args); return result; }; } (utils$f)); const utils$e = utils$f; var stringify$7 = (ast, options = {}) => { let stringify = (node, parent = {}) => { let invalidBlock = options.escapeInvalid && utils$e.isInvalidBrace(parent); let invalidNode = node.invalid === true && options.escapeInvalid === true; let output = ''; if (node.value) { if ((invalidBlock || invalidNode) && utils$e.isOpenOrClose(node)) { return '\\' + node.value; } return node.value; } if (node.value) { return node.value; } if (node.nodes) { for (let child of node.nodes) { output += stringify(child); } } return output; }; return stringify(ast); }; /*! * is-number * * Copyright (c) 2014-present, Jon Schlinkert. * Released under the MIT License. */ var isNumber$2 = function(num) { if (typeof num === 'number') { return num - num === 0; } if (typeof num === 'string' && num.trim() !== '') { return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); } return false; }; /*! * to-regex-range * * Copyright (c) 2015-present, Jon Schlinkert. * Released under the MIT License. */ const isNumber$1 = isNumber$2; const toRegexRange$1 = (min, max, options) => { if (isNumber$1(min) === false) { throw new TypeError('toRegexRange: expected the first argument to be a number'); } if (max === void 0 || min === max) { return String(min); } if (isNumber$1(max) === false) { throw new TypeError('toRegexRange: expected the second argument to be a number.'); } let opts = { relaxZeros: true, ...options }; if (typeof opts.strictZeros === 'boolean') { opts.relaxZeros = opts.strictZeros === false; } let relax = String(opts.relaxZeros); let shorthand = String(opts.shorthand); let capture = String(opts.capture); let wrap = String(opts.wrap); let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) { return toRegexRange$1.cache[cacheKey].result; } let a = Math.min(min, max); let b = Math.max(min, max); if (Math.abs(a - b) === 1) { let result = min + '|' + max; if (opts.capture) { return `(${result})`; } if (opts.wrap === false) { return result; } return `(?:${result})`; } let isPadded = hasPadding(min) || hasPadding(max); let state = { min, max, a, b }; let positives = []; let negatives = []; if (isPadded) { state.isPadded = isPadded; state.maxLen = String(state.max).length; } if (a < 0) { let newMin = b < 0 ? Math.abs(b) : 1; negatives = splitToPatterns(newMin, Math.abs(a), state, opts); a = state.a = 0; } if (b >= 0) { positives = splitToPatterns(a, b, state, opts); } state.negatives = negatives; state.positives = positives; state.result = collatePatterns(negatives, positives); if (opts.capture === true) { state.result = `(${state.result})`; } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { state.result = `(?:${state.result})`; } toRegexRange$1.cache[cacheKey] = state; return state.result; }; function collatePatterns(neg, pos, options) { let onlyNegative = filterPatterns(neg, pos, '-', false) || []; let onlyPositive = filterPatterns(pos, neg, '', false) || []; let intersected = filterPatterns(neg, pos, '-?', true) || []; let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); return subpatterns.join('|'); } function splitToRanges(min, max) { let nines = 1; let zeros = 1; let stop = countNines(min, nines); let stops = new Set([max]); while (min <= stop && stop <= max) { stops.add(stop); nines += 1; stop = countNines(min, nines); } stop = countZeros(max + 1, zeros) - 1; while (min < stop && stop <= max) { stops.add(stop); zeros += 1; stop = countZeros(max + 1, zeros) - 1; } stops = [...stops]; 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: start, count: [], digits: 0 }; } let zipped = zip(start, stop); let digits = zipped.length; let pattern = ''; let count = 0; for (let i = 0; i < digits; i++) { let [startDigit, stopDigit] = zipped[i]; if (startDigit === stopDigit) { pattern += startDigit; } else if (startDigit !== '0' || stopDigit !== '9') { pattern += toCharacterClass(startDigit, stopDigit); } else { count++; } } if (count) { pattern += options.shorthand === true ? '\\d' : '[0-9]'; } return { pattern, count: [count], digits }; } function splitToPatterns(min, max, tok, options) { let ranges = splitToRanges(min, max); let tokens = []; let start = min; let prev; for (let i = 0; i < ranges.length; i++) { let max = ranges[i]; let obj = rangeToPattern(String(start), String(max), options); let zeros = ''; if (!tok.isPadded && prev && prev.pattern === obj.pattern) { if (prev.count.length > 1) { prev.count.pop(); } prev.count.push(obj.count[0]); prev.string = prev.pattern + toQuantifier(prev.count); start = max + 1; continue; } if (tok.isPadded) { zeros = padZeros(max, tok, options); } obj.string = zeros + obj.pattern + toQuantifier(obj.count); tokens.push(obj); start = max + 1; prev = obj; } return tokens; } function filterPatterns(arr, comparison, prefix, intersection, options) { let result = []; for (let ele of arr) { let { string } = ele; // only push if _both_ are negative... if (!intersection && !contains(comparison, 'string', string)) { result.push(prefix + string); } // or _both_ are positive if (intersection && contains(comparison, 'string', string)) { result.push(prefix + string); } } return result; } /** * Zip strings */ function zip(a, b) { let arr = []; for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); return arr; } function compare(a, b) { return a > b ? 1 : b > a ? -1 : 0; } function contains(arr, key, val) { return arr.some(ele => ele[key] === val); } function countNines(min, len) { return Number(String(min).slice(0, -len) + '9'.repeat(len)); } function countZeros(integer, zeros) { return integer - (integer % Math.pow(10, zeros)); } function toQuantifier(digits) { let [start = 0, stop = ''] = digits; if (stop || start > 1) { return `{${start + (stop ? ',' + stop : '')}}`; } return ''; } function toCharacterClass(a, b, options) { return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; } function hasPadding(str) { return /^-?(0+)\d/.test(str); } function padZeros(value, tok, options) { if (!tok.isPadded) { return value; } let diff = Math.abs(tok.maxLen - String(value).length); let relax = options.relaxZeros !== false; switch (diff) { case 0: return ''; case 1: return relax ? '0?' : '0'; case 2: return relax ? '0{0,2}' : '00'; default: { return relax ? `0{0,${diff}}` : `0{${diff}}`; } } } /** * Cache */ toRegexRange$1.cache = {}; toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {}); /** * Expose `toRegexRange` */ var toRegexRange_1 = toRegexRange$1; /*! * fill-range * * Copyright (c) 2014-present, Jon Schlinkert. * Licensed under the MIT License. */ const util$1 = require$$0$6; const toRegexRange = toRegexRange_1; const isObject$2 = val => val !== null && typeof val === 'object' && !Array.isArray(val); const transform$1 = toNumber => { return value => toNumber === true ? Number(value) : String(value); }; const isValidValue = value => { return typeof value === 'number' || (typeof value === 'string' && value !== ''); }; const isNumber = num => Number.isInteger(+num); const zeros = input => { let value = `${input}`; let index = -1; if (value[0] === '-') value = value.slice(1); if (value === '0') return false; while (value[++index] === '0'); return index > 0; }; const stringify$6 = (start, end, options) => { if (typeof start === 'string' || typeof end === 'string') { return true; } return options.stringify === true; }; const pad = (input, maxLength, toNumber) => { if (maxLength > 0) { let dash = input[0] === '-' ? '-' : ''; if (dash) input = input.slice(1); input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); } if (toNumber === false) { return String(input); } return input; }; const toMaxLen = (input, maxLength) => { let negative = input[0] === '-' ? '-' : ''; if (negative) { input = input.slice(1); maxLength--; } while (input.length < maxLength) input = '0' + input; return negative ? ('-' + input) : input; }; const toSequence = (parts, options) => { parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); let prefix = options.capture ? '' : '?:'; let positives = ''; let negatives = ''; let result; if (parts.positives.length) { positives = parts.positives.join('|'); } if (parts.negatives.length) { negatives = `-(${prefix}${parts.negatives.join('|')})`; } if (positives && negatives) { result = `${positives}|${negatives}`; } else { result = positives || negatives; } if (options.wrap) { return `(${prefix}${result})`; } return result; }; const toRange = (a, b, isNumbers, options) => { if (isNumbers) { return toRegexRange(a, b, { wrap: false, ...options }); } let start = String.fromCharCode(a); if (a === b) return start; let stop = String.fromCharCode(b); return `[${start}-${stop}]`; }; const toRegex = (start, end, options) => { if (Array.isArray(start)) { let wrap = options.wrap === true; let prefix = options.capture ? '' : '?:'; return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); } return toRegexRange(start, end, options); }; const rangeError = (...args) => { return new RangeError('Invalid range arguments: ' + util$1.inspect(...args)); }; const invalidRange = (start, end, options) => { if (options.strictRanges === true) throw rangeError([start, end]); return []; }; const invalidStep = (step, options) => { if (options.strictRanges === true) { throw new TypeError(`Expected step "${step}" to be a number`); } return []; }; const fillNumbers = (start, end, step = 1, options = {}) => { let a = Number(start); let b = Number(end); if (!Number.isInteger(a) || !Number.isInteger(b)) { if (options.strictRanges === true) throw rangeError([start, end]); return []; } // fix negative zero if (a === 0) a = 0; if (b === 0) b = 0; let descending = a > b; let startString = String(start); let endString = String(end); let stepString = String(step); step = Math.max(Math.abs(step), 1); let padded = zeros(startString) || zeros(endString) || zeros(stepString); let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; let toNumber = padded === false && stringify$6(start, end, options) === false; let format = options.transform || transform$1(toNumber); if (options.toRegex && step === 1) { return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); } let parts = { negatives: [], positives: [] }; let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); let range = []; let index = 0; while (descending ? a >= b : a <= b) { if (options.toRegex === true && step > 1) { push(a); } else { range.push(pad(format(a, index), maxLen, toNumber)); } a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return step > 1 ? toSequence(parts, options) : toRegex(range, null, { wrap: false, ...options }); } return range; }; const fillLetters = (start, end, step = 1, options = {}) => { if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { return invalidRange(start, end, options); } let format = options.transform || (val => String.fromCharCode(val)); let a = `${start}`.charCodeAt(0); let b = `${end}`.charCodeAt(0); let descending = a > b; let min = Math.min(a, b); let max = Math.max(a, b); if (options.toRegex && step === 1) { return toRange(min, max, false, options); } let range = []; let index = 0; while (descending ? a >= b : a <= b) { range.push(format(a, index)); a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return toRegex(range, null, { wrap: false, options }); } return range; }; const fill$2 = (start, end, step, options = {}) => { if (end == null && isValidValue(start)) { return [start]; } if (!isValidValue(start) || !isValidValue(end)) { return invalidRange(start, end, options); } if (typeof step === 'function') { return fill$2(start, end, 1, { transform: step }); } if (isObject$2(step)) { return fill$2(start, end, 0, step); } let opts = { ...options }; if (opts.capture === true) opts.wrap = true; step = step || opts.step || 1; if (!isNumber(step)) { if (step != null && !isObject$2(step)) return invalidStep(step, opts); return fill$2(start, end, 1, step); } if (isNumber(start) && isNumber(end)) { return fillNumbers(start, end, step, opts); } return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); }; var fillRange = fill$2; const fill$1 = fillRange; const utils$d = utils$f; const compile$1 = (ast, options = {}) => { let walk = (node, parent = {}) => { let invalidBlock = utils$d.isInvalidBrace(parent); let invalidNode = node.invalid === true && options.escapeInvalid === true; let invalid = invalidBlock === true || invalidNode === true; let prefix = options.escapeInvalid === true ? '\\' : ''; let output = ''; if (node.isOpen === true) { return prefix + node.value; } if (node.isClose === true) { return prefix + node.value; } if (node.type === 'open') { return invalid ? (prefix + node.value) : '('; } if (node.type === 'close') { return invalid ? (prefix + node.value) : ')'; } if (node.type === 'comma') { return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); } if (node.value) { return node.value; } if (node.nodes && node.ranges > 0) { let args = utils$d.reduce(node.nodes); let range = fill$1(...args, { ...options, wrap: false, toRegex: true }); if (range.length !== 0) { return args.length > 1 && range.length > 1 ? `(${range})` : range; } } if (node.nodes) { for (let child of node.nodes) { output += walk(child, node); } } return output; }; return walk(ast); }; var compile_1 = compile$1; const fill = fillRange; const stringify$5 = stringify$7; const utils$c = utils$f; const append$1 = (queue = '', stash = '', enclose = false) => { let result = []; queue = [].concat(queue); stash = [].concat(stash); if (!stash.length) return queue; if (!queue.length) { return enclose ? utils$c.flatten(stash).map(ele => `{${ele}}`) : stash; } for (let item of queue) { if (Array.isArray(item)) { for (let value of item) { result.push(append$1(value, stash, enclose)); } } else { for (let ele of stash) { if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; result.push(Array.isArray(ele) ? append$1(item, ele, enclose) : (item + ele)); } } } return utils$c.flatten(result); }; const expand$2 = (ast, options = {}) => { let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; let walk = (node, parent = {}) => { node.queue = []; let p = parent; let q = parent.queue; while (p.type !== 'brace' && p.type !== 'root' && p.parent) { p = p.parent; q = p.queue; } if (node.invalid || node.dollar) { q.push(append$1(q.pop(), stringify$5(node, options))); return; } if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { q.push(append$1(q.pop(), ['{}'])); return; } if (node.nodes && node.ranges > 0) { let args = utils$c.reduce(node.nodes); if (utils$c.exceedsLimit(...args, options.step, rangeLimit)) { throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); } let range = fill(...args, options); if (range.length === 0) { range = stringify$5(node, options); } q.push(append$1(q.pop(), range)); node.nodes = []; return; } let enclose = utils$c.encloseBrace(node); let queue = node.queue; let block = node; while (block.type !== 'brace' && block.type !== 'root' && block.parent) { block = block.parent; queue = block.queue; } for (let i = 0; i < node.nodes.length; i++) { let child = node.nodes[i]; if (child.type === 'comma' && node.type === 'brace') { if (i === 1) queue.push(''); queue.push(''); continue; } if (child.type === 'close') { q.push(append$1(q.pop(), queue, enclose)); continue; } if (child.value && child.type !== 'open') { queue.push(append$1(queue.pop(), child.value)); continue; } if (child.nodes) { walk(child, node); } } return queue; }; return utils$c.flatten(walk(ast)); }; var expand_1$1 = expand$2; var constants$3 = { MAX_LENGTH: 1024 * 64, // Digits CHAR_0: '0', /* 0 */ CHAR_9: '9', /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 'A', /* A */ CHAR_LOWERCASE_A: 'a', /* a */ CHAR_UPPERCASE_Z: 'Z', /* Z */ CHAR_LOWERCASE_Z: 'z', /* z */ CHAR_LEFT_PARENTHESES: '(', /* ( */ CHAR_RIGHT_PARENTHESES: ')', /* ) */ CHAR_ASTERISK: '*', /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: '&', /* & */ CHAR_AT: '@', /* @ */ CHAR_BACKSLASH: '\\', /* \ */ CHAR_BACKTICK: '`', /* ` */ CHAR_CARRIAGE_RETURN: '\r', /* \r */ CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ CHAR_COLON: ':', /* : */ CHAR_COMMA: ',', /* , */ CHAR_DOLLAR: '$', /* . */ CHAR_DOT: '.', /* . */ CHAR_DOUBLE_QUOTE: '"', /* " */ CHAR_EQUAL: '=', /* = */ CHAR_EXCLAMATION_MARK: '!', /* ! */ CHAR_FORM_FEED: '\f', /* \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', /* \n */ CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ 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', /* \t */ CHAR_UNDERSCORE: '_', /* _ */ CHAR_VERTICAL_LINE: '|', /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ }; const stringify$4 = stringify$7; /** * Constants */ const { MAX_LENGTH: MAX_LENGTH$2, CHAR_BACKSLASH, /* \ */ CHAR_BACKTICK, /* ` */ CHAR_COMMA: CHAR_COMMA$2, /* , */ CHAR_DOT: CHAR_DOT$2, /* . */ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$2, /* ( */ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$2, /* ) */ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$2, /* { */ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$2, /* } */ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$2, /* [ */ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$2, /* ] */ CHAR_DOUBLE_QUOTE, /* " */ CHAR_SINGLE_QUOTE, /* ' */ CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = constants$3; /** * parse */ const parse$d = (input, options = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } let opts = options || {}; let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$2, opts.maxLength) : MAX_LENGTH$2; if (input.length > max) { throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); } let ast = { type: 'root', input, nodes: [] }; let stack = [ast]; let block = ast; let prev = ast; let brackets = 0; let length = input.length; let index = 0; let depth = 0; let value; /** * Helpers */ const advance = () => input[index++]; const push = node => { if (node.type === 'text' && prev.type === 'dot') { prev.type = 'text'; } if (prev && prev.type === 'text' && node.type === 'text') { prev.value += node.value; return; } block.nodes.push(node); node.parent = block; node.prev = prev; prev = node; return node; }; push({ type: 'bos' }); while (index < length) { block = stack[stack.length - 1]; value = advance(); /** * Invalid chars */ if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { continue; } /** * Escaped chars */ if (value === CHAR_BACKSLASH) { push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); continue; } /** * Right square bracket (literal): ']' */ if (value === CHAR_RIGHT_SQUARE_BRACKET$2) { push({ type: 'text', value: '\\' + value }); continue; } /** * Left square bracket: '[' */ if (value === CHAR_LEFT_SQUARE_BRACKET$2) { brackets++; let next; while (index < length && (next = advance())) { value += next; if (next === CHAR_LEFT_SQUARE_BRACKET$2) { brackets++; continue; } if (next === CHAR_BACKSLASH) { value += advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET$2) { brackets--; if (brackets === 0) { break; } } } push({ type: 'text', value }); continue; } /** * Parentheses */ if (value === CHAR_LEFT_PARENTHESES$2) { block = push({ type: 'paren', nodes: [] }); stack.push(block); push({ type: 'text', value }); continue; } if (value === CHAR_RIGHT_PARENTHESES$2) { if (block.type !== 'paren') { push({ type: 'text', value }); continue; } block = stack.pop(); push({ type: 'text', value }); block = stack[stack.length - 1]; continue; } /** * Quotes: '|"|` */ if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { let open = value; let next; if (options.keepQuotes !== true) { value = ''; } while (index < length && (next = advance())) { if (next === CHAR_BACKSLASH) { value += next + advance(); continue; } if (next === open) { if (options.keepQuotes === true) value += next; break; } value += next; } push({ type: 'text', value }); continue; } /** * Left curly brace: '{' */ if (value === CHAR_LEFT_CURLY_BRACE$2) { depth++; let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; let brace = { type: 'brace', open: true, close: false, dollar, depth, commas: 0, ranges: 0, nodes: [] }; block = push(brace); stack.push(block); push({ type: 'open', value }); continue; } /** * Right curly brace: '}' */ if (value === CHAR_RIGHT_CURLY_BRACE$2) { if (block.type !== 'brace') { push({ type: 'text', value }); continue; } let type = 'close'; block = stack.pop(); block.close = true; push({ type, value }); depth--; block = stack[stack.length - 1]; continue; } /** * Comma: ',' */ if (value === CHAR_COMMA$2 && depth > 0) { if (block.ranges > 0) { block.ranges = 0; let open = block.nodes.shift(); block.nodes = [open, { type: 'text', value: stringify$4(block) }]; } push({ type: 'comma', value }); block.commas++; continue; } /** * Dot: '.' */ if (value === CHAR_DOT$2 && depth > 0 && block.commas === 0) { let siblings = block.nodes; if (depth === 0 || siblings.length === 0) { push({ type: 'text', value }); continue; } if (prev.type === 'dot') { block.range = []; prev.value += value; prev.type = 'range'; if (block.nodes.length !== 3 && block.nodes.length !== 5) { block.invalid = true; block.ranges = 0; prev.type = 'text'; continue; } block.ranges++; block.args = []; continue; } if (prev.type === 'range') { siblings.pop(); let before = siblings[siblings.length - 1]; before.value += prev.value + value; prev = before; block.ranges--; continue; } push({ type: 'dot', value }); continue; } /** * Text */ push({ type: 'text', value }); } // Mark imbalanced braces and brackets as invalid do { block = stack.pop(); if (block.type !== 'root') { block.nodes.forEach(node => { if (!node.nodes) { if (node.type === 'open') node.isOpen = true; if (node.type === 'close') node.isClose = true; if (!node.nodes) node.type = 'text'; node.invalid = true; } }); // get the location of the block on parent.nodes (block's siblings) let parent = stack[stack.length - 1]; let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes parent.nodes.splice(index, 1, ...block.nodes); } } while (stack.length > 0); push({ type: 'eos' }); return ast; }; var parse_1$2 = parse$d; const stringify$3 = stringify$7; const compile = compile_1; const expand$1 = expand_1$1; const parse$c = parse_1$2; /** * Expand the given pattern or create a regex-compatible string. * * ```js * const braces = require('braces'); * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] * ``` * @param {String} `str` * @param {Object} `options` * @return {String} * @api public */ const braces$2 = (input, options = {}) => { let output = []; if (Array.isArray(input)) { for (let pattern of input) { let result = braces$2.create(pattern, options); if (Array.isArray(result)) { output.push(...result); } else { output.push(result); } } } else { output = [].concat(braces$2.create(input, options)); } if (options && options.expand === true && options.nodupes === true) { output = [...new Set(output)]; } return output; }; /** * Parse the given `str` with the given `options`. * * ```js * // braces.parse(pattern, [, options]); * const ast = braces.parse('a/{b,c}/d'); * console.log(ast); * ``` * @param {String} pattern Brace pattern to parse * @param {Object} options * @return {Object} Returns an AST * @api public */ braces$2.parse = (input, options = {}) => parse$c(input, options); /** * Creates a braces string from an AST, or an AST node. * * ```js * const braces = require('braces'); * let ast = braces.parse('foo/{a,b}/bar'); * console.log(stringify(ast.nodes[2])); //=> '{a,b}' * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces$2.stringify = (input, options = {}) => { if (typeof input === 'string') { return stringify$3(braces$2.parse(input, options), options); } return stringify$3(input, options); }; /** * Compiles a brace pattern into a regex-compatible, optimized string. * This method is called by the main [braces](#braces) function by default. * * ```js * const braces = require('braces'); * console.log(braces.compile('a/{b,c}/d')); * //=> ['a/(b|c)/d'] * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces$2.compile = (input, options = {}) => { if (typeof input === 'string') { input = braces$2.parse(input, options); } return compile(input, options); }; /** * 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 [.compile](#compile) instead. * * ```js * const 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 */ braces$2.expand = (input, options = {}) => { if (typeof input === 'string') { input = braces$2.parse(input, options); } let result = expand$1(input, options); // filter out empty strings if specified if (options.noempty === true) { result = result.filter(Boolean); } // filter out duplicates if specified if (options.nodupes === true) { result = [...new Set(result)]; } return result; }; /** * 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 * const 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 */ braces$2.create = (input, options = {}) => { if (input === '' || input.length < 3) { return [input]; } return options.expand !== true ? braces$2.compile(input, options) : braces$2.expand(input, options); }; /** * Expose "braces" */ var braces_1 = braces$2; const util$3 = require$$0$6; const braces$1 = braces_1; const picomatch$2 = picomatch$3; const utils$b = utils$k; const isEmptyString = val => val === '' || val === './'; /** * Returns an array of strings that match one or more glob patterns. * * ```js * const mm = require('micromatch'); * // mm(list, patterns[, options]); * * console.log(mm(['a.js', 'a.txt'], ['*.js'])); * //=> [ 'a.js' ] * ``` * @param {String|Array} `list` 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) * @return {Array} Returns an array of matches * @summary false * @api public */ const micromatch$1 = (list, patterns, options) => { patterns = [].concat(patterns); list = [].concat(list); let omit = new Set(); let keep = new Set(); let items = new Set(); let negatives = 0; let onResult = state => { items.add(state.output); if (options && options.onResult) { options.onResult(state); } }; for (let i = 0; i < patterns.length; i++) { let isMatch = picomatch$2(String(patterns[i]), { ...options, onResult }, true); let negated = isMatch.state.negated || isMatch.state.negatedExtglob; if (negated) negatives++; for (let item of list) { let matched = isMatch(item, true); let match = negated ? !matched.isMatch : matched.isMatch; if (!match) continue; if (negated) { omit.add(matched.output); } else { omit.delete(matched.output); keep.add(matched.output); } } } let result = negatives === patterns.length ? [...items] : [...keep]; let matches = result.filter(item => !omit.has(item)); if (options && matches.length === 0) { if (options.failglob === true) { throw new Error(`No matches found for "${patterns.join(', ')}"`); } if (options.nonull === true || options.nullglob === true) { return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; } } return matches; }; /** * Backwards compatibility */ micromatch$1.match = micromatch$1; /** * Returns a 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 * const mm = require('micromatch'); * // mm.matcher(pattern[, options]); * * const isMatch = mm.matcher('*.!(*a)'); * console.log(isMatch('a.a')); //=> false * console.log(isMatch('a.b')); //=> true * ``` * @param {String} `pattern` Glob pattern * @param {Object} `options` * @return {Function} Returns a matcher function. * @api public */ micromatch$1.matcher = (pattern, options) => picomatch$2(pattern, options); /** * Returns true if **any** of the given glob `patterns` match the specified `string`. * * ```js * const mm = require('micromatch'); * // mm.isMatch(string, patterns[, options]); * * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true * console.log(mm.isMatch('a.a', 'b.*')); //=> false * ``` * @param {String} `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). * @return {Boolean} Returns true if any patterns match `str` * @api public */ micromatch$1.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str); /** * Backwards compatibility */ micromatch$1.any = micromatch$1.isMatch; /** * Returns a list of strings that _**do not match any**_ of the given `patterns`. * * ```js * const mm = require('micromatch'); * // mm.not(list, patterns[, options]); * * console.log(mm.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 */ micromatch$1.not = (list, patterns, options = {}) => { patterns = [].concat(patterns).map(String); let result = new Set(); let items = []; let onResult = state => { if (options.onResult) options.onResult(state); items.push(state.output); }; let matches = new Set(micromatch$1(list, patterns, { ...options, onResult })); for (let item of items) { if (!matches.has(item)) { result.add(item); } } return [...result]; }; /** * 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 mm = require('micromatch'); * // mm.contains(string, pattern[, options]); * * console.log(mm.contains('aa/bb/cc', '*b')); * //=> true * console.log(mm.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 any of the patterns matches any part of `str`. * @api public */ micromatch$1.contains = (str, pattern, options) => { if (typeof str !== 'string') { throw new TypeError(`Expected a string: "${util$3.inspect(str)}"`); } if (Array.isArray(pattern)) { return pattern.some(p => micromatch$1.contains(str, p, options)); } if (typeof pattern === 'string') { if (isEmptyString(str) || isEmptyString(pattern)) { return false; } if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { return true; } } return micromatch$1.isMatch(str, pattern, { ...options, contains: true }); }; /** * 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 * const mm = require('micromatch'); * // mm.matchKeys(object, patterns[, options]); * * const obj = { aa: 'a', ab: 'b', ac: 'c' }; * console.log(mm.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 */ micromatch$1.matchKeys = (obj, patterns, options) => { if (!utils$b.isObject(obj)) { throw new TypeError('Expected the first argument to be an object'); } let keys = micromatch$1(Object.keys(obj), patterns, options); let res = {}; for (let key of keys) res[key] = obj[key]; return res; }; /** * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. * * ```js * const mm = require('micromatch'); * // mm.some(list, patterns[, options]); * * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // true * console.log(mm.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` matches any of the strings in `list` * @api public */ micromatch$1.some = (list, patterns, options) => { let items = [].concat(list); for (let pattern of [].concat(patterns)) { let isMatch = picomatch$2(String(pattern), options); if (items.some(item => isMatch(item))) { return true; } } return false; }; /** * Returns true if every string in the given `list` matches * any of the given glob `patterns`. * * ```js * const mm = require('micromatch'); * // mm.every(list, patterns[, options]); * * console.log(mm.every('foo.js', ['foo.js'])); * // true * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); * // true * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // false * console.log(mm.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 all `patterns` matches all of the strings in `list` * @api public */ micromatch$1.every = (list, patterns, options) => { let items = [].concat(list); for (let pattern of [].concat(patterns)) { let isMatch = picomatch$2(String(pattern), options); if (!items.every(item => isMatch(item))) { return false; } } return true; }; /** * Returns true if **all** of the given `patterns` match * the specified string. * * ```js * const mm = require('micromatch'); * // mm.all(string, patterns[, options]); * * console.log(mm.all('foo.js', ['foo.js'])); * // true * * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); * // false * * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); * // true * * console.log(mm.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 */ micromatch$1.all = (str, patterns, options) => { if (typeof str !== 'string') { throw new TypeError(`Expected a string: "${util$3.inspect(str)}"`); } return [].concat(patterns).every(p => picomatch$2(p, options)(str)); }; /** * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. * * ```js * const mm = require('micromatch'); * // mm.capture(pattern, string[, options]); * * console.log(mm.capture('test/*.js', 'test/foo.js')); * //=> ['foo'] * console.log(mm.capture('test/*.js', 'foo/bar.css')); * //=> null * ``` * @param {String} `glob` Glob pattern to use for matching. * @param {String} `input` String to match * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. * @api public */ micromatch$1.capture = (glob, input, options) => { let posix = utils$b.isWindows(options); let regex = picomatch$2.makeRe(String(glob), { ...options, capture: true }); let match = regex.exec(posix ? utils$b.toPosixSlashes(input) : input); if (match) { return match.slice(1).map(v => v === void 0 ? '' : v); } }; /** * Create a regular expression from the given glob `pattern`. * * ```js * const mm = require('micromatch'); * // mm.makeRe(pattern[, options]); * * console.log(mm.makeRe('*.js')); * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ * ``` * @param {String} `pattern` A glob pattern to convert to regex. * @param {Object} `options` * @return {RegExp} Returns a regex created from the given pattern. * @api public */ micromatch$1.makeRe = (...args) => picomatch$2.makeRe(...args); /** * Scan a glob pattern to separate the pattern into segments. Used * by the [split](#split) method. * * ```js * const mm = require('micromatch'); * const state = mm.scan(pattern[, options]); * ``` * @param {String} `pattern` * @param {Object} `options` * @return {Object} Returns an object with * @api public */ micromatch$1.scan = (...args) => picomatch$2.scan(...args); /** * Parse a glob pattern to create the source string for a regular * expression. * * ```js * const mm = require('micromatch'); * const state = mm.parse(pattern[, options]); * ``` * @param {String} `glob` * @param {Object} `options` * @return {Object} Returns an object with useful properties and output to be used as regex source string. * @api public */ micromatch$1.parse = (patterns, options) => { let res = []; for (let pattern of [].concat(patterns || [])) { for (let str of braces$1(String(pattern), options)) { res.push(picomatch$2.parse(str, options)); } } return res; }; /** * Process the given brace `pattern`. * * ```js * const { braces } = require('micromatch'); * console.log(braces('foo/{a,b,c}/bar')); * //=> [ 'foo/(a|b|c)/bar' ] * * console.log(braces('foo/{a,b,c}/bar', { expand: true })); * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] * ``` * @param {String} `pattern` String with brace pattern to process. * @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$1.braces = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) { return [pattern]; } return braces$1(pattern, options); }; /** * Expand braces */ micromatch$1.braceExpand = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); return micromatch$1.braces(pattern, { ...options, expand: true }); }; /** * Expose micromatch */ var micromatch_1 = micromatch$1; Object.defineProperty(pattern$1, "__esModule", { value: true }); pattern$1.removeDuplicateSlashes = pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0; const path$f = require$$0$4; const globParent$1 = globParent$2; const micromatch = micromatch_1; const GLOBSTAR$1 = '**'; const ESCAPE_SYMBOL = '\\'; const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/; const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/; const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/; const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./; /** * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string. * The latter is due to the presence of the device path at the beginning of the UNC path. */ const DOUBLE_SLASH_RE$1 = /(?!^)\/{2,}/g; function isStaticPattern(pattern, options = {}) { return !isDynamicPattern(pattern, options); } pattern$1.isStaticPattern = isStaticPattern; function isDynamicPattern(pattern, options = {}) { /** * A special case with an empty string is necessary for matching patterns that start with a forward slash. * An empty string cannot be a dynamic pattern. * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. */ if (pattern === '') { return false; } /** * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check * filepath directly (without read directory). */ if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { return true; } if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { return true; } if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { return true; } if (options.braceExpansion !== false && hasBraceExpansion(pattern)) { return true; } return false; } pattern$1.isDynamicPattern = isDynamicPattern; function hasBraceExpansion(pattern) { const openingBraceIndex = pattern.indexOf('{'); if (openingBraceIndex === -1) { return false; } const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1); if (closingBraceIndex === -1) { return false; } const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex); return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent); } function convertToPositivePattern(pattern) { return isNegativePattern(pattern) ? pattern.slice(1) : pattern; } pattern$1.convertToPositivePattern = convertToPositivePattern; function convertToNegativePattern(pattern) { return '!' + pattern; } pattern$1.convertToNegativePattern = convertToNegativePattern; function isNegativePattern(pattern) { return pattern.startsWith('!') && pattern[1] !== '('; } pattern$1.isNegativePattern = isNegativePattern; function isPositivePattern(pattern) { return !isNegativePattern(pattern); } pattern$1.isPositivePattern = isPositivePattern; function getNegativePatterns(patterns) { return patterns.filter(isNegativePattern); } pattern$1.getNegativePatterns = getNegativePatterns; function getPositivePatterns$1(patterns) { return patterns.filter(isPositivePattern); } pattern$1.getPositivePatterns = getPositivePatterns$1; /** * Returns patterns that can be applied inside the current directory. * * @example * // ['./*', '*', 'a/*'] * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) */ function getPatternsInsideCurrentDirectory(patterns) { return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); } pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; /** * Returns patterns to be expanded relative to (outside) the current directory. * * @example * // ['../*', './../*'] * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) */ function getPatternsOutsideCurrentDirectory(patterns) { return patterns.filter(isPatternRelatedToParentDirectory); } pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; function isPatternRelatedToParentDirectory(pattern) { return pattern.startsWith('..') || pattern.startsWith('./..'); } pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; function getBaseDirectory(pattern) { return globParent$1(pattern, { flipBackslashes: false }); } pattern$1.getBaseDirectory = getBaseDirectory; function hasGlobStar(pattern) { return pattern.includes(GLOBSTAR$1); } pattern$1.hasGlobStar = hasGlobStar; function endsWithSlashGlobStar(pattern) { return pattern.endsWith('/' + GLOBSTAR$1); } pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar; function isAffectDepthOfReadingPattern(pattern) { const basename = path$f.basename(pattern); return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); } pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; function expandPatternsWithBraceExpansion(patterns) { return patterns.reduce((collection, pattern) => { return collection.concat(expandBraceExpansion(pattern)); }, []); } pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; function expandBraceExpansion(pattern) { const patterns = micromatch.braces(pattern, { expand: true, nodupes: true }); /** * Sort the patterns by length so that the same depth patterns are processed side by side. * `a/{b,}/{c,}/*` – `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']` */ patterns.sort((a, b) => a.length - b.length); /** * Micromatch can return an empty string in the case of patterns like `{a,}`. */ return patterns.filter((pattern) => pattern !== ''); } pattern$1.expandBraceExpansion = expandBraceExpansion; function getPatternParts(pattern, options) { let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); /** * The scan method returns an empty array in some cases. * See micromatch/picomatch#58 for more details. */ if (parts.length === 0) { parts = [pattern]; } /** * The scan method does not return an empty part for the pattern with a forward slash. * This is another part of micromatch/picomatch#58. */ if (parts[0].startsWith('/')) { parts[0] = parts[0].slice(1); parts.unshift(''); } return parts; } pattern$1.getPatternParts = getPatternParts; function makeRe(pattern, options) { return micromatch.makeRe(pattern, options); } pattern$1.makeRe = makeRe; function convertPatternsToRe(patterns, options) { return patterns.map((pattern) => makeRe(pattern, options)); } pattern$1.convertPatternsToRe = convertPatternsToRe; function matchAny(entry, patternsRe) { return patternsRe.some((patternRe) => patternRe.test(entry)); } pattern$1.matchAny = matchAny; /** * This package only works with forward slashes as a path separator. * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. */ function removeDuplicateSlashes(pattern) { return pattern.replace(DOUBLE_SLASH_RE$1, '/'); } pattern$1.removeDuplicateSlashes = removeDuplicateSlashes; var stream$4 = {}; /* * merge2 * https://github.com/teambition/merge2 * * Copyright (c) 2014-2020 Teambition * Licensed under the MIT license. */ const Stream = require$$0$7; const PassThrough = Stream.PassThrough; const slice = Array.prototype.slice; var merge2_1 = merge2$1; function merge2$1 () { const streamsQueue = []; const args = slice.call(arguments); let merging = false; let options = args[args.length - 1]; if (options && !Array.isArray(options) && options.pipe == null) { args.pop(); } else { options = {}; } const doEnd = options.end !== false; const doPipeError = options.pipeError === true; if (options.objectMode == null) { options.objectMode = true; } if (options.highWaterMark == null) { options.highWaterMark = 64 * 1024; } const mergedStream = PassThrough(options); function addStream () { for (let i = 0, len = arguments.length; i < len; i++) { streamsQueue.push(pauseStreams(arguments[i], options)); } mergeStream(); return this } function mergeStream () { if (merging) { return } merging = true; let streams = streamsQueue.shift(); if (!streams) { process.nextTick(endStream); return } if (!Array.isArray(streams)) { streams = [streams]; } let pipesCount = streams.length + 1; function next () { if (--pipesCount > 0) { return } merging = false; mergeStream(); } function pipe (stream) { function onend () { stream.removeListener('merge2UnpipeEnd', onend); stream.removeListener('end', onend); if (doPipeError) { stream.removeListener('error', onerror); } next(); } function onerror (err) { mergedStream.emit('error', err); } // skip ended stream if (stream._readableState.endEmitted) { return next() } stream.on('merge2UnpipeEnd', onend); stream.on('end', onend); if (doPipeError) { stream.on('error', onerror); } stream.pipe(mergedStream, { end: false }); // compatible for old stream stream.resume(); } for (let i = 0; i < streams.length; i++) { pipe(streams[i]); } next(); } function endStream () { merging = false; // emit 'queueDrain' when all streams merged. mergedStream.emit('queueDrain'); if (doEnd) { mergedStream.end(); } } mergedStream.setMaxListeners(0); mergedStream.add = addStream; mergedStream.on('unpipe', function (stream) { stream.emit('merge2UnpipeEnd'); }); if (args.length) { addStream.apply(null, args); } return mergedStream } // check and pause streams for pipe. function pauseStreams (streams, options) { if (!Array.isArray(streams)) { // Backwards-compat with old-style streams if (!streams._readableState && streams.pipe) { streams = streams.pipe(PassThrough(options)); } if (!streams._readableState || !streams.pause || !streams.pipe) { throw new Error('Only readable stream can be merged.') } streams.pause(); } else { for (let i = 0, len = streams.length; i < len; i++) { streams[i] = pauseStreams(streams[i], options); } } return streams } Object.defineProperty(stream$4, "__esModule", { value: true }); stream$4.merge = void 0; const merge2 = merge2_1; function merge$1(streams) { const mergedStream = merge2(streams); streams.forEach((stream) => { stream.once('error', (error) => mergedStream.emit('error', error)); }); mergedStream.once('close', () => propagateCloseEventToSources(streams)); mergedStream.once('end', () => propagateCloseEventToSources(streams)); return mergedStream; } stream$4.merge = merge$1; function propagateCloseEventToSources(streams) { streams.forEach((stream) => stream.emit('close')); } var string$2 = {}; Object.defineProperty(string$2, "__esModule", { value: true }); string$2.isEmpty = string$2.isString = void 0; function isString$1(input) { return typeof input === 'string'; } string$2.isString = isString$1; function isEmpty$1(input) { return input === ''; } string$2.isEmpty = isEmpty$1; Object.defineProperty(utils$g, "__esModule", { value: true }); utils$g.string = utils$g.stream = utils$g.pattern = utils$g.path = utils$g.fs = utils$g.errno = utils$g.array = void 0; const array = array$1; utils$g.array = array; const errno = errno$1; utils$g.errno = errno; const fs$g = fs$h; utils$g.fs = fs$g; const path$e = path$h; utils$g.path = path$e; const pattern = pattern$1; utils$g.pattern = pattern; const stream$3 = stream$4; utils$g.stream = stream$3; const string$1 = string$2; utils$g.string = string$1; Object.defineProperty(tasks, "__esModule", { value: true }); tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0; const utils$a = utils$g; function generate(input, settings) { const patterns = processPatterns(input, settings); const ignore = processPatterns(settings.ignore, settings); const positivePatterns = getPositivePatterns(patterns); const negativePatterns = getNegativePatternsAsPositive(patterns, ignore); const staticPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isStaticPattern(pattern, settings)); const dynamicPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isDynamicPattern(pattern, settings)); const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); return staticTasks.concat(dynamicTasks); } tasks.generate = generate; function processPatterns(input, settings) { let patterns = input; /** * The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry * and some problems with the micromatch package (see fast-glob issues: #365, #394). * * To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown * in matching in the case of a large set of patterns after expansion. */ if (settings.braceExpansion) { patterns = utils$a.pattern.expandPatternsWithBraceExpansion(patterns); } /** * If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used * at any nesting level. * * We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change * the pattern in the filter before creating a regular expression. There is no need to change the patterns * in the application. Only on the input. */ if (settings.baseNameMatch) { patterns = patterns.map((pattern) => pattern.includes('/') ? pattern : `**/${pattern}`); } /** * This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion. */ return patterns.map((pattern) => utils$a.pattern.removeDuplicateSlashes(pattern)); } /** * Returns tasks grouped by basic pattern directories. * * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. * This is necessary because directory traversal starts at the base directory and goes deeper. */ function convertPatternsToTasks(positive, negative, dynamic) { const tasks = []; const patternsOutsideCurrentDirectory = utils$a.pattern.getPatternsOutsideCurrentDirectory(positive); const patternsInsideCurrentDirectory = utils$a.pattern.getPatternsInsideCurrentDirectory(positive); const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); /* * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. */ if ('.' in insideCurrentDirectoryGroup) { tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); } else { tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); } return tasks; } tasks.convertPatternsToTasks = convertPatternsToTasks; function getPositivePatterns(patterns) { return utils$a.pattern.getPositivePatterns(patterns); } tasks.getPositivePatterns = getPositivePatterns; function getNegativePatternsAsPositive(patterns, ignore) { const negative = utils$a.pattern.getNegativePatterns(patterns).concat(ignore); const positive = negative.map(utils$a.pattern.convertToPositivePattern); return positive; } tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive; function groupPatternsByBaseDirectory(patterns) { const group = {}; return patterns.reduce((collection, pattern) => { const base = utils$a.pattern.getBaseDirectory(pattern); if (base in collection) { collection[base].push(pattern); } else { collection[base] = [pattern]; } return collection; }, group); } tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; function convertPatternGroupsToTasks(positive, negative, dynamic) { return Object.keys(positive).map((base) => { return convertPatternGroupToTask(base, positive[base], negative, dynamic); }); } tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks; function convertPatternGroupToTask(base, positive, negative, dynamic) { return { dynamic, positive, negative, base, patterns: [].concat(positive, negative.map(utils$a.pattern.convertToNegativePattern)) }; } tasks.convertPatternGroupToTask = convertPatternGroupToTask; var async$7 = {}; var async$6 = {}; var out$3 = {}; var async$5 = {}; var async$4 = {}; var out$2 = {}; var async$3 = {}; var out$1 = {}; var async$2 = {}; Object.defineProperty(async$2, "__esModule", { value: true }); async$2.read = void 0; function read$3(path, settings, callback) { settings.fs.lstat(path, (lstatError, lstat) => { if (lstatError !== null) { callFailureCallback$2(callback, lstatError); return; } if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { callSuccessCallback$2(callback, lstat); return; } settings.fs.stat(path, (statError, stat) => { if (statError !== null) { if (settings.throwErrorOnBrokenSymbolicLink) { callFailureCallback$2(callback, statError); return; } callSuccessCallback$2(callback, lstat); return; } if (settings.markSymbolicLink) { stat.isSymbolicLink = () => true; } callSuccessCallback$2(callback, stat); }); }); } async$2.read = read$3; function callFailureCallback$2(callback, error) { callback(error); } function callSuccessCallback$2(callback, result) { callback(null, result); } var sync$8 = {}; Object.defineProperty(sync$8, "__esModule", { value: true }); sync$8.read = void 0; function read$2(path, settings) { const lstat = settings.fs.lstatSync(path); if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { return lstat; } try { const stat = settings.fs.statSync(path); if (settings.markSymbolicLink) { stat.isSymbolicLink = () => true; } return stat; } catch (error) { if (!settings.throwErrorOnBrokenSymbolicLink) { return lstat; } throw error; } } sync$8.read = read$2; var settings$3 = {}; var fs$f = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; const fs = require$$0__default__default; exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, lstatSync: fs.lstatSync, statSync: fs.statSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === undefined) { return exports.FILE_SYSTEM_ADAPTER; } return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } exports.createFileSystemAdapter = createFileSystemAdapter; } (fs$f)); Object.defineProperty(settings$3, "__esModule", { value: true }); const fs$e = fs$f; let Settings$2 = class Settings { constructor(_options = {}) { this._options = _options; this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); this.fs = fs$e.createFileSystemAdapter(this._options.fs); this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } }; settings$3.default = Settings$2; Object.defineProperty(out$1, "__esModule", { value: true }); out$1.statSync = out$1.stat = out$1.Settings = void 0; const async$1 = async$2; const sync$7 = sync$8; const settings_1$3 = settings$3; out$1.Settings = settings_1$3.default; function stat$4(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { async$1.read(path, getSettings$2(), optionsOrSettingsOrCallback); return; } async$1.read(path, getSettings$2(optionsOrSettingsOrCallback), callback); } out$1.stat = stat$4; function statSync(path, optionsOrSettings) { const settings = getSettings$2(optionsOrSettings); return sync$7.read(path, settings); } out$1.statSync = statSync; function getSettings$2(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1$3.default) { return settingsOrOptions; } return new settings_1$3.default(settingsOrOptions); } /*! queue-microtask. MIT License. Feross Aboukhadijeh */ let promise; var queueMicrotask_1 = typeof queueMicrotask === 'function' ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal$1) // reuse resolved promise, and allocate it lazily : cb => (promise || (promise = Promise.resolve())) .then(cb) .catch(err => setTimeout(() => { throw err }, 0)); /*! run-parallel. MIT License. Feross Aboukhadijeh */ var runParallel_1 = runParallel; const queueMicrotask$1 = queueMicrotask_1; function runParallel (tasks, cb) { let results, pending, keys; let isSync = true; if (Array.isArray(tasks)) { results = []; pending = tasks.length; } else { keys = Object.keys(tasks); results = {}; pending = keys.length; } function done (err) { function end () { if (cb) cb(err, results); cb = null; } if (isSync) queueMicrotask$1(end); else end(); } function each (i, err, result) { results[i] = result; if (--pending === 0 || err) { done(err); } } if (!pending) { // empty done(null); } else if (keys) { // object keys.forEach(function (key) { tasks[key](function (err, result) { each(key, err, result); }); }); } else { // array tasks.forEach(function (task, i) { task(function (err, result) { each(i, err, result); }); }); } isSync = false; } var constants$2$1 = {}; Object.defineProperty(constants$2$1, "__esModule", { value: true }); constants$2$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); } const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); const SUPPORTED_MAJOR_VERSION = 10; const SUPPORTED_MINOR_VERSION = 10; const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; /** * IS `true` for Node.js 10.10 and greater. */ constants$2$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; var utils$9 = {}; var fs$d = {}; Object.defineProperty(fs$d, "__esModule", { value: true }); fs$d.createDirentFromStats = void 0; class DirentFromStats { constructor(name, stats) { this.name = name; this.isBlockDevice = stats.isBlockDevice.bind(stats); this.isCharacterDevice = stats.isCharacterDevice.bind(stats); this.isDirectory = stats.isDirectory.bind(stats); this.isFIFO = stats.isFIFO.bind(stats); this.isFile = stats.isFile.bind(stats); this.isSocket = stats.isSocket.bind(stats); this.isSymbolicLink = stats.isSymbolicLink.bind(stats); } } function createDirentFromStats(name, stats) { return new DirentFromStats(name, stats); } fs$d.createDirentFromStats = createDirentFromStats; Object.defineProperty(utils$9, "__esModule", { value: true }); utils$9.fs = void 0; const fs$c = fs$d; utils$9.fs = fs$c; var common$a = {}; Object.defineProperty(common$a, "__esModule", { value: true }); common$a.joinPathSegments = void 0; function joinPathSegments$1(a, b, separator) { /** * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). */ if (a.endsWith(separator)) { return a + b; } return a + separator + b; } common$a.joinPathSegments = joinPathSegments$1; Object.defineProperty(async$3, "__esModule", { value: true }); async$3.readdir = async$3.readdirWithFileTypes = async$3.read = void 0; const fsStat$5 = out$1; const rpl = runParallel_1; const constants_1$1 = constants$2$1; const utils$8 = utils$9; const common$9 = common$a; function read$1(directory, settings, callback) { if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { readdirWithFileTypes$1(directory, settings, callback); return; } readdir$3(directory, settings, callback); } async$3.read = read$1; function readdirWithFileTypes$1(directory, settings, callback) { settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { if (readdirError !== null) { callFailureCallback$1(callback, readdirError); return; } const entries = dirents.map((dirent) => ({ dirent, name: dirent.name, path: common$9.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) })); if (!settings.followSymbolicLinks) { callSuccessCallback$1(callback, entries); return; } const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); rpl(tasks, (rplError, rplEntries) => { if (rplError !== null) { callFailureCallback$1(callback, rplError); return; } callSuccessCallback$1(callback, rplEntries); }); }); } async$3.readdirWithFileTypes = readdirWithFileTypes$1; function makeRplTaskEntry(entry, settings) { return (done) => { if (!entry.dirent.isSymbolicLink()) { done(null, entry); return; } settings.fs.stat(entry.path, (statError, stats) => { if (statError !== null) { if (settings.throwErrorOnBrokenSymbolicLink) { done(statError); return; } done(null, entry); return; } entry.dirent = utils$8.fs.createDirentFromStats(entry.name, stats); done(null, entry); }); }; } function readdir$3(directory, settings, callback) { settings.fs.readdir(directory, (readdirError, names) => { if (readdirError !== null) { callFailureCallback$1(callback, readdirError); return; } const tasks = names.map((name) => { const path = common$9.joinPathSegments(directory, name, settings.pathSegmentSeparator); return (done) => { fsStat$5.stat(path, settings.fsStatSettings, (error, stats) => { if (error !== null) { done(error); return; } const entry = { name, path, dirent: utils$8.fs.createDirentFromStats(name, stats) }; if (settings.stats) { entry.stats = stats; } done(null, entry); }); }; }); rpl(tasks, (rplError, entries) => { if (rplError !== null) { callFailureCallback$1(callback, rplError); return; } callSuccessCallback$1(callback, entries); }); }); } async$3.readdir = readdir$3; function callFailureCallback$1(callback, error) { callback(error); } function callSuccessCallback$1(callback, result) { callback(null, result); } var sync$6 = {}; Object.defineProperty(sync$6, "__esModule", { value: true }); sync$6.readdir = sync$6.readdirWithFileTypes = sync$6.read = void 0; const fsStat$4 = out$1; const constants_1 = constants$2$1; const utils$7 = utils$9; const common$8 = common$a; function read(directory, settings) { if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { return readdirWithFileTypes(directory, settings); } return readdir$2(directory, settings); } sync$6.read = read; function readdirWithFileTypes(directory, settings) { const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); return dirents.map((dirent) => { const entry = { dirent, name: dirent.name, path: common$8.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) }; if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { try { const stats = settings.fs.statSync(entry.path); entry.dirent = utils$7.fs.createDirentFromStats(entry.name, stats); } catch (error) { if (settings.throwErrorOnBrokenSymbolicLink) { throw error; } } } return entry; }); } sync$6.readdirWithFileTypes = readdirWithFileTypes; function readdir$2(directory, settings) { const names = settings.fs.readdirSync(directory); return names.map((name) => { const entryPath = common$8.joinPathSegments(directory, name, settings.pathSegmentSeparator); const stats = fsStat$4.statSync(entryPath, settings.fsStatSettings); const entry = { name, path: entryPath, dirent: utils$7.fs.createDirentFromStats(name, stats) }; if (settings.stats) { entry.stats = stats; } return entry; }); } sync$6.readdir = readdir$2; var settings$2 = {}; var fs$b = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; const fs = require$$0__default__default; exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, lstatSync: fs.lstatSync, statSync: fs.statSync, readdir: fs.readdir, readdirSync: fs.readdirSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === undefined) { return exports.FILE_SYSTEM_ADAPTER; } return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } exports.createFileSystemAdapter = createFileSystemAdapter; } (fs$b)); Object.defineProperty(settings$2, "__esModule", { value: true }); const path$d = require$$0$4; const fsStat$3 = out$1; const fs$a = fs$b; let Settings$1 = class Settings { constructor(_options = {}) { this._options = _options; this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); this.fs = fs$a.createFileSystemAdapter(this._options.fs); this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$d.sep); this.stats = this._getValue(this._options.stats, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); this.fsStatSettings = new fsStat$3.Settings({ followSymbolicLink: this.followSymbolicLinks, fs: this.fs, throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink }); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } }; settings$2.default = Settings$1; Object.defineProperty(out$2, "__esModule", { value: true }); out$2.Settings = out$2.scandirSync = out$2.scandir = void 0; const async = async$3; const sync$5 = sync$6; const settings_1$2 = settings$2; out$2.Settings = settings_1$2.default; function scandir(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { async.read(path, getSettings$1(), optionsOrSettingsOrCallback); return; } async.read(path, getSettings$1(optionsOrSettingsOrCallback), callback); } out$2.scandir = scandir; function scandirSync(path, optionsOrSettings) { const settings = getSettings$1(optionsOrSettings); return sync$5.read(path, settings); } out$2.scandirSync = scandirSync; function getSettings$1(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1$2.default) { return settingsOrOptions; } return new settings_1$2.default(settingsOrOptions); } var queue = {exports: {}}; function reusify$1 (Constructor) { var head = new Constructor(); var tail = head; function get () { var current = head; if (current.next) { head = current.next; } else { head = new Constructor(); tail = head; } current.next = null; return current } function release (obj) { tail.next = obj; tail = obj; } return { get: get, release: release } } var reusify_1 = reusify$1; /* eslint-disable no-var */ var reusify = reusify_1; function fastqueue (context, worker, concurrency) { if (typeof context === 'function') { concurrency = worker; worker = context; context = null; } if (concurrency < 1) { throw new Error('fastqueue concurrency must be greater than 1') } var cache = reusify(Task); var queueHead = null; var queueTail = null; var _running = 0; var errorHandler = null; var self = { push: push, drain: noop$4, saturated: noop$4, pause: pause, paused: false, concurrency: concurrency, running: running, resume: resume, idle: idle, length: length, getQueue: getQueue, unshift: unshift, empty: noop$4, kill: kill, killAndDrain: killAndDrain, error: error }; return self function running () { return _running } function pause () { self.paused = true; } function length () { var current = queueHead; var counter = 0; while (current) { current = current.next; counter++; } return counter } function getQueue () { var current = queueHead; var tasks = []; while (current) { tasks.push(current.value); current = current.next; } return tasks } function resume () { if (!self.paused) return self.paused = false; for (var i = 0; i < self.concurrency; i++) { _running++; release(); } } function idle () { return _running === 0 && self.length() === 0 } function push (value, done) { var current = cache.get(); current.context = context; current.release = release; current.value = value; current.callback = done || noop$4; current.errorHandler = errorHandler; if (_running === self.concurrency || self.paused) { if (queueTail) { queueTail.next = current; queueTail = current; } else { queueHead = current; queueTail = current; self.saturated(); } } else { _running++; worker.call(context, current.value, current.worked); } } function unshift (value, done) { var current = cache.get(); current.context = context; current.release = release; current.value = value; current.callback = done || noop$4; if (_running === self.concurrency || self.paused) { if (queueHead) { current.next = queueHead; queueHead = current; } else { queueHead = current; queueTail = current; self.saturated(); } } else { _running++; worker.call(context, current.value, current.worked); } } function release (holder) { if (holder) { cache.release(holder); } var next = queueHead; if (next) { if (!self.paused) { if (queueTail === queueHead) { queueTail = null; } queueHead = next.next; next.next = null; worker.call(context, next.value, next.worked); if (queueTail === null) { self.empty(); } } else { _running--; } } else if (--_running === 0) { self.drain(); } } function kill () { queueHead = null; queueTail = null; self.drain = noop$4; } function killAndDrain () { queueHead = null; queueTail = null; self.drain(); self.drain = noop$4; } function error (handler) { errorHandler = handler; } } function noop$4 () {} function Task () { this.value = null; this.callback = noop$4; this.next = null; this.release = noop$4; this.context = null; this.errorHandler = null; var self = this; this.worked = function worked (err, result) { var callback = self.callback; var errorHandler = self.errorHandler; var val = self.value; self.value = null; self.callback = noop$4; if (self.errorHandler) { errorHandler(err, val); } callback.call(self.context, err, result); self.release(self); }; } function queueAsPromised (context, worker, concurrency) { if (typeof context === 'function') { concurrency = worker; worker = context; context = null; } function asyncWrapper (arg, cb) { worker.call(this, arg) .then(function (res) { cb(null, res); }, cb); } var queue = fastqueue(context, asyncWrapper, concurrency); var pushCb = queue.push; var unshiftCb = queue.unshift; queue.push = push; queue.unshift = unshift; queue.drained = drained; return queue function push (value) { var p = new Promise(function (resolve, reject) { pushCb(value, function (err, result) { if (err) { reject(err); return } resolve(result); }); }); // Let's fork the promise chain to // make the error bubble up to the user but // not lead to a unhandledRejection p.catch(noop$4); return p } function unshift (value) { var p = new Promise(function (resolve, reject) { unshiftCb(value, function (err, result) { if (err) { reject(err); return } resolve(result); }); }); // Let's fork the promise chain to // make the error bubble up to the user but // not lead to a unhandledRejection p.catch(noop$4); return p } function drained () { var previousDrain = queue.drain; var p = new Promise(function (resolve) { queue.drain = function () { previousDrain(); resolve(); }; }); return p } } queue.exports = fastqueue; queue.exports.promise = queueAsPromised; var queueExports = queue.exports; var common$7 = {}; Object.defineProperty(common$7, "__esModule", { value: true }); common$7.joinPathSegments = common$7.replacePathSegmentSeparator = common$7.isAppliedFilter = common$7.isFatalError = void 0; function isFatalError(settings, error) { if (settings.errorFilter === null) { return true; } return !settings.errorFilter(error); } common$7.isFatalError = isFatalError; function isAppliedFilter(filter, value) { return filter === null || filter(value); } common$7.isAppliedFilter = isAppliedFilter; function replacePathSegmentSeparator(filepath, separator) { return filepath.split(/[/\\]/).join(separator); } common$7.replacePathSegmentSeparator = replacePathSegmentSeparator; function joinPathSegments(a, b, separator) { if (a === '') { return b; } /** * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). */ if (a.endsWith(separator)) { return a + b; } return a + separator + b; } common$7.joinPathSegments = joinPathSegments; var reader$1 = {}; Object.defineProperty(reader$1, "__esModule", { value: true }); const common$6 = common$7; let Reader$1 = class Reader { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._root = common$6.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); } }; reader$1.default = Reader$1; Object.defineProperty(async$4, "__esModule", { value: true }); const events_1 = require$$0$5; const fsScandir$2 = out$2; const fastq = queueExports; const common$5 = common$7; const reader_1$4 = reader$1; class AsyncReader extends reader_1$4.default { constructor(_root, _settings) { super(_root, _settings); this._settings = _settings; this._scandir = fsScandir$2.scandir; this._emitter = new events_1.EventEmitter(); this._queue = fastq(this._worker.bind(this), this._settings.concurrency); this._isFatalError = false; this._isDestroyed = false; this._queue.drain = () => { if (!this._isFatalError) { this._emitter.emit('end'); } }; } read() { this._isFatalError = false; this._isDestroyed = false; setImmediate(() => { this._pushToQueue(this._root, this._settings.basePath); }); return this._emitter; } get isDestroyed() { return this._isDestroyed; } destroy() { if (this._isDestroyed) { throw new Error('The reader is already destroyed'); } this._isDestroyed = true; this._queue.killAndDrain(); } onEntry(callback) { this._emitter.on('entry', callback); } onError(callback) { this._emitter.once('error', callback); } onEnd(callback) { this._emitter.once('end', callback); } _pushToQueue(directory, base) { const queueItem = { directory, base }; this._queue.push(queueItem, (error) => { if (error !== null) { this._handleError(error); } }); } _worker(item, done) { this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { if (error !== null) { done(error, undefined); return; } for (const entry of entries) { this._handleEntry(entry, item.base); } done(null, undefined); }); } _handleError(error) { if (this._isDestroyed || !common$5.isFatalError(this._settings, error)) { return; } this._isFatalError = true; this._isDestroyed = true; this._emitter.emit('error', error); } _handleEntry(entry, base) { if (this._isDestroyed || this._isFatalError) { return; } const fullpath = entry.path; if (base !== undefined) { entry.path = common$5.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } if (common$5.isAppliedFilter(this._settings.entryFilter, entry)) { this._emitEntry(entry); } if (entry.dirent.isDirectory() && common$5.isAppliedFilter(this._settings.deepFilter, entry)) { this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } } _emitEntry(entry) { this._emitter.emit('entry', entry); } } async$4.default = AsyncReader; Object.defineProperty(async$5, "__esModule", { value: true }); const async_1$4 = async$4; class AsyncProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new async_1$4.default(this._root, this._settings); this._storage = []; } read(callback) { this._reader.onError((error) => { callFailureCallback(callback, error); }); this._reader.onEntry((entry) => { this._storage.push(entry); }); this._reader.onEnd(() => { callSuccessCallback(callback, this._storage); }); this._reader.read(); } } async$5.default = AsyncProvider; function callFailureCallback(callback, error) { callback(error); } function callSuccessCallback(callback, entries) { callback(null, entries); } var stream$2 = {}; Object.defineProperty(stream$2, "__esModule", { value: true }); const stream_1$5 = require$$0$7; const async_1$3 = async$4; class StreamProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new async_1$3.default(this._root, this._settings); this._stream = new stream_1$5.Readable({ objectMode: true, read: () => { }, destroy: () => { if (!this._reader.isDestroyed) { this._reader.destroy(); } } }); } read() { this._reader.onError((error) => { this._stream.emit('error', error); }); this._reader.onEntry((entry) => { this._stream.push(entry); }); this._reader.onEnd(() => { this._stream.push(null); }); this._reader.read(); return this._stream; } } stream$2.default = StreamProvider; var sync$4 = {}; var sync$3 = {}; Object.defineProperty(sync$3, "__esModule", { value: true }); const fsScandir$1 = out$2; const common$4 = common$7; const reader_1$3 = reader$1; class SyncReader extends reader_1$3.default { constructor() { super(...arguments); this._scandir = fsScandir$1.scandirSync; this._storage = []; this._queue = new Set(); } read() { this._pushToQueue(this._root, this._settings.basePath); this._handleQueue(); return this._storage; } _pushToQueue(directory, base) { this._queue.add({ directory, base }); } _handleQueue() { for (const item of this._queue.values()) { this._handleDirectory(item.directory, item.base); } } _handleDirectory(directory, base) { try { const entries = this._scandir(directory, this._settings.fsScandirSettings); for (const entry of entries) { this._handleEntry(entry, base); } } catch (error) { this._handleError(error); } } _handleError(error) { if (!common$4.isFatalError(this._settings, error)) { return; } throw error; } _handleEntry(entry, base) { const fullpath = entry.path; if (base !== undefined) { entry.path = common$4.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } if (common$4.isAppliedFilter(this._settings.entryFilter, entry)) { this._pushToStorage(entry); } if (entry.dirent.isDirectory() && common$4.isAppliedFilter(this._settings.deepFilter, entry)) { this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } } _pushToStorage(entry) { this._storage.push(entry); } } sync$3.default = SyncReader; Object.defineProperty(sync$4, "__esModule", { value: true }); const sync_1$3 = sync$3; class SyncProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new sync_1$3.default(this._root, this._settings); } read() { return this._reader.read(); } } sync$4.default = SyncProvider; var settings$1 = {}; Object.defineProperty(settings$1, "__esModule", { value: true }); const path$c = require$$0$4; const fsScandir = out$2; class Settings { constructor(_options = {}) { this._options = _options; this.basePath = this._getValue(this._options.basePath, undefined); this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); this.deepFilter = this._getValue(this._options.deepFilter, null); this.entryFilter = this._getValue(this._options.entryFilter, null); this.errorFilter = this._getValue(this._options.errorFilter, null); this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$c.sep); this.fsScandirSettings = new fsScandir.Settings({ followSymbolicLinks: this._options.followSymbolicLinks, fs: this._options.fs, pathSegmentSeparator: this._options.pathSegmentSeparator, stats: this._options.stats, throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink }); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } } settings$1.default = Settings; Object.defineProperty(out$3, "__esModule", { value: true }); out$3.Settings = out$3.walkStream = out$3.walkSync = out$3.walk = void 0; const async_1$2 = async$5; const stream_1$4 = stream$2; const sync_1$2 = sync$4; const settings_1$1 = settings$1; out$3.Settings = settings_1$1.default; function walk$2(directory, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { new async_1$2.default(directory, getSettings()).read(optionsOrSettingsOrCallback); return; } new async_1$2.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); } out$3.walk = walk$2; function walkSync(directory, optionsOrSettings) { const settings = getSettings(optionsOrSettings); const provider = new sync_1$2.default(directory, settings); return provider.read(); } out$3.walkSync = walkSync; function walkStream(directory, optionsOrSettings) { const settings = getSettings(optionsOrSettings); const provider = new stream_1$4.default(directory, settings); return provider.read(); } out$3.walkStream = walkStream; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1$1.default) { return settingsOrOptions; } return new settings_1$1.default(settingsOrOptions); } var reader = {}; Object.defineProperty(reader, "__esModule", { value: true }); const path$b = require$$0$4; const fsStat$2 = out$1; const utils$6 = utils$g; class Reader { constructor(_settings) { this._settings = _settings; this._fsStatSettings = new fsStat$2.Settings({ followSymbolicLink: this._settings.followSymbolicLinks, fs: this._settings.fs, throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks }); } _getFullEntryPath(filepath) { return path$b.resolve(this._settings.cwd, filepath); } _makeEntry(stats, pattern) { const entry = { name: pattern, path: pattern, dirent: utils$6.fs.createDirentFromStats(pattern, stats) }; if (this._settings.stats) { entry.stats = stats; } return entry; } _isFatalError(error) { return !utils$6.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; } } reader.default = Reader; var stream$1 = {}; Object.defineProperty(stream$1, "__esModule", { value: true }); const stream_1$3 = require$$0$7; const fsStat$1 = out$1; const fsWalk$2 = out$3; const reader_1$2 = reader; class ReaderStream extends reader_1$2.default { constructor() { super(...arguments); this._walkStream = fsWalk$2.walkStream; this._stat = fsStat$1.stat; } dynamic(root, options) { return this._walkStream(root, options); } static(patterns, options) { const filepaths = patterns.map(this._getFullEntryPath, this); const stream = new stream_1$3.PassThrough({ objectMode: true }); stream._write = (index, _enc, done) => { return this._getEntry(filepaths[index], patterns[index], options) .then((entry) => { if (entry !== null && options.entryFilter(entry)) { stream.push(entry); } if (index === filepaths.length - 1) { stream.end(); } done(); }) .catch(done); }; for (let i = 0; i < filepaths.length; i++) { stream.write(i); } return stream; } _getEntry(filepath, pattern, options) { return this._getStat(filepath) .then((stats) => this._makeEntry(stats, pattern)) .catch((error) => { if (options.errorFilter(error)) { return null; } throw error; }); } _getStat(filepath) { return new Promise((resolve, reject) => { this._stat(filepath, this._fsStatSettings, (error, stats) => { return error === null ? resolve(stats) : reject(error); }); }); } } stream$1.default = ReaderStream; Object.defineProperty(async$6, "__esModule", { value: true }); const fsWalk$1 = out$3; const reader_1$1 = reader; const stream_1$2 = stream$1; class ReaderAsync extends reader_1$1.default { constructor() { super(...arguments); this._walkAsync = fsWalk$1.walk; this._readerStream = new stream_1$2.default(this._settings); } dynamic(root, options) { return new Promise((resolve, reject) => { this._walkAsync(root, options, (error, entries) => { if (error === null) { resolve(entries); } else { reject(error); } }); }); } async static(patterns, options) { const entries = []; const stream = this._readerStream.static(patterns, options); // After #235, replace it with an asynchronous iterator. return new Promise((resolve, reject) => { stream.once('error', reject); stream.on('data', (entry) => entries.push(entry)); stream.once('end', () => resolve(entries)); }); } } async$6.default = ReaderAsync; var provider = {}; var deep = {}; var partial = {}; var matcher = {}; Object.defineProperty(matcher, "__esModule", { value: true }); const utils$5 = utils$g; class Matcher { constructor(_patterns, _settings, _micromatchOptions) { this._patterns = _patterns; this._settings = _settings; this._micromatchOptions = _micromatchOptions; this._storage = []; this._fillStorage(); } _fillStorage() { for (const pattern of this._patterns) { const segments = this._getPatternSegments(pattern); const sections = this._splitSegmentsIntoSections(segments); this._storage.push({ complete: sections.length <= 1, pattern, segments, sections }); } } _getPatternSegments(pattern) { const parts = utils$5.pattern.getPatternParts(pattern, this._micromatchOptions); return parts.map((part) => { const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings); if (!dynamic) { return { dynamic: false, pattern: part }; } return { dynamic: true, pattern: part, patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions) }; }); } _splitSegmentsIntoSections(segments) { return utils$5.array.splitWhen(segments, (segment) => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern)); } } matcher.default = Matcher; Object.defineProperty(partial, "__esModule", { value: true }); const matcher_1 = matcher; class PartialMatcher extends matcher_1.default { match(filepath) { const parts = filepath.split('/'); const levels = parts.length; const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); for (const pattern of patterns) { const section = pattern.sections[0]; /** * In this case, the pattern has a globstar and we must read all directories unconditionally, * but only if the level has reached the end of the first group. * * fixtures/{a,b}/** * ^ true/false ^ always true */ if (!pattern.complete && levels > section.length) { return true; } const match = parts.every((part, index) => { const segment = pattern.segments[index]; if (segment.dynamic && segment.patternRe.test(part)) { return true; } if (!segment.dynamic && segment.pattern === part) { return true; } return false; }); if (match) { return true; } } return false; } } partial.default = PartialMatcher; Object.defineProperty(deep, "__esModule", { value: true }); const utils$4 = utils$g; const partial_1 = partial; class DeepFilter { constructor(_settings, _micromatchOptions) { this._settings = _settings; this._micromatchOptions = _micromatchOptions; } getFilter(basePath, positive, negative) { const matcher = this._getMatcher(positive); const negativeRe = this._getNegativePatternsRe(negative); return (entry) => this._filter(basePath, entry, matcher, negativeRe); } _getMatcher(patterns) { return new partial_1.default(patterns, this._settings, this._micromatchOptions); } _getNegativePatternsRe(patterns) { const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern); return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); } _filter(basePath, entry, matcher, negativeRe) { if (this._isSkippedByDeep(basePath, entry.path)) { return false; } if (this._isSkippedSymbolicLink(entry)) { return false; } const filepath = utils$4.path.removeLeadingDotSegment(entry.path); if (this._isSkippedByPositivePatterns(filepath, matcher)) { return false; } return this._isSkippedByNegativePatterns(filepath, negativeRe); } _isSkippedByDeep(basePath, entryPath) { /** * Avoid unnecessary depth calculations when it doesn't matter. */ if (this._settings.deep === Infinity) { return false; } return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; } _getEntryLevel(basePath, entryPath) { const entryPathDepth = entryPath.split('/').length; if (basePath === '') { return entryPathDepth; } const basePathDepth = basePath.split('/').length; return entryPathDepth - basePathDepth; } _isSkippedSymbolicLink(entry) { return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); } _isSkippedByPositivePatterns(entryPath, matcher) { return !this._settings.baseNameMatch && !matcher.match(entryPath); } _isSkippedByNegativePatterns(entryPath, patternsRe) { return !utils$4.pattern.matchAny(entryPath, patternsRe); } } deep.default = DeepFilter; var entry$1 = {}; Object.defineProperty(entry$1, "__esModule", { value: true }); const utils$3$1 = utils$g; class EntryFilter { constructor(_settings, _micromatchOptions) { this._settings = _settings; this._micromatchOptions = _micromatchOptions; this.index = new Map(); } getFilter(positive, negative) { const positiveRe = utils$3$1.pattern.convertPatternsToRe(positive, this._micromatchOptions); const negativeRe = utils$3$1.pattern.convertPatternsToRe(negative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })); return (entry) => this._filter(entry, positiveRe, negativeRe); } _filter(entry, positiveRe, negativeRe) { const filepath = utils$3$1.path.removeLeadingDotSegment(entry.path); if (this._settings.unique && this._isDuplicateEntry(filepath)) { return false; } if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { return false; } if (this._isSkippedByAbsoluteNegativePatterns(filepath, negativeRe)) { return false; } const isDirectory = entry.dirent.isDirectory(); const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(filepath, negativeRe, isDirectory); if (this._settings.unique && isMatched) { this._createIndexRecord(filepath); } return isMatched; } _isDuplicateEntry(filepath) { return this.index.has(filepath); } _createIndexRecord(filepath) { this.index.set(filepath, undefined); } _onlyFileFilter(entry) { return this._settings.onlyFiles && !entry.dirent.isFile(); } _onlyDirectoryFilter(entry) { return this._settings.onlyDirectories && !entry.dirent.isDirectory(); } _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { if (!this._settings.absolute) { return false; } const fullpath = utils$3$1.path.makeAbsolute(this._settings.cwd, entryPath); return utils$3$1.pattern.matchAny(fullpath, patternsRe); } _isMatchToPatterns(filepath, patternsRe, isDirectory) { // Trying to match files and directories by patterns. const isMatched = utils$3$1.pattern.matchAny(filepath, patternsRe); // A pattern with a trailling slash can be used for directory matching. // To apply such pattern, we need to add a tralling slash to the path. if (!isMatched && isDirectory) { return utils$3$1.pattern.matchAny(filepath + '/', patternsRe); } return isMatched; } } entry$1.default = EntryFilter; var error$2 = {}; Object.defineProperty(error$2, "__esModule", { value: true }); const utils$2$1 = utils$g; class ErrorFilter { constructor(_settings) { this._settings = _settings; } getFilter() { return (error) => this._isNonFatalError(error); } _isNonFatalError(error) { return utils$2$1.errno.isEnoentCodeError(error) || this._settings.suppressErrors; } } error$2.default = ErrorFilter; var entry = {}; Object.defineProperty(entry, "__esModule", { value: true }); const utils$1$1 = utils$g; class EntryTransformer { constructor(_settings) { this._settings = _settings; } getTransformer() { return (entry) => this._transform(entry); } _transform(entry) { let filepath = entry.path; if (this._settings.absolute) { filepath = utils$1$1.path.makeAbsolute(this._settings.cwd, filepath); filepath = utils$1$1.path.unixify(filepath); } if (this._settings.markDirectories && entry.dirent.isDirectory()) { filepath += '/'; } if (!this._settings.objectMode) { return filepath; } return Object.assign(Object.assign({}, entry), { path: filepath }); } } entry.default = EntryTransformer; Object.defineProperty(provider, "__esModule", { value: true }); const path$a = require$$0$4; const deep_1 = deep; const entry_1 = entry$1; const error_1 = error$2; const entry_2 = entry; class Provider { constructor(_settings) { this._settings = _settings; this.errorFilter = new error_1.default(this._settings); this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); this.entryTransformer = new entry_2.default(this._settings); } _getRootDirectory(task) { return path$a.resolve(this._settings.cwd, task.base); } _getReaderOptions(task) { const basePath = task.base === '.' ? '' : task.base; return { basePath, pathSegmentSeparator: '/', concurrency: this._settings.concurrency, deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), entryFilter: this.entryFilter.getFilter(task.positive, task.negative), errorFilter: this.errorFilter.getFilter(), followSymbolicLinks: this._settings.followSymbolicLinks, fs: this._settings.fs, stats: this._settings.stats, throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, transform: this.entryTransformer.getTransformer() }; } _getMicromatchOptions() { return { dot: this._settings.dot, matchBase: this._settings.baseNameMatch, nobrace: !this._settings.braceExpansion, nocase: !this._settings.caseSensitiveMatch, noext: !this._settings.extglob, noglobstar: !this._settings.globstar, posix: true, strictSlashes: false }; } } provider.default = Provider; Object.defineProperty(async$7, "__esModule", { value: true }); const async_1$1 = async$6; const provider_1$2 = provider; class ProviderAsync extends provider_1$2.default { constructor() { super(...arguments); this._reader = new async_1$1.default(this._settings); } async read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const entries = await this.api(root, task, options); return entries.map((entry) => options.transform(entry)); } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } async$7.default = ProviderAsync; var stream = {}; Object.defineProperty(stream, "__esModule", { value: true }); const stream_1$1 = require$$0$7; const stream_2 = stream$1; const provider_1$1 = provider; class ProviderStream extends provider_1$1.default { constructor() { super(...arguments); this._reader = new stream_2.default(this._settings); } read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const source = this.api(root, task, options); const destination = new stream_1$1.Readable({ objectMode: true, read: () => { } }); source .once('error', (error) => destination.emit('error', error)) .on('data', (entry) => destination.emit('data', options.transform(entry))) .once('end', () => destination.emit('end')); destination .once('close', () => source.destroy()); return destination; } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } stream.default = ProviderStream; var sync$2$1 = {}; var sync$1$1 = {}; Object.defineProperty(sync$1$1, "__esModule", { value: true }); const fsStat = out$1; const fsWalk = out$3; const reader_1 = reader; class ReaderSync extends reader_1.default { constructor() { super(...arguments); this._walkSync = fsWalk.walkSync; this._statSync = fsStat.statSync; } dynamic(root, options) { return this._walkSync(root, options); } static(patterns, options) { const entries = []; for (const pattern of patterns) { const filepath = this._getFullEntryPath(pattern); const entry = this._getEntry(filepath, pattern, options); if (entry === null || !options.entryFilter(entry)) { continue; } entries.push(entry); } return entries; } _getEntry(filepath, pattern, options) { try { const stats = this._getStat(filepath); return this._makeEntry(stats, pattern); } catch (error) { if (options.errorFilter(error)) { return null; } throw error; } } _getStat(filepath) { return this._statSync(filepath, this._fsStatSettings); } } sync$1$1.default = ReaderSync; Object.defineProperty(sync$2$1, "__esModule", { value: true }); const sync_1$1 = sync$1$1; const provider_1 = provider; class ProviderSync extends provider_1.default { constructor() { super(...arguments); this._reader = new sync_1$1.default(this._settings); } read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const entries = this.api(root, task, options); return entries.map(options.transform); } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } sync$2$1.default = ProviderSync; var settings = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; const fs = require$$0__default__default; const os = require$$2$1; /** * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 */ const CPU_COUNT = Math.max(os.cpus().length, 1); exports.DEFAULT_FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, lstatSync: fs.lstatSync, stat: fs.stat, statSync: fs.statSync, readdir: fs.readdir, readdirSync: fs.readdirSync }; class Settings { constructor(_options = {}) { this._options = _options; this.absolute = this._getValue(this._options.absolute, false); this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); this.braceExpansion = this._getValue(this._options.braceExpansion, true); this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); this.cwd = this._getValue(this._options.cwd, process.cwd()); this.deep = this._getValue(this._options.deep, Infinity); this.dot = this._getValue(this._options.dot, false); this.extglob = this._getValue(this._options.extglob, true); this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); this.fs = this._getFileSystemMethods(this._options.fs); this.globstar = this._getValue(this._options.globstar, true); this.ignore = this._getValue(this._options.ignore, []); this.markDirectories = this._getValue(this._options.markDirectories, false); this.objectMode = this._getValue(this._options.objectMode, false); this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); this.onlyFiles = this._getValue(this._options.onlyFiles, true); this.stats = this._getValue(this._options.stats, false); this.suppressErrors = this._getValue(this._options.suppressErrors, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); this.unique = this._getValue(this._options.unique, true); if (this.onlyDirectories) { this.onlyFiles = false; } if (this.stats) { this.objectMode = true; } // Remove the cast to the array in the next major (#404). this.ignore = [].concat(this.ignore); } _getValue(option, value) { return option === undefined ? value : option; } _getFileSystemMethods(methods = {}) { return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); } } exports.default = Settings; } (settings)); const taskManager = tasks; const async_1 = async$7; const stream_1 = stream; const sync_1 = sync$2$1; const settings_1 = settings; const utils$l = utils$g; async function FastGlob(source, options) { assertPatternsInput(source); const works = getWorks(source, async_1.default, options); const result = await Promise.all(works); return utils$l.array.flatten(result); } // https://github.com/typescript-eslint/typescript-eslint/issues/60 // eslint-disable-next-line no-redeclare (function (FastGlob) { FastGlob.glob = FastGlob; FastGlob.globSync = sync; FastGlob.globStream = stream; FastGlob.async = FastGlob; function sync(source, options) { assertPatternsInput(source); const works = getWorks(source, sync_1.default, options); return utils$l.array.flatten(works); } FastGlob.sync = sync; function stream(source, options) { assertPatternsInput(source); const works = getWorks(source, stream_1.default, options); /** * The stream returned by the provider cannot work with an asynchronous iterator. * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. * This affects performance (+25%). I don't see best solution right now. */ return utils$l.stream.merge(works); } FastGlob.stream = stream; function generateTasks(source, options) { assertPatternsInput(source); const patterns = [].concat(source); const settings = new settings_1.default(options); return taskManager.generate(patterns, settings); } FastGlob.generateTasks = generateTasks; function isDynamicPattern(source, options) { assertPatternsInput(source); const settings = new settings_1.default(options); return utils$l.pattern.isDynamicPattern(source, settings); } FastGlob.isDynamicPattern = isDynamicPattern; function escapePath(source) { assertPatternsInput(source); return utils$l.path.escape(source); } FastGlob.escapePath = escapePath; function convertPathToPattern(source) { assertPatternsInput(source); return utils$l.path.convertPathToPattern(source); } FastGlob.convertPathToPattern = convertPathToPattern; (function (posix) { function escapePath(source) { assertPatternsInput(source); return utils$l.path.escapePosixPath(source); } posix.escapePath = escapePath; function convertPathToPattern(source) { assertPatternsInput(source); return utils$l.path.convertPosixPathToPattern(source); } posix.convertPathToPattern = convertPathToPattern; })(FastGlob.posix || (FastGlob.posix = {})); (function (win32) { function escapePath(source) { assertPatternsInput(source); return utils$l.path.escapeWindowsPath(source); } win32.escapePath = escapePath; function convertPathToPattern(source) { assertPatternsInput(source); return utils$l.path.convertWindowsPathToPattern(source); } win32.convertPathToPattern = convertPathToPattern; })(FastGlob.win32 || (FastGlob.win32 = {})); })(FastGlob || (FastGlob = {})); function getWorks(source, _Provider, options) { const patterns = [].concat(source); const settings = new settings_1.default(options); const tasks = taskManager.generate(patterns, settings); const provider = new _Provider(settings); return tasks.map(provider.read, provider); } function assertPatternsInput(input) { const source = [].concat(input); const isValidSource = source.every((item) => utils$l.string.isString(item) && !utils$l.string.isEmpty(item)); if (!isValidSource) { throw new TypeError('Patterns must be a string (non empty) or an array of strings'); } } // This file was generated. Do not modify manually! var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 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, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 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, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; // This file was generated. Do not modify manually! 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, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 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, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 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, 20, 1, 64, 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, 38, 6, 186, 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, 19, 72, 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, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 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, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 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, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 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, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191]; // This file was generated. Do not modify manually! 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\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\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\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\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-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\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-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; // This file was generated. Do not modify manually! 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\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\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\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\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-\u1b4c\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-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; // 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. // Reserved word lists for various dialects of the language var reservedWords$2 = { 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", 5: "class enum extends super const export import", 6: "enum", strict: "implements interface let package private protected public static yield", strictBind: "eval arguments" }; // And the keywords var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; var keywords$1 = { 5: ecma5AndLessKeywords, "5module": ecma5AndLessKeywords + " export import", 6: ecma5AndLessKeywords + " const class extends export import super" }; var keywordRelationalOperator = /^in(stanceof)?$/; // ## Character categories var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); // 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 } } return false } // Test whether a given character code starts an identifier. function isIdentifierStart(code, astral) { if (code < 65) { return code === 36 } if (code < 91) { return true } if (code < 97) { return code === 95 } if (code < 123) { return true } if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet(code, astralIdentifierStartCodes) } // Test whether a given character is part of an identifier. function isIdentifierChar(code, astral) { if (code < 48) { return code === 36 } if (code < 58) { return true } if (code < 65) { return false } if (code < 91) { return true } if (code < 97) { return code === 95 } if (code < 123) { return true } if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) } // ## Token types // The assignment of fine-grained, information-carrying type objects // allows the tokenizer to store the information it has about a // token in a way that is very cheap for the parser to look up. // All token type variables start with an underscore, to make them // easy to recognize. // The `beforeExpr` property is used to disambiguate between regular // expressions and divisions. It is set on all token types that can // be followed by an expression (thus, a slash after them would be a // regular expression). // // The `startsExpr` property is used to check if the token ends a // `yield` expression. It is set on all token types that either can // directly start an expression (like a quotation mark) or can // continue an expression (like the body of a string). // // `isLoop` marks a keyword as starting a loop, which is important // to know when parsing a label, in order to allow or disallow // continue jumps to that label. var TokenType$1 = function TokenType(label, conf) { if ( conf === void 0 ) conf = {}; this.label = label; this.keyword = conf.keyword; this.beforeExpr = !!conf.beforeExpr; this.startsExpr = !!conf.startsExpr; this.isLoop = !!conf.isLoop; this.isAssign = !!conf.isAssign; this.prefix = !!conf.prefix; this.postfix = !!conf.postfix; this.binop = conf.binop || null; this.updateContext = null; }; function binop(name, prec) { return new TokenType$1(name, {beforeExpr: true, binop: prec}) } var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; // Map keyword names to token types. var keywords$2 = {}; // Succinct definitions of keyword token types function kw(name, options) { if ( options === void 0 ) options = {}; options.keyword = name; return keywords$2[name] = new TokenType$1(name, options) } var types$1 = { num: new TokenType$1("num", startsExpr), regexp: new TokenType$1("regexp", startsExpr), string: new TokenType$1("string", startsExpr), name: new TokenType$1("name", startsExpr), privateId: new TokenType$1("privateId", startsExpr), eof: new TokenType$1("eof"), // Punctuation token types. bracketL: new TokenType$1("[", {beforeExpr: true, startsExpr: true}), bracketR: new TokenType$1("]"), braceL: new TokenType$1("{", {beforeExpr: true, startsExpr: true}), braceR: new TokenType$1("}"), parenL: new TokenType$1("(", {beforeExpr: true, startsExpr: true}), parenR: new TokenType$1(")"), comma: new TokenType$1(",", beforeExpr), semi: new TokenType$1(";", beforeExpr), colon: new TokenType$1(":", beforeExpr), dot: new TokenType$1("."), question: new TokenType$1("?", beforeExpr), questionDot: new TokenType$1("?."), arrow: new TokenType$1("=>", beforeExpr), template: new TokenType$1("template"), invalidTemplate: new TokenType$1("invalidTemplate"), ellipsis: new TokenType$1("...", beforeExpr), backQuote: new TokenType$1("`", startsExpr), dollarBraceL: new TokenType$1("${", {beforeExpr: true, startsExpr: true}), // Operators. These carry several kinds of properties to help the // parser use them properly (the presence of these properties is // what categorizes them as operators). // // `binop`, when present, specifies that this operator is a binary // operator, and will refer to its precedence. // // `prefix` and `postfix` mark the operator as a prefix or postfix // unary operator. // // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as // binary operators with a very low precedence, that should result // in AssignmentExpression nodes. eq: new TokenType$1("=", {beforeExpr: true, isAssign: true}), assign: new TokenType$1("_=", {beforeExpr: true, isAssign: true}), incDec: new TokenType$1("++/--", {prefix: true, postfix: true, startsExpr: true}), prefix: new TokenType$1("!/~", {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$1("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), modulo: binop("%", 10), star: binop("*", 10), slash: binop("/", 10), starstar: new TokenType$1("**", {beforeExpr: true}), coalesce: binop("??", 1), // Keyword token types. _break: kw("break"), _case: kw("case", beforeExpr), _catch: kw("catch"), _continue: kw("continue"), _debugger: kw("debugger"), _default: kw("default", beforeExpr), _do: kw("do", {isLoop: true, beforeExpr: true}), _else: kw("else", beforeExpr), _finally: kw("finally"), _for: kw("for", {isLoop: true}), _function: kw("function", startsExpr), _if: kw("if"), _return: kw("return", beforeExpr), _switch: kw("switch"), _throw: kw("throw", beforeExpr), _try: kw("try"), _var: kw("var"), _const: kw("const"), _while: kw("while", {isLoop: true}), _with: kw("with"), _new: kw("new", {beforeExpr: true, startsExpr: true}), _this: kw("this", startsExpr), _super: kw("super", startsExpr), _class: kw("class", startsExpr), _extends: kw("extends", beforeExpr), _export: kw("export"), _import: kw("import", startsExpr), _null: kw("null", startsExpr), _true: kw("true", startsExpr), _false: kw("false", startsExpr), _in: kw("in", {beforeExpr: true, binop: 7}), _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) }; // Matches a whole line break (where CRLF is considered a single // line break). Used to count lines. var lineBreak = /\r\n?|\n|\u2028|\u2029/; var lineBreakG = new RegExp(lineBreak.source, "g"); function isNewLine(code) { return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 } function nextLineBreak(code, from, end) { if ( end === void 0 ) end = code.length; for (var i = from; i < end; i++) { var next = code.charCodeAt(i); if (isNewLine(next)) { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 } } return -1 } var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; var skipWhiteSpace$1 = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; var ref = Object.prototype; var hasOwnProperty$1 = ref.hasOwnProperty; var toString$1 = ref.toString; var hasOwn = Object.hasOwn || (function (obj, propName) { return ( hasOwnProperty$1.call(obj, propName) ); }); var isArray$1 = Array.isArray || (function (obj) { return ( toString$1.call(obj) === "[object Array]" ); }); function wordsRegexp(words) { return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") } function codePointToString(code) { // UTF-16 Decoding if (code <= 0xFFFF) { return String.fromCharCode(code) } code -= 0x10000; return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) } var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; // These are used when `options.locations` is on, for the // `startLoc` and `endLoc` properties. var Position = function Position(line, col) { this.line = line; this.column = col; }; Position.prototype.offset = function offset (n) { return new Position(this.line, this.column + n) }; var SourceLocation = function SourceLocation(p, start, end) { this.start = start; this.end = end; if (p.sourceFile !== null) { this.source = p.sourceFile; } }; // The `getLineInfo` function is mostly useful when the // `locations` option is off (for performance reasons) and you // want to find the line/column position for a given character // offset. `input` should be the code string that the offset refers // into. function getLineInfo(input, offset) { for (var line = 1, cur = 0;;) { var nextBreak = nextLineBreak(input, cur, offset); if (nextBreak < 0) { return new Position(line, offset - cur) } ++line; cur = nextBreak; } } // A second argument must be given to configure the parser process. // These options are recognized (only `ecmaVersion` is required): var defaultOptions = { // `ecmaVersion` indicates the ECMAScript version to parse. Must be // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` // (the latest version the library supports). This influences // support for strict mode, the set of reserved words, and support // for new syntax features. ecmaVersion: null, // `sourceType` indicates the mode the code should be parsed in. // Can be either `"script"` or `"module"`. This influences global // strict mode and parsing of `import` and `export` declarations. sourceType: "script", // `onInsertedSemicolon` can be a callback that will be called // when a semicolon is automatically inserted. It will be passed // the position of the comma as an offset, and if `locations` is // enabled, it is given the location as a `{line, column}` object // as second argument. onInsertedSemicolon: null, // `onTrailingComma` is similar to `onInsertedSemicolon`, but for // trailing commas. onTrailingComma: null, // By default, reserved words are only enforced if ecmaVersion >= 5. // Set `allowReserved` to a boolean value to explicitly turn this on // an off. When this option has the value "never", reserved words // and keywords can also not be used as property names. allowReserved: null, // When enabled, a return at the top level is not considered an // error. allowReturnOutsideFunction: false, // When enabled, import/export statements are not constrained to // appearing at the top of the program, and an import.meta expression // in a script isn't considered an error. allowImportExportEverywhere: false, // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. // When enabled, await identifiers are allowed to appear at the top-level scope, // but they are still not allowed in non-async functions. allowAwaitOutsideFunction: null, // When enabled, super identifiers are not constrained to // appearing in methods and do not raise an error when they appear elsewhere. allowSuperOutsideMethod: null, // When enabled, hashbang directive in the beginning of file is // allowed and treated as a line comment. Enabled by default when // `ecmaVersion` >= 2023. allowHashBang: false, // By default, the parser will verify that private properties are // only used in places where they are valid and have been declared. // Set this to false to turn such checks off. checkPrivateFields: true, // When `locations` is on, `loc` properties holding objects with // `start` and `end` properties in `{line, column}` form (with // line being 1-based and column 0-based) will be attached to the // nodes. locations: false, // A function can be passed as `onToken` option, which will // cause Acorn to call that function with object in the same // format as tokens returned from `tokenizer().getToken()`. Note // that you are not allowed to call the parser from the // callback—that will corrupt its internal state. onToken: null, // A function can be passed as `onComment` option, which will // cause Acorn to call that function with `(block, text, start, // end)` parameters whenever a comment is skipped. `block` is a // boolean indicating whether this is a block (`/* */`) comment, // `text` is the content of the comment, and `start` and `end` are // character offsets that denote the start and end of the comment. // When the `locations` option is on, two more parameters are // passed, the full `{line, column}` locations of the start and // end of the comments. Note that you are not allowed to call the // parser from the callback—that will corrupt its internal state. onComment: null, // Nodes have their start and end characters offsets recorded in // `start` and `end` properties (directly on the node, rather than // the `loc` object, which holds line/column data. To also add a // [semi-standardized][range] `range` property holding a `[start, // end]` array with the same numbers, set the `ranges` option to // `true`. // // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 ranges: false, // It is possible to parse multiple files into a single AST by // passing the tree produced by parsing the first file as // `program` option in subsequent parses. This will add the // toplevel forms of the parsed file to the `Program` (top) node // of an existing parse tree. program: null, // When `locations` is on, you can pass this to record the source // file in every node's `loc` object. sourceFile: null, // This value, if given, is stored in every node, whether // `locations` is on or off. directSourceFile: null, // When enabled, parenthesized expressions are represented by // (non-standard) ParenthesizedExpression nodes preserveParens: false }; // Interpret and default an options object var warnedAboutEcmaVersion = false; function getOptions(opts) { var options = {}; for (var opt in defaultOptions) { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; } if (options.ecmaVersion === "latest") { options.ecmaVersion = 1e8; } else if (options.ecmaVersion == null) { if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { warnedAboutEcmaVersion = true; console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); } options.ecmaVersion = 11; } else if (options.ecmaVersion >= 2015) { options.ecmaVersion -= 2009; } if (options.allowReserved == null) { options.allowReserved = options.ecmaVersion < 5; } if (!opts || opts.allowHashBang == null) { options.allowHashBang = options.ecmaVersion >= 14; } if (isArray$1(options.onToken)) { var tokens = options.onToken; options.onToken = function (token) { return tokens.push(token); }; } if (isArray$1(options.onComment)) { options.onComment = pushComment(options, options.onComment); } return options } function pushComment(options, array) { return function(block, text, start, end, startLoc, endLoc) { var comment = { type: block ? "Block" : "Line", value: text, start: start, end: end }; if (options.locations) { comment.loc = new SourceLocation(this, startLoc, endLoc); } if (options.ranges) { comment.range = [start, end]; } array.push(comment); } } // Each scope gets a bitset that may contain these flags var SCOPE_TOP = 1, SCOPE_FUNCTION = 2, SCOPE_ASYNC = 4, SCOPE_GENERATOR = 8, SCOPE_ARROW = 16, SCOPE_SIMPLE_CATCH = 32, SCOPE_SUPER = 64, SCOPE_DIRECT_SUPER = 128, SCOPE_CLASS_STATIC_BLOCK = 256, SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; function functionFlags(async, generator) { return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) } // Used in checkLVal* and declareName to determine the type of a binding var BIND_NONE = 0, // Not a binding BIND_VAR = 1, // Var-style binding BIND_LEXICAL = 2, // Let- or const-style binding BIND_FUNCTION = 3, // Function declaration BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding BIND_OUTSIDE = 5; // Special case for function names as bound inside the function var Parser$1 = function Parser(options, input, startPos) { this.options = options = getOptions(options); this.sourceFile = options.sourceFile; this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); var reserved = ""; if (options.allowReserved !== true) { reserved = reservedWords$2[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; if (options.sourceType === "module") { reserved += " await"; } } this.reservedWords = wordsRegexp(reserved); var reservedStrict = (reserved ? reserved + " " : "") + reservedWords$2.strict; this.reservedWordsStrict = wordsRegexp(reservedStrict); this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords$2.strictBind); this.input = String(input); // Used to signal to callers of `readWord1` whether the word // contained any escape sequences. This is needed because words with // escape sequences must not be interpreted as keywords. this.containsEsc = false; // Set up token state // The current position of the tokenizer in the input. if (startPos) { this.pos = startPos; this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; } else { this.pos = this.lineStart = 0; this.curLine = 1; } // Properties of the current token: // Its type this.type = types$1.eof; // For tokens that include more information than their type, the value this.value = null; // Its start and end offset this.start = this.end = this.pos; // And, if locations are used, the {line, column} object // corresponding to those offsets this.startLoc = this.endLoc = this.curPosition(); // Position information for the previous token this.lastTokEndLoc = this.lastTokStartLoc = null; this.lastTokStart = this.lastTokEnd = this.pos; // The context stack is used to superficially track syntactic // context to predict whether a regular expression is allowed in a // given position. this.context = this.initialContext(); this.exprAllowed = true; // Figure out if it's a module code. this.inModule = options.sourceType === "module"; this.strict = this.inModule || this.strictDirective(this.pos); // Used to signify the start of a potential arrow function this.potentialArrowAt = -1; this.potentialArrowInForAwait = false; // Positions to delayed-check that yield/await does not exist in default parameters. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; // Labels in scope. this.labels = []; // Thus-far undefined exports. this.undefinedExports = Object.create(null); // If enabled, skip leading hashbang line. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") { this.skipLineComment(2); } // Scope tracking for duplicate variable names (see scope.js) this.scopeStack = []; this.enterScope(SCOPE_TOP); // For RegExp validation this.regexpState = null; // The stack of private names. // Each element has two properties: 'declared' and 'used'. // When it exited from the outermost class definition, all used private names must be declared. this.privateNameStack = []; }; var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } }; Parser$1.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 && !this.currentVarScope().inClassFieldInit }; prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit }; prototypeAccessors.canAwait.get = function () { for (var i = this.scopeStack.length - 1; i >= 0; i--) { var scope = this.scopeStack[i]; if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false } if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 } } return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction }; prototypeAccessors.allowSuper.get = function () { var ref = this.currentThisScope(); var flags = ref.flags; var inClassFieldInit = ref.inClassFieldInit; return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod }; prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; prototypeAccessors.allowNewDotTarget.get = function () { var ref = this.currentThisScope(); var flags = ref.flags; var inClassFieldInit = ref.inClassFieldInit; return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit }; prototypeAccessors.inClassStaticBlock.get = function () { return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0 }; Parser$1.extend = function extend () { var plugins = [], len = arguments.length; while ( len-- ) plugins[ len ] = arguments[ len ]; var cls = this; for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } return cls }; Parser$1.parse = function parse (input, options) { return new this(options, input).parse() }; Parser$1.parseExpressionAt = function parseExpressionAt (input, pos, options) { var parser = new this(options, input, pos); parser.nextToken(); return parser.parseExpression() }; Parser$1.tokenizer = function tokenizer (input, options) { return new this(options, input) }; Object.defineProperties( Parser$1.prototype, prototypeAccessors ); var pp$9 = Parser$1.prototype; // ## Parser utilities var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; pp$9.strictDirective = function(start) { if (this.options.ecmaVersion < 5) { return false } for (;;) { // Try to find string literal. skipWhiteSpace$1.lastIndex = start; start += skipWhiteSpace$1.exec(this.input)[0].length; var match = literal.exec(this.input.slice(start)); if (!match) { return false } if ((match[1] || match[2]) === "use strict") { skipWhiteSpace$1.lastIndex = start + match[0].length; var spaceAfter = skipWhiteSpace$1.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; var next = this.input.charAt(end); return next === ";" || next === "}" || (lineBreak.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) } start += match[0].length; // Skip semicolon, if any. skipWhiteSpace$1.lastIndex = start; start += skipWhiteSpace$1.exec(this.input)[0].length; if (this.input[start] === ";") { start++; } } }; // Predicate that tests whether the next token is of the given // type, and if yes, consumes it as a side effect. pp$9.eat = function(type) { if (this.type === type) { this.next(); return true } else { return false } }; // Tests whether parsed token is a contextual keyword. pp$9.isContextual = function(name) { return this.type === types$1.name && this.value === name && !this.containsEsc }; // Consumes contextual keyword if possible. pp$9.eatContextual = function(name) { if (!this.isContextual(name)) { return false } this.next(); return true }; // Asserts that following token is given contextual keyword. pp$9.expectContextual = function(name) { if (!this.eatContextual(name)) { this.unexpected(); } }; // Test whether a semicolon can be inserted at the current position. pp$9.canInsertSemicolon = function() { return this.type === types$1.eof || this.type === types$1.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }; pp$9.insertSemicolon = function() { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon) { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } return true } }; // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. pp$9.semicolon = function() { if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); } }; pp$9.afterTrailingComma = function(tokType, notNext) { if (this.type === tokType) { if (this.options.onTrailingComma) { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } if (!notNext) { this.next(); } return true } }; // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error. pp$9.expect = function(type) { this.eat(type) || this.unexpected(); }; // Raise an unexpected token error. pp$9.unexpected = function(pos) { this.raise(pos != null ? pos : this.start, "Unexpected token"); }; var DestructuringErrors = function DestructuringErrors() { this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1; }; pp$9.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, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); } }; pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) { if (!refDestructuringErrors) { return false } var shorthandAssign = refDestructuringErrors.shorthandAssign; var doubleProto = refDestructuringErrors.doubleProto; if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } if (shorthandAssign >= 0) { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } if (doubleProto >= 0) { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } }; pp$9.checkYieldAwaitInDefaultParams = function() { if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } if (this.awaitPos) { this.raise(this.awaitPos, "Await expression cannot be a default value"); } }; pp$9.isSimpleAssignTarget = function(expr) { if (expr.type === "ParenthesizedExpression") { return this.isSimpleAssignTarget(expr.expression) } return expr.type === "Identifier" || expr.type === "MemberExpression" }; var pp$8 = Parser$1.prototype; // ### Statement parsing // Parse a program. Initializes the parser, reads any number of // statements, and wraps them in a Program node. Optionally takes a // `program` argument. If present, the statements will be appended // to its body instead of creating a new node. pp$8.parseTopLevel = function(node) { var exports = Object.create(null); if (!node.body) { node.body = []; } while (this.type !== types$1.eof) { var stmt = this.parseStatement(null, true, exports); node.body.push(stmt); } if (this.inModule) { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) { var name = list[i]; this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); } } this.adaptDirectivePrologue(node.body); this.next(); node.sourceType = this.options.sourceType; return this.finishNode(node, "Program") }; var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; pp$8.isLet = function(context) { if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } skipWhiteSpace$1.lastIndex = this.pos; var skip = skipWhiteSpace$1.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 || nextCh === 92) { return true } // '[', '/' if (context) { return false } if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral if (isIdentifierStart(nextCh, true)) { var pos = next + 1; while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } var ident = this.input.slice(next, pos); if (!keywordRelationalOperator.test(ident)) { return true } } return false }; // check 'async [no LineTerminator here] function' // - 'async /*foo*/ function' is OK. // - 'async /*\n*/ function' is invalid. pp$8.isAsyncFunction = function() { if (this.options.ecmaVersion < 8 || !this.isContextual("async")) { return false } skipWhiteSpace$1.lastIndex = this.pos; var skip = skipWhiteSpace$1.exec(this.input); var next = this.pos + skip[0].length, after; return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) }; // Parse a single statement. // // If expecting a statement and finding a slash operator, parse a // regular expression literal. This is to handle cases like // `if (foo) /blah/.exec(foo)`, where looking at the previous token // does not help. pp$8.parseStatement = function(context, topLevel, exports) { var starttype = this.type, node = this.startNode(), kind; if (this.isLet(context)) { starttype = types$1._var; kind = "let"; } // Most types of statements are recognized by the keyword they // start with. Many are trivial to parse, some require a bit of // complexity. switch (starttype) { case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword) case types$1._debugger: return this.parseDebuggerStatement(node) case types$1._do: return this.parseDoStatement(node) case types$1._for: return this.parseForStatement(node) case types$1._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$1._class: if (context) { this.unexpected(); } return this.parseClass(node, true) case types$1._if: return this.parseIfStatement(node) case types$1._return: return this.parseReturnStatement(node) case types$1._switch: return this.parseSwitchStatement(node) case types$1._throw: return this.parseThrowStatement(node) case types$1._try: return this.parseTryStatement(node) case types$1._const: case types$1._var: kind = kind || this.value; if (context && kind !== "var") { this.unexpected(); } return this.parseVarStatement(node, kind) case types$1._while: return this.parseWhileStatement(node) case types$1._with: return this.parseWithStatement(node) case types$1.braceL: return this.parseBlock(true, node) case types$1.semi: return this.parseEmptyStatement(node) case types$1._export: case types$1._import: if (this.options.ecmaVersion > 10 && starttype === types$1._import) { skipWhiteSpace$1.lastIndex = this.pos; var skip = skipWhiteSpace$1.exec(this.input); var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); if (nextCh === 40 || nextCh === 46) // '(' or '.' { return this.parseExpressionStatement(node, this.parseExpression()) } } if (!this.options.allowImportExportEverywhere) { if (!topLevel) { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } if (!this.inModule) { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } } return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports) // If the statement does not start with a statement keyword or a // brace, it's an ExpressionStatement or LabeledStatement. We // simply start parsing an expression, and afterwards, if the // next token is a colon and the expression was a simple // Identifier node, we switch to interpreting it as a label. default: if (this.isAsyncFunction()) { if (context) { this.unexpected(); } this.next(); return this.parseFunctionStatement(node, true, !context) } var maybeName = this.value, expr = this.parseExpression(); if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) { return this.parseLabeledStatement(node, maybeName, expr, context) } else { return this.parseExpressionStatement(node, expr) } } }; pp$8.parseBreakContinueStatement = function(node, keyword) { var isBreak = keyword === "break"; this.next(); if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; } else if (this.type !== types$1.name) { this.unexpected(); } else { node.label = this.parseIdent(); this.semicolon(); } // Verify that there is an actual destination to break or // continue to. var i = 0; for (; i < this.labels.length; ++i) { var lab = this.labels[i]; if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } if (node.label && isBreak) { break } } } if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") }; pp$8.parseDebuggerStatement = function(node) { this.next(); this.semicolon(); return this.finishNode(node, "DebuggerStatement") }; pp$8.parseDoStatement = function(node) { this.next(); this.labels.push(loopLabel); node.body = this.parseStatement("do"); this.labels.pop(); this.expect(types$1._while); node.test = this.parseParenExpression(); if (this.options.ecmaVersion >= 6) { this.eat(types$1.semi); } else { this.semicolon(); } return this.finishNode(node, "DoWhileStatement") }; // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpression`), and then check // whether the next token is `in` or `of`. When there is no init // part (semicolon immediately after the opening parenthesis), it // is a regular `for` loop. pp$8.parseForStatement = function(node) { this.next(); var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; this.labels.push(loopLabel); this.enterScope(0); this.expect(types$1.parenL); if (this.type === types$1.semi) { if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, null) } var isLet = this.isLet(); if (this.type === types$1._var || this.type === types$1._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$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { if (this.options.ecmaVersion >= 9) { if (this.type === types$1._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 startsWithLet = this.isContextual("let"), isForOf = false; var refDestructuringErrors = new DestructuringErrors; var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { if (this.options.ecmaVersion >= 9) { if (this.type === types$1._in) { if (awaitAt > -1) { this.unexpected(awaitAt); } } else { node.await = awaitAt > -1; } } if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); } this.toAssignable(init, false, refDestructuringErrors); this.checkLValPattern(init); return this.parseForIn(node, init) } else { this.checkExpressionErrors(refDestructuringErrors, true); } if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, init) }; pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) { this.next(); return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) }; pp$8.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$1._else) ? this.parseStatement("if") : null; return this.finishNode(node, "IfStatement") }; pp$8.parseReturnStatement = function(node) { if (!this.inFunction && !this.options.allowReturnOutsideFunction) { this.raise(this.start, "'return' outside of function"); } this.next(); // In `return` (and `break`/`continue`), the keywords with // optional arguments, we eagerly look for a semicolon or the // possibility to insert one. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; } else { node.argument = this.parseExpression(); this.semicolon(); } return this.finishNode(node, "ReturnStatement") }; pp$8.parseSwitchStatement = function(node) { this.next(); node.discriminant = this.parseParenExpression(); node.cases = []; this.expect(types$1.braceL); this.labels.push(switchLabel); this.enterScope(0); // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is used to keep the node that we are currently // adding statements to. var cur; for (var sawDefault = false; this.type !== types$1.braceR;) { if (this.type === types$1._case || this.type === types$1._default) { var isCase = this.type === types$1._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$1.colon); } else { if (!cur) { this.unexpected(); } cur.consequent.push(this.parseStatement(null)); } } this.exitScope(); if (cur) { this.finishNode(cur, "SwitchCase"); } this.next(); // Closing brace this.labels.pop(); return this.finishNode(node, "SwitchStatement") }; pp$8.parseThrowStatement = function(node) { this.next(); if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) { this.raise(this.lastTokEnd, "Illegal newline after throw"); } node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement") }; // Reused empty array added for node fields that are always empty. var empty$1 = []; pp$8.parseCatchClauseParam = function() { var param = this.parseBindingAtom(); var simple = param.type === "Identifier"; this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); this.expect(types$1.parenR); return param }; pp$8.parseTryStatement = function(node) { this.next(); node.block = this.parseBlock(); node.handler = null; if (this.type === types$1._catch) { var clause = this.startNode(); this.next(); if (this.eat(types$1.parenL)) { clause.param = this.parseCatchClauseParam(); } 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$1._finally) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) { this.raise(node.start, "Missing catch or finally clause"); } return this.finishNode(node, "TryStatement") }; pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) { this.next(); this.parseVar(node, false, kind, allowMissingInitializer); this.semicolon(); return this.finishNode(node, "VariableDeclaration") }; pp$8.parseWhileStatement = function(node) { this.next(); node.test = this.parseParenExpression(); this.labels.push(loopLabel); node.body = this.parseStatement("while"); this.labels.pop(); return this.finishNode(node, "WhileStatement") }; pp$8.parseWithStatement = function(node) { if (this.strict) { this.raise(this.start, "'with' in strict mode"); } this.next(); node.object = this.parseParenExpression(); node.body = this.parseStatement("with"); return this.finishNode(node, "WithStatement") }; pp$8.parseEmptyStatement = function(node) { this.next(); return this.finishNode(node, "EmptyStatement") }; pp$8.parseLabeledStatement = function(node, maybeName, expr, context) { for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) { var label = list[i$1]; if (label.name === maybeName) { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); } } var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null; for (var i = this.labels.length - 1; i >= 0; i--) { var label$1 = this.labels[i]; if (label$1.statementStart === node.start) { // Update information about previous labels on this node label$1.statementStart = this.start; label$1.kind = kind; } else { break } } this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); this.labels.pop(); node.label = expr; return this.finishNode(node, "LabeledStatement") }; pp$8.parseExpressionStatement = function(node, expr) { node.expression = expr; this.semicolon(); return this.finishNode(node, "ExpressionStatement") }; // Parse a semicolon-enclosed block of statements, handling `"use // strict"` declarations when `allowStrict` is true (used for // function bodies). pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) { if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; if ( node === void 0 ) node = this.startNode(); node.body = []; this.expect(types$1.braceL); if (createNewLexicalScope) { this.enterScope(0); } while (this.type !== types$1.braceR) { var stmt = this.parseStatement(null); node.body.push(stmt); } if (exitStrict) { this.strict = false; } this.next(); if (createNewLexicalScope) { this.exitScope(); } return this.finishNode(node, "BlockStatement") }; // Parse a regular `for` loop. The disambiguation code in // `parseStatement` will already have parsed the init statement or // expression. pp$8.parseFor = function(node, init) { node.init = init; this.expect(types$1.semi); node.test = this.type === types$1.semi ? null : this.parseExpression(); this.expect(types$1.semi); node.update = this.type === types$1.parenR ? null : this.parseExpression(); this.expect(types$1.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, "ForStatement") }; // Parse a `for`/`in` and `for`/`of` loop, which are almost // same from parser's perspective. pp$8.parseForIn = function(node, init) { var isForIn = this.type === types$1._in; this.next(); if ( init.type === "VariableDeclaration" && init.declarations[0].init != null && ( !isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier" ) ) { this.raise( init.start, ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") ); } node.left = init; node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); this.expect(types$1.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") }; // Parse a list of variable declarations. pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) { node.declarations = []; node.kind = kind; for (;;) { var decl = this.startNode(); this.parseVarId(decl, kind); if (this.eat(types$1.eq)) { decl.init = this.parseMaybeAssign(isFor); } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { this.unexpected(); } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) { this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); } else { decl.init = null; } node.declarations.push(this.finishNode(decl, "VariableDeclarator")); if (!this.eat(types$1.comma)) { break } } return node }; pp$8.parseVarId = function(decl, kind) { decl.id = this.parseBindingAtom(); this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); }; var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; // Parse a function declaration or literal (depending on the // `statement & FUNC_STATEMENT`). // Remove `allowExpressionBody` for 7.0.0, as it is only called with false pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { this.initFunction(node); if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT)) { this.unexpected(); } node.generator = this.eat(types$1.star); } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } if (statement & FUNC_STATEMENT) { node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent(); if (node.id && !(statement & FUNC_HANGING_STATEMENT)) // If it is a regular function declaration in sloppy mode, then it is // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding // mode depends on properties of the current scope (see // treatFunctionsAsVar). { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } } var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags(node.async, node.generator)); if (!(statement & FUNC_STATEMENT)) { node.id = this.type === types$1.name ? this.parseIdent() : null; } this.parseFunctionParams(node); this.parseFunctionBody(node, allowExpressionBody, false, forInit); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") }; pp$8.parseFunctionParams = function(node) { this.expect(types$1.parenL); node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); }; // Parse a class declaration or literal (depending on the // `isStatement` parameter). pp$8.parseClass = function(node, isStatement) { this.next(); // ecma-262 14.6 Class Definitions // A class definition is always strict mode code. var oldStrict = this.strict; this.strict = true; this.parseClassId(node, isStatement); this.parseClassSuper(node); var privateNameMap = this.enterClassBody(); var classBody = this.startNode(); var hadConstructor = false; classBody.body = []; this.expect(types$1.braceL); while (this.type !== types$1.braceR) { var element = this.parseClassElement(node.superClass !== null); if (element) { classBody.body.push(element); if (element.type === "MethodDefinition" && element.kind === "constructor") { if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); } hadConstructor = true; } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); } } } this.strict = oldStrict; this.next(); node.body = this.finishNode(classBody, "ClassBody"); this.exitClassBody(); return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") }; pp$8.parseClassElement = function(constructorAllowsSuper) { if (this.eat(types$1.semi)) { return null } var ecmaVersion = this.options.ecmaVersion; var node = this.startNode(); var keyName = ""; var isGenerator = false; var isAsync = false; var kind = "method"; var isStatic = false; if (this.eatContextual("static")) { // Parse static init block if (ecmaVersion >= 13 && this.eat(types$1.braceL)) { this.parseClassStaticBlock(node); return node } if (this.isClassElementNameStart() || this.type === types$1.star) { isStatic = true; } else { keyName = "static"; } } node.static = isStatic; if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) { isAsync = true; } else { keyName = "async"; } } if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) { isGenerator = true; } if (!keyName && !isAsync && !isGenerator) { var lastValue = this.value; if (this.eatContextual("get") || this.eatContextual("set")) { if (this.isClassElementNameStart()) { kind = lastValue; } else { keyName = lastValue; } } } // Parse element name if (keyName) { // 'async', 'get', 'set', or 'static' were not a keyword contextually. // The last token is any of those. Make it the element name. node.computed = false; node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); node.key.name = keyName; this.finishNode(node.key, "Identifier"); } else { this.parseClassElementName(node); } // Parse element value if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) { var isConstructor = !node.static && checkKeyName(node, "constructor"); var allowsDirectSuper = isConstructor && constructorAllowsSuper; // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } node.kind = isConstructor ? "constructor" : kind; this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); } else { this.parseClassField(node); } return node }; pp$8.isClassElementNameStart = function() { return ( this.type === types$1.name || this.type === types$1.privateId || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword ) }; pp$8.parseClassElementName = function(element) { if (this.type === types$1.privateId) { if (this.value === "constructor") { this.raise(this.start, "Classes can't have an element named '#constructor'"); } element.computed = false; element.key = this.parsePrivateIdent(); } else { this.parsePropertyName(element); } }; pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { // Check key and flags var key = method.key; if (method.kind === "constructor") { 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"); } } else if (method.static && checkKeyName(method, "prototype")) { this.raise(key.start, "Classes may not have a static property named prototype"); } // Parse value var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); // Check value if (method.kind === "get" && value.params.length !== 0) { this.raiseRecoverable(value.start, "getter should have no params"); } if (method.kind === "set" && value.params.length !== 1) { this.raiseRecoverable(value.start, "setter should have exactly one param"); } if (method.kind === "set" && value.params[0].type === "RestElement") { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } return this.finishNode(method, "MethodDefinition") }; pp$8.parseClassField = function(field) { if (checkKeyName(field, "constructor")) { this.raise(field.key.start, "Classes can't have a field named 'constructor'"); } else if (field.static && checkKeyName(field, "prototype")) { this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); } if (this.eat(types$1.eq)) { // To raise SyntaxError if 'arguments' exists in the initializer. var scope = this.currentThisScope(); var inClassFieldInit = scope.inClassFieldInit; scope.inClassFieldInit = true; field.value = this.parseMaybeAssign(); scope.inClassFieldInit = inClassFieldInit; } else { field.value = null; } this.semicolon(); return this.finishNode(field, "PropertyDefinition") }; pp$8.parseClassStaticBlock = function(node) { node.body = []; var oldLabels = this.labels; this.labels = []; this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); while (this.type !== types$1.braceR) { var stmt = this.parseStatement(null); node.body.push(stmt); } this.next(); this.exitScope(); this.labels = oldLabels; return this.finishNode(node, "StaticBlock") }; pp$8.parseClassId = function(node, isStatement) { if (this.type === types$1.name) { node.id = this.parseIdent(); if (isStatement) { this.checkLValSimple(node.id, BIND_LEXICAL, false); } } else { if (isStatement === true) { this.unexpected(); } node.id = null; } }; pp$8.parseClassSuper = function(node) { node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null; }; pp$8.enterClassBody = function() { var element = {declared: Object.create(null), used: []}; this.privateNameStack.push(element); return element.declared }; pp$8.exitClassBody = function() { var ref = this.privateNameStack.pop(); var declared = ref.declared; var used = ref.used; if (!this.options.checkPrivateFields) { return } var len = this.privateNameStack.length; var parent = len === 0 ? null : this.privateNameStack[len - 1]; for (var i = 0; i < used.length; ++i) { var id = used[i]; if (!hasOwn(declared, id.name)) { if (parent) { parent.used.push(id); } else { this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); } } } }; function isPrivateNameConflicted(privateNameMap, element) { var name = element.key.name; var curr = privateNameMap[name]; var next = "true"; if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { next = (element.static ? "s" : "i") + element.kind; } // `class { get #a(){}; static set #a(_){} }` is also conflict. if ( curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget" ) { privateNameMap[name] = "true"; return false } else if (!curr) { privateNameMap[name] = next; return false } else { return true } } function checkKeyName(node, name) { var computed = node.computed; var key = node.key; return !computed && ( key.type === "Identifier" && key.name === name || key.type === "Literal" && key.value === name ) } // Parses module export declaration. pp$8.parseExportAllDeclaration = function(node, exports) { if (this.options.ecmaVersion >= 11) { if (this.eatContextual("as")) { node.exported = this.parseModuleExportName(); this.checkExport(exports, node.exported, this.lastTokStart); } else { node.exported = null; } } this.expectContextual("from"); if (this.type !== types$1.string) { this.unexpected(); } node.source = this.parseExprAtom(); this.semicolon(); return this.finishNode(node, "ExportAllDeclaration") }; pp$8.parseExport = function(node, exports) { this.next(); // export * from '...' if (this.eat(types$1.star)) { return this.parseExportAllDeclaration(node, exports) } if (this.eat(types$1._default)) { // export default ... this.checkExport(exports, "default", this.lastTokStart); node.declaration = this.parseExportDefaultDeclaration(); return this.finishNode(node, "ExportDefaultDeclaration") } // export var|const|let|function|class ... if (this.shouldParseExportStatement()) { node.declaration = this.parseExportDeclaration(node); if (node.declaration.type === "VariableDeclaration") { this.checkVariableExport(exports, node.declaration.declarations); } else { this.checkExport(exports, node.declaration.id, 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$1.string) { this.unexpected(); } node.source = this.parseExprAtom(); } else { for (var i = 0, list = node.specifiers; i < list.length; i += 1) { // check for keywords used as local names var spec = list[i]; this.checkUnreserved(spec.local); // check if export is defined this.checkLocalExport(spec.local); if (spec.local.type === "Literal") { this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); } } node.source = null; } this.semicolon(); } return this.finishNode(node, "ExportNamedDeclaration") }; pp$8.parseExportDeclaration = function(node) { return this.parseStatement(null) }; pp$8.parseExportDefaultDeclaration = function() { var isAsync; if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) { var fNode = this.startNode(); this.next(); if (isAsync) { this.next(); } return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync) } else if (this.type === types$1._class) { var cNode = this.startNode(); return this.parseClass(cNode, "nullableID") } else { var declaration = this.parseMaybeAssign(); this.semicolon(); return declaration } }; pp$8.checkExport = function(exports, name, pos) { if (!exports) { return } if (typeof name !== "string") { name = name.type === "Identifier" ? name.name : name.value; } if (hasOwn(exports, name)) { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } exports[name] = true; }; pp$8.checkPatternExport = function(exports, pat) { var type = pat.type; if (type === "Identifier") { this.checkExport(exports, pat, pat.start); } else if (type === "ObjectPattern") { for (var i = 0, list = pat.properties; i < list.length; i += 1) { var prop = list[i]; this.checkPatternExport(exports, prop); } } else if (type === "ArrayPattern") { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { var elt = list$1[i$1]; if (elt) { this.checkPatternExport(exports, elt); } } } else if (type === "Property") { this.checkPatternExport(exports, pat.value); } else if (type === "AssignmentPattern") { this.checkPatternExport(exports, pat.left); } else if (type === "RestElement") { this.checkPatternExport(exports, pat.argument); } else if (type === "ParenthesizedExpression") { this.checkPatternExport(exports, pat.expression); } }; pp$8.checkVariableExport = function(exports, decls) { if (!exports) { return } for (var i = 0, list = decls; i < list.length; i += 1) { var decl = list[i]; this.checkPatternExport(exports, decl.id); } }; pp$8.shouldParseExportStatement = function() { return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction() }; // Parses a comma-separated list of module exports. pp$8.parseExportSpecifier = function(exports) { var node = this.startNode(); node.local = this.parseModuleExportName(); node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; this.checkExport( exports, node.exported, node.exported.start ); return this.finishNode(node, "ExportSpecifier") }; pp$8.parseExportSpecifiers = function(exports) { var nodes = [], first = true; // export { x, y as z } [from '...'] this.expect(types$1.braceL); while (!this.eat(types$1.braceR)) { if (!first) { this.expect(types$1.comma); if (this.afterTrailingComma(types$1.braceR)) { break } } else { first = false; } nodes.push(this.parseExportSpecifier(exports)); } return nodes }; // Parses import declaration. pp$8.parseImport = function(node) { this.next(); // import '...' if (this.type === types$1.string) { node.specifiers = empty$1; node.source = this.parseExprAtom(); } else { node.specifiers = this.parseImportSpecifiers(); this.expectContextual("from"); node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected(); } this.semicolon(); return this.finishNode(node, "ImportDeclaration") }; // Parses a comma-separated list of module imports. pp$8.parseImportSpecifier = function() { var node = this.startNode(); node.imported = this.parseModuleExportName(); if (this.eatContextual("as")) { node.local = this.parseIdent(); } else { this.checkUnreserved(node.imported); node.local = node.imported; } this.checkLValSimple(node.local, BIND_LEXICAL); return this.finishNode(node, "ImportSpecifier") }; pp$8.parseImportDefaultSpecifier = function() { // import defaultObj, { x, y as z } from '...' var node = this.startNode(); node.local = this.parseIdent(); this.checkLValSimple(node.local, BIND_LEXICAL); return this.finishNode(node, "ImportDefaultSpecifier") }; pp$8.parseImportNamespaceSpecifier = function() { var node = this.startNode(); this.next(); this.expectContextual("as"); node.local = this.parseIdent(); this.checkLValSimple(node.local, BIND_LEXICAL); return this.finishNode(node, "ImportNamespaceSpecifier") }; pp$8.parseImportSpecifiers = function() { var nodes = [], first = true; if (this.type === types$1.name) { nodes.push(this.parseImportDefaultSpecifier()); if (!this.eat(types$1.comma)) { return nodes } } if (this.type === types$1.star) { nodes.push(this.parseImportNamespaceSpecifier()); return nodes } this.expect(types$1.braceL); while (!this.eat(types$1.braceR)) { if (!first) { this.expect(types$1.comma); if (this.afterTrailingComma(types$1.braceR)) { break } } else { first = false; } nodes.push(this.parseImportSpecifier()); } return nodes }; pp$8.parseModuleExportName = function() { if (this.options.ecmaVersion >= 13 && this.type === types$1.string) { var stringLiteral = this.parseLiteral(this.value); if (loneSurrogate.test(stringLiteral.value)) { this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); } return stringLiteral } return this.parseIdent(true) }; // Set `ExpressionStatement#directive` property for directive prologues. pp$8.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$8.isDirectiveCandidate = function(statement) { return ( this.options.ecmaVersion >= 5 && statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && // Reject parenthesized strings. (this.input[statement.start] === "\"" || this.input[statement.start] === "'") ) }; var pp$7 = Parser$1.prototype; // Convert existing expression atom to assignable pattern // if possible. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) { if (this.options.ecmaVersion >= 6 && node) { switch (node.type) { case "Identifier": if (this.inAsync && node.name === "await") { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } break case "ObjectPattern": case "ArrayPattern": case "AssignmentPattern": case "RestElement": break case "ObjectExpression": node.type = "ObjectPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } for (var i = 0, list = node.properties; i < list.length; i += 1) { var prop = list[i]; this.toAssignable(prop, isBinding); // Early error: // AssignmentRestProperty[Yield, Await] : // `...` DestructuringAssignmentTarget[Yield, Await] // // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. if ( prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") ) { this.raise(prop.argument.start, "Unexpected token"); } } break case "Property": // AssignmentProperty has type === "Property" if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } this.toAssignable(node.value, isBinding); break case "ArrayExpression": node.type = "ArrayPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } this.toAssignableList(node.elements, isBinding); break case "SpreadElement": node.type = "RestElement"; this.toAssignable(node.argument, isBinding); if (node.argument.type === "AssignmentPattern") { this.raise(node.argument.start, "Rest elements cannot have a default value"); } break case "AssignmentExpression": if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } node.type = "AssignmentPattern"; delete node.operator; this.toAssignable(node.left, isBinding); break case "ParenthesizedExpression": this.toAssignable(node.expression, isBinding, refDestructuringErrors); break case "ChainExpression": this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); break case "MemberExpression": if (!isBinding) { break } default: this.raise(node.start, "Assigning to rvalue"); } } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } return node }; // Convert list of expression atoms to binding list. pp$7.toAssignableList = function(exprList, isBinding) { var end = exprList.length; for (var i = 0; i < end; i++) { var elt = exprList[i]; if (elt) { this.toAssignable(elt, isBinding); } } if (end) { var last = exprList[end - 1]; if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") { this.unexpected(last.argument.start); } } return exprList }; // Parses spread element. pp$7.parseSpread = function(refDestructuringErrors) { var node = this.startNode(); this.next(); node.argument = this.parseMaybeAssign(false, refDestructuringErrors); return this.finishNode(node, "SpreadElement") }; pp$7.parseRestBinding = function() { var node = this.startNode(); this.next(); // RestElement inside of a function parameter must be an identifier if (this.options.ecmaVersion === 6 && this.type !== types$1.name) { this.unexpected(); } node.argument = this.parseBindingAtom(); return this.finishNode(node, "RestElement") }; // Parses lvalue (assignable) atom. pp$7.parseBindingAtom = function() { if (this.options.ecmaVersion >= 6) { switch (this.type) { case types$1.bracketL: var node = this.startNode(); this.next(); node.elements = this.parseBindingList(types$1.bracketR, true, true); return this.finishNode(node, "ArrayPattern") case types$1.braceL: return this.parseObj(true) } } return this.parseIdent() }; pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) { var elts = [], first = true; while (!this.eat(close)) { if (first) { first = false; } else { this.expect(types$1.comma); } if (allowEmpty && this.type === types$1.comma) { elts.push(null); } else if (allowTrailingComma && this.afterTrailingComma(close)) { break } else if (this.type === types$1.ellipsis) { var rest = this.parseRestBinding(); this.parseBindingListItem(rest); elts.push(rest); if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); } this.expect(close); break } else { elts.push(this.parseAssignableListItem(allowModifiers)); } } return elts }; pp$7.parseAssignableListItem = function(allowModifiers) { var elem = this.parseMaybeDefault(this.start, this.startLoc); this.parseBindingListItem(elem); return elem }; pp$7.parseBindingListItem = function(param) { return param }; // Parses assignment pattern around given atom if possible. pp$7.parseMaybeDefault = function(startPos, startLoc, left) { left = left || this.parseBindingAtom(); if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left } var node = this.startNodeAt(startPos, startLoc); node.left = left; node.right = this.parseMaybeAssign(); return this.finishNode(node, "AssignmentPattern") }; // The following three functions all verify that a node is an lvalue — // something that can be bound, or assigned to. In order to do so, they perform // a variety of checks: // // - Check that none of the bound/assigned-to identifiers are reserved words. // - Record name declarations for bindings in the appropriate scope. // - Check duplicate argument names, if checkClashes is set. // // If a complex binding pattern is encountered (e.g., object and array // destructuring), the entire pattern is recursively checked. // // There are three versions of checkLVal*() appropriate for different // circumstances: // // - checkLValSimple() shall be used if the syntactic construct supports // nothing other than identifiers and member expressions. Parenthesized // expressions are also correctly handled. This is generally appropriate for // constructs for which the spec says // // > It is a Syntax Error if AssignmentTargetType of [the production] is not // > simple. // // It is also appropriate for checking if an identifier is valid and not // defined elsewhere, like import declarations or function/class identifiers. // // Examples where this is used include: // a += …; // import a from '…'; // where a is the node to be checked. // // - checkLValPattern() shall be used if the syntactic construct supports // anything checkLValSimple() supports, as well as object and array // destructuring patterns. This is generally appropriate for constructs for // which the spec says // // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor // > an ArrayLiteral and AssignmentTargetType of [the production] is not // > simple. // // Examples where this is used include: // (a = …); // const a = …; // try { … } catch (a) { … } // where a is the node to be checked. // // - checkLValInnerPattern() shall be used if the syntactic construct supports // anything checkLValPattern() supports, as well as default assignment // patterns, rest elements, and other constructs that may appear within an // object or array destructuring pattern. // // As a special case, function parameters also use checkLValInnerPattern(), // as they also support defaults and rest constructs. // // These functions deliberately support both assignment and binding constructs, // as the logic for both is exceedingly similar. If the node is the target of // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it // should be set to the appropriate BIND_* constant, like BIND_VAR or // BIND_LEXICAL. // // If the function is called with a non-BIND_NONE bindingType, then // additionally a checkClashes object may be specified to allow checking for // duplicate argument names. checkClashes is ignored if the provided construct // is an assignment (i.e., bindingType is BIND_NONE). pp$7.checkLValSimple = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE; var isBind = bindingType !== BIND_NONE; switch (expr.type) { case "Identifier": if (this.strict && this.reservedWordsStrictBind.test(expr.name)) { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } if (isBind) { if (bindingType === BIND_LEXICAL && expr.name === "let") { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } if (checkClashes) { if (hasOwn(checkClashes, expr.name)) { this.raiseRecoverable(expr.start, "Argument name clash"); } checkClashes[expr.name] = true; } if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } } break case "ChainExpression": this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); break case "MemberExpression": if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } break case "ParenthesizedExpression": if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } return this.checkLValSimple(expr.expression, bindingType, checkClashes) default: this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); } }; pp$7.checkLValPattern = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE; switch (expr.type) { case "ObjectPattern": for (var i = 0, list = expr.properties; i < list.length; i += 1) { var prop = list[i]; this.checkLValInnerPattern(prop, bindingType, checkClashes); } break case "ArrayPattern": for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { var elem = list$1[i$1]; if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } } break default: this.checkLValSimple(expr, bindingType, checkClashes); } }; pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) { if ( bindingType === void 0 ) bindingType = BIND_NONE; switch (expr.type) { case "Property": // AssignmentProperty has type === "Property" this.checkLValInnerPattern(expr.value, bindingType, checkClashes); break case "AssignmentPattern": this.checkLValPattern(expr.left, bindingType, checkClashes); break case "RestElement": this.checkLValPattern(expr.argument, bindingType, checkClashes); break default: this.checkLValPattern(expr, bindingType, checkClashes); } }; // The algorithm used to determine whether a regexp can appear at a // given point in the program is loosely based on sweet.js' approach. // See https://github.com/mozilla/sweet.js/wiki/design var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override; this.generator = !!generator; }; var types$2 = { b_stat: new TokContext("{", false), b_expr: new TokContext("{", true), b_tmpl: new TokContext("${", false), p_stat: new TokContext("(", false), p_expr: new TokContext("(", true), q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), f_stat: new TokContext("function", false), f_expr: new TokContext("function", true), f_expr_gen: new TokContext("function", true, false, null, true), f_gen: new TokContext("function", false, false, null, true) }; var pp$6 = Parser$1.prototype; pp$6.initialContext = function() { return [types$2.b_stat] }; pp$6.curContext = function() { return this.context[this.context.length - 1] }; pp$6.braceIsBlock = function(prevType) { var parent = this.curContext(); if (parent === types$2.f_expr || parent === types$2.f_stat) { return true } if (prevType === types$1.colon && (parent === types$2.b_stat || parent === types$2.b_expr)) { return !parent.isExpr } // The check for `tt.name && exprAllowed` detects whether we are // after a `yield` or `of` construct. See the `updateContext` for // `tt.name`. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) { return true } if (prevType === types$1.braceL) { return parent === types$2.b_stat } if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) { return false } return !this.exprAllowed }; pp$6.inGeneratorContext = function() { for (var i = this.context.length - 1; i >= 1; i--) { var context = this.context[i]; if (context.token === "function") { return context.generator } } return false }; pp$6.updateContext = function(prevType) { var update, type = this.type; if (type.keyword && prevType === types$1.dot) { this.exprAllowed = false; } else if (update = type.updateContext) { update.call(this, prevType); } else { this.exprAllowed = type.beforeExpr; } }; // Used to handle egde cases when token context could not be inferred correctly during tokenization phase pp$6.overrideContext = function(tokenCtx) { if (this.curContext() !== tokenCtx) { this.context[this.context.length - 1] = tokenCtx; } }; // Token-specific context update code types$1.parenR.updateContext = types$1.braceR.updateContext = function() { if (this.context.length === 1) { this.exprAllowed = true; return } var out = this.context.pop(); if (out === types$2.b_stat && this.curContext().token === "function") { out = this.context.pop(); } this.exprAllowed = !out.isExpr; }; types$1.braceL.updateContext = function(prevType) { this.context.push(this.braceIsBlock(prevType) ? types$2.b_stat : types$2.b_expr); this.exprAllowed = true; }; types$1.dollarBraceL.updateContext = function() { this.context.push(types$2.b_tmpl); this.exprAllowed = true; }; types$1.parenL.updateContext = function(prevType) { var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while; this.context.push(statementParens ? types$2.p_stat : types$2.p_expr); this.exprAllowed = true; }; types$1.incDec.updateContext = function() { // tokExprAllowed stays unchanged }; types$1._function.updateContext = types$1._class.updateContext = function(prevType) { if (prevType.beforeExpr && prevType !== types$1._else && !(prevType === types$1.semi && this.curContext() !== types$2.p_stat) && !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types$2.b_stat)) { this.context.push(types$2.f_expr); } else { this.context.push(types$2.f_stat); } this.exprAllowed = false; }; types$1.backQuote.updateContext = function() { if (this.curContext() === types$2.q_tmpl) { this.context.pop(); } else { this.context.push(types$2.q_tmpl); } this.exprAllowed = false; }; types$1.star.updateContext = function(prevType) { if (prevType === types$1._function) { var index = this.context.length - 1; if (this.context[index] === types$2.f_expr) { this.context[index] = types$2.f_expr_gen; } else { this.context[index] = types$2.f_gen; } } this.exprAllowed = true; }; types$1.name.updateContext = function(prevType) { var allowed = false; if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) { if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) { allowed = true; } } this.exprAllowed = allowed; }; // A recursive descent parser operates by defining functions for all // syntactic elements, and recursively calling those, each function // advancing the input stream and returning an AST node. Precedence // of constructs (for example, the fact that `!x[1]` means `!(x[1])` // instead of `(!x)[1]` is handled by the fact that the parser // function that parses unary prefix operators is called first, and // in turn calls the function that parses `[]` subscripts — that // way, it'll receive the node for `x[1]` already parsed, and wraps // *that* in the unary operator node. // // Acorn uses an [operator precedence parser][opp] to handle binary // operator precedence, because it is much more compact than using // the technique outlined above, which uses different, nesting // functions to specify precedence, for all of the ten binary // precedence levels that JavaScript defines. // // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser var pp$5 = Parser$1.prototype; // Check if property name clashes with already added. // Object/class getters and setters are not allowed to clash — // either with each other or with an init property — and in // strict mode, init properties are also not allowed to be repeated. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) { if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") { return } if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) { return } var key = prop.key; var name; switch (key.type) { case "Identifier": name = key.name; break case "Literal": name = String(key.value); break default: return } var kind = prop.kind; if (this.options.ecmaVersion >= 6) { if (name === "__proto__" && kind === "init") { if (propHash.proto) { if (refDestructuringErrors) { if (refDestructuringErrors.doubleProto < 0) { refDestructuringErrors.doubleProto = key.start; } } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } } propHash.proto = true; } return } name = "$" + name; var other = propHash[name]; if (other) { var redefinition; if (kind === "init") { redefinition = this.strict && other.init || other.get || other.set; } else { redefinition = other.init || other[kind]; } if (redefinition) { this.raiseRecoverable(key.start, "Redefinition of property"); } } else { other = propHash[name] = { init: false, get: false, set: false }; } other[kind] = true; }; // ### Expression parsing // These nest, from the most general expression type at the top to // 'atomic', nondivisible expression types at the bottom. Most of // the functions will simply let the function(s) below them parse, // and, *if* the syntactic construct they handle is present, wrap // the AST node that the inner parser gave them in another node. // Parse a full expression. The optional arguments are used to // forbid the `in` operator (in for loops initalization expressions) // and provide reference for storing '=' operator inside shorthand // property assignment in contexts where both object expression // and object pattern might appear (so it's possible to raise // delayed syntax error at correct position). pp$5.parseExpression = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); if (this.type === types$1.comma) { var node = this.startNodeAt(startPos, startLoc); node.expressions = [expr]; while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } return this.finishNode(node, "SequenceExpression") } return expr }; // Parse an assignment expression. This includes applications of // operators like `+=`. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { if (this.isContextual("yield")) { if (this.inGenerator) { return this.parseYield(forInit) } // The tokenizer will assume an expression is allowed after // `yield`, but this isn't that kind of yield else { this.exprAllowed = false; } } var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; if (refDestructuringErrors) { oldParenAssign = refDestructuringErrors.parenthesizedAssign; oldTrailingComma = refDestructuringErrors.trailingComma; oldDoubleProto = refDestructuringErrors.doubleProto; refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; } else { refDestructuringErrors = new DestructuringErrors; ownDestructuringErrors = true; } var startPos = this.start, startLoc = this.startLoc; if (this.type === types$1.parenL || this.type === types$1.name) { this.potentialArrowAt = this.start; this.potentialArrowInForAwait = forInit === "await"; } var left = this.parseMaybeConditional(forInit, refDestructuringErrors); if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } if (this.type.isAssign) { var node = this.startNodeAt(startPos, startLoc); node.operator = this.value; if (this.type === types$1.eq) { left = this.toAssignable(left, false, refDestructuringErrors); } if (!ownDestructuringErrors) { refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; } if (refDestructuringErrors.shorthandAssign >= left.start) { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly if (this.type === types$1.eq) { this.checkLValPattern(left); } else { this.checkLValSimple(left); } node.left = left; this.next(); node.right = this.parseMaybeAssign(forInit); if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; } return this.finishNode(node, "AssignmentExpression") } else { if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } } if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } return left }; // Parse a ternary conditional (`?:`) operator. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprOps(forInit, refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } if (this.eat(types$1.question)) { var node = this.startNodeAt(startPos, startLoc); node.test = expr; node.consequent = this.parseMaybeAssign(); this.expect(types$1.colon); node.alternate = this.parseMaybeAssign(forInit); return this.finishNode(node, "ConditionalExpression") } return expr }; // Start the precedence parser. pp$5.parseExprOps = function(forInit, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) }; // Parse binary operators with the operator precedence parsing // algorithm. `left` is the left-hand side of the operator. // `minPrec` provides context that allows the function to stop and // defer further parser to one of its callers when it encounters an // operator that has a lower precedence than the set it is parsing. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { var prec = this.type.binop; if (prec != null && (!forInit || this.type !== types$1._in)) { if (prec > minPrec) { var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND; var coalesce = this.type === types$1.coalesce; if (coalesce) { // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. prec = types$1.logicalAND.binop; } var op = this.value; this.next(); var startPos = this.start, startLoc = this.startLoc; var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) { this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); } return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) } } return left }; pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) { if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); } var node = this.startNodeAt(startPos, startLoc); node.left = left; node.operator = op; node.right = right; return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") }; // Parse unary operators, both prefix and postfix. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { var startPos = this.start, startLoc = this.startLoc, expr; if (this.isContextual("await") && this.canAwait) { expr = this.parseAwait(forInit); sawUnary = true; } else if (this.type.prefix) { var node = this.startNode(), update = this.type === types$1.incDec; node.operator = this.value; node.prefix = true; this.next(); node.argument = this.parseMaybeUnary(null, true, update, forInit); this.checkExpressionErrors(refDestructuringErrors, true); if (update) { this.checkLValSimple(node.argument); } else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } else { sawUnary = true; } expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); } else if (!sawUnary && this.type === types$1.privateId) { if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { this.unexpected(); } expr = this.parsePrivateIdent(); // only could be private fields in 'in', such as #x in obj if (this.type !== types$1._in) { this.unexpected(); } } else { expr = this.parseExprSubscripts(refDestructuringErrors, forInit); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } while (this.type.postfix && !this.canInsertSemicolon()) { var node$1 = this.startNodeAt(startPos, startLoc); node$1.operator = this.value; node$1.prefix = false; node$1.argument = expr; this.checkLValSimple(expr); this.next(); expr = this.finishNode(node$1, "UpdateExpression"); } } if (!incDec && this.eat(types$1.starstar)) { if (sawUnary) { this.unexpected(this.lastTokStart); } else { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) } } else { return expr } }; function isPrivateFieldAccess(node) { return ( node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) ) } // Parse call, dot, and `[]`-subscript expressions. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprAtom(refDestructuringErrors, forInit); if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") { return expr } var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); if (refDestructuringErrors && result.type === "MemberExpression") { if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } } return result }; pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.potentialArrowAt === base.start; var optionalChained = false; while (true) { var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); if (element.optional) { optionalChained = true; } if (element === base || element.type === "ArrowFunctionExpression") { if (optionalChained) { var chainNode = this.startNodeAt(startPos, startLoc); chainNode.expression = element; element = this.finishNode(chainNode, "ChainExpression"); } return element } base = element; } }; pp$5.shouldParseAsyncArrow = function() { return !this.canInsertSemicolon() && this.eat(types$1.arrow) }; pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit) }; pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { var optionalSupported = this.options.ecmaVersion >= 11; var optional = optionalSupported && this.eat(types$1.questionDot); if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } var computed = this.eat(types$1.bracketL); if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) { var node = this.startNodeAt(startPos, startLoc); node.object = base; if (computed) { node.property = this.parseExpression(); this.expect(types$1.bracketR); } else if (this.type === types$1.privateId && base.type !== "Super") { node.property = this.parsePrivateIdent(); } else { node.property = this.parseIdent(this.options.allowReserved !== "never"); } node.computed = !!computed; if (optionalSupported) { node.optional = optional; } base = this.finishNode(node, "MemberExpression"); } else if (!noCalls && this.eat(types$1.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$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) { 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.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit) } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; var node$1 = this.startNodeAt(startPos, startLoc); node$1.callee = base; node$1.arguments = exprList; if (optionalSupported) { node$1.optional = optional; } base = this.finishNode(node$1, "CallExpression"); } else if (this.type === types$1.backQuote) { if (optional || optionalChained) { this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); } var node$2 = this.startNodeAt(startPos, startLoc); node$2.tag = base; node$2.quasi = this.parseTemplate({isTagged: true}); base = this.finishNode(node$2, "TaggedTemplateExpression"); } return base }; // Parse an atomic expression — either a single token that is an // expression, an expression started by a keyword like `function` or // `new`, or an expression wrapped in punctuation like `()`, `[]`, // or `{}`. pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) { // 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$1.slash) { this.readRegexp(); } var node, canBeArrow = this.potentialArrowAt === this.start; switch (this.type) { case types$1._super: if (!this.allowSuper) { this.raise(this.start, "'super' keyword outside a method"); } node = this.startNode(); this.next(); if (this.type === types$1.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$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) { this.unexpected(); } return this.finishNode(node, "Super") case types$1._this: node = this.startNode(); this.next(); return this.finishNode(node, "ThisExpression") case types$1.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$1._function)) { this.overrideContext(types$2.f_expr); return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit) } if (canBeArrow && !this.canInsertSemicolon()) { if (this.eat(types$1.arrow)) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) } if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { id = this.parseIdent(false); if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) { this.unexpected(); } return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit) } } return id case types$1.regexp: var value = this.value; node = this.parseLiteral(value.value); node.regex = {pattern: value.pattern, flags: value.flags}; return node case types$1.num: case types$1.string: return this.parseLiteral(this.value) case types$1._null: case types$1._true: case types$1._false: node = this.startNode(); node.value = this.type === types$1._null ? null : this.type === types$1._true; node.raw = this.type.keyword; this.next(); return this.finishNode(node, "Literal") case types$1.parenL: var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); if (refDestructuringErrors) { if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) { refDestructuringErrors.parenthesizedAssign = start; } if (refDestructuringErrors.parenthesizedBind < 0) { refDestructuringErrors.parenthesizedBind = start; } } return expr case types$1.bracketL: node = this.startNode(); this.next(); node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors); return this.finishNode(node, "ArrayExpression") case types$1.braceL: this.overrideContext(types$2.b_expr); return this.parseObj(false, refDestructuringErrors) case types$1._function: node = this.startNode(); this.next(); return this.parseFunction(node, 0) case types$1._class: return this.parseClass(this.startNode(), false) case types$1._new: return this.parseNew() case types$1.backQuote: return this.parseTemplate() case types$1._import: if (this.options.ecmaVersion >= 11) { return this.parseExprImport(forNew) } else { return this.unexpected() } default: return this.parseExprAtomDefault() } }; pp$5.parseExprAtomDefault = function() { this.unexpected(); }; pp$5.parseExprImport = function(forNew) { var node = this.startNode(); // Consume `import` as an identifier for `import.meta`. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } var meta = this.parseIdent(true); if (this.type === types$1.parenL && !forNew) { return this.parseDynamicImport(node) } else if (this.type === types$1.dot) { node.meta = meta; return this.parseImportMeta(node) } else { this.unexpected(); } }; pp$5.parseDynamicImport = function(node) { this.next(); // skip `(` // Parse node.source. node.source = this.parseMaybeAssign(); // Verify ending. if (!this.eat(types$1.parenR)) { var errorPos = this.start; if (this.eat(types$1.comma) && this.eat(types$1.parenR)) { this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); } else { this.unexpected(errorPos); } } return this.finishNode(node, "ImportExpression") }; pp$5.parseImportMeta = function(node) { this.next(); // skip `.` var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "meta") { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } if (containsEsc) { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } return this.finishNode(node, "MetaProperty") }; pp$5.parseLiteral = function(value) { var node = this.startNode(); node.value = value; node.raw = this.input.slice(this.start, this.end); if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } this.next(); return this.finishNode(node, "Literal") }; pp$5.parseParenExpression = function() { this.expect(types$1.parenL); var val = this.parseExpression(); this.expect(types$1.parenR); return val }; pp$5.shouldParseArrow = function(exprList) { return !this.canInsertSemicolon() }; pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; if (this.options.ecmaVersion >= 6) { this.next(); var innerStartPos = this.start, innerStartLoc = this.startLoc; var exprList = [], first = true, lastIsComma = false; var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; this.yieldPos = 0; this.awaitPos = 0; // Do not save awaitIdentPos to allow checking awaits nested in parameters while (this.type !== types$1.parenR) { first ? first = false : this.expect(types$1.comma); if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) { lastIsComma = true; break } else if (this.type === types$1.ellipsis) { spreadStart = this.start; exprList.push(this.parseParenItem(this.parseRestBinding())); if (this.type === types$1.comma) { this.raiseRecoverable( this.start, "Comma is not permitted after the rest element" ); } break } else { exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); } } var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; this.expect(types$1.parenR); if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; return this.parseParenArrowList(startPos, startLoc, exprList, forInit) } if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } if (spreadStart) { this.unexpected(spreadStart); } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; if (exprList.length > 1) { val = this.startNodeAt(innerStartPos, innerStartLoc); val.expressions = exprList; this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); } else { val = exprList[0]; } } else { val = this.parseParenExpression(); } if (this.options.preserveParens) { var par = this.startNodeAt(startPos, startLoc); par.expression = val; return this.finishNode(par, "ParenthesizedExpression") } else { return val } }; pp$5.parseParenItem = function(item) { return item }; pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit) }; // New's precedence is slightly tricky. It must allow its argument to // be a `[]` or dot subscript expression, but not a call — at least, // not without wrapping it in parentheses. Thus, it uses the noCalls // argument to parseSubscripts to prevent it from consuming the // argument list. var empty = []; pp$5.parseNew = function() { if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } var node = this.startNode(); var meta = this.parseIdent(true); if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) { node.meta = meta; var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "target") { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } if (containsEsc) { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } if (!this.allowNewDotTarget) { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); } return this.finishNode(node, "MetaProperty") } var startPos = this.start, startLoc = this.startLoc; node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false); if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); } else { node.arguments = empty; } return this.finishNode(node, "NewExpression") }; // Parse template expression. pp$5.parseTemplateElement = function(ref) { var isTagged = ref.isTagged; var elem = this.startNode(); if (this.type === types$1.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$1.backQuote; return this.finishNode(elem, "TemplateElement") }; pp$5.parseTemplate = function(ref) { if ( ref === void 0 ) ref = {}; var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; var node = this.startNode(); this.next(); node.expressions = []; var curElt = this.parseTemplateElement({isTagged: isTagged}); node.quasis = [curElt]; while (!curElt.tail) { if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); } this.expect(types$1.dollarBraceL); node.expressions.push(this.parseExpression()); this.expect(types$1.braceR); node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); } this.next(); return this.finishNode(node, "TemplateLiteral") }; pp$5.isAsyncProp = function(prop) { return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }; // Parse an object literal or binding pattern. pp$5.parseObj = function(isPattern, refDestructuringErrors) { var node = this.startNode(), first = true, propHash = {}; node.properties = []; this.next(); while (!this.eat(types$1.braceR)) { if (!first) { this.expect(types$1.comma); if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break } } else { first = false; } var prop = this.parseProperty(isPattern, refDestructuringErrors); if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } node.properties.push(prop); } return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") }; pp$5.parseProperty = function(isPattern, refDestructuringErrors) { var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) { if (isPattern) { prop.argument = this.parseIdent(false); if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); } return this.finishNode(prop, "RestElement") } // Parse argument. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); // To disallow trailing comma via `this.toAssignable()`. if (this.type === types$1.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$1.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$1.star); this.parsePropertyName(prop); } else { isAsync = false; } this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); return this.finishNode(prop, "Property") }; pp$5.parseGetterSetter = function(prop) { 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"); } } }; pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { if ((isGenerator || isAsync) && this.type === types$1.colon) { this.unexpected(); } if (this.eat(types$1.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$1.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$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) { if (isGenerator || isAsync) { this.unexpected(); } this.parseGetterSetter(prop); } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { if (isGenerator || isAsync) { this.unexpected(); } this.checkUnreserved(prop.key); if (prop.key.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = startPos; } prop.kind = "init"; if (isPattern) { prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); } else if (this.type === types$1.eq && refDestructuringErrors) { if (refDestructuringErrors.shorthandAssign < 0) { refDestructuringErrors.shorthandAssign = this.start; } prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); } else { prop.value = this.copyNode(prop.key); } prop.shorthand = true; } else { this.unexpected(); } }; pp$5.parsePropertyName = function(prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(types$1.bracketL)) { prop.computed = true; prop.key = this.parseMaybeAssign(); this.expect(types$1.bracketR); return prop.key } else { prop.computed = false; } } return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") }; // Initialize empty function node. pp$5.initFunction = function(node) { node.id = null; if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } if (this.options.ecmaVersion >= 8) { node.async = false; } }; // Parse object or class method. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.initFunction(node); if (this.options.ecmaVersion >= 6) { node.generator = isGenerator; } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); this.expect(types$1.parenL); node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); this.parseFunctionBody(node, false, true, false); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "FunctionExpression") }; // Parse arrow function expression with given parameters. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) { var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); this.initFunction(node); if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; node.params = this.toAssignableList(params, true); this.parseFunctionBody(node, true, false, forInit); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "ArrowFunctionExpression") }; // Parse function body and check parameters. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { var isExpression = isArrowFunction && this.type !== types$1.braceL; var oldStrict = this.strict, useStrict = false; if (isExpression) { node.body = this.parseMaybeAssign(forInit); node.expression = true; this.checkParams(node, false); } else { var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); if (!oldStrict || nonSimple) { useStrict = this.strictDirective(this.end); // If this is a strict mode function, verify that argument names // are not repeated, and it does not try to bind the words `eval` // or `arguments`. if (useStrict && nonSimple) { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } } // Start a new scope with regard to labels and the `inFunction` // flag (restore them to their old value afterwards). var oldLabels = this.labels; this.labels = []; if (useStrict) { this.strict = true; } // Add the params to varDeclaredNames to ensure that an error is thrown // if a let/const declaration in the function clashes with one of the params. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); node.expression = false; this.adaptDirectivePrologue(node.body.body); this.labels = oldLabels; } this.exitScope(); }; pp$5.isSimpleParamList = function(params) { for (var i = 0, list = params; i < list.length; i += 1) { var param = list[i]; if (param.type !== "Identifier") { return false } } return true }; // Checks function params for various disallowed patterns such as using "eval" // or "arguments" and duplicate parameters. pp$5.checkParams = function(node, allowDuplicates) { var nameHash = Object.create(null); for (var i = 0, list = node.params; i < list.length; i += 1) { var param = list[i]; this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); } }; // Parses a comma-separated list of expressions, and returns them as // an array. `close` is the token type that ends the list, and // `allowEmpty` can be turned on to allow subsequent commas with // nothing in between them to be parsed as `null` (which is needed // for array literals). pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { var elts = [], first = true; while (!this.eat(close)) { if (!first) { this.expect(types$1.comma); if (allowTrailingComma && this.afterTrailingComma(close)) { break } } else { first = false; } var elt = (void 0); if (allowEmpty && this.type === types$1.comma) { elt = null; } else if (this.type === types$1.ellipsis) { elt = this.parseSpread(refDestructuringErrors); if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this.start; } } else { elt = this.parseMaybeAssign(false, refDestructuringErrors); } elts.push(elt); } return elts }; pp$5.checkUnreserved = function(ref) { var start = ref.start; var end = ref.end; var name = ref.name; if (this.inGenerator && name === "yield") { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } if (this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } if (this.currentThisScope().inClassFieldInit && name === "arguments") { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } if (this.inClassStaticBlock && (name === "arguments" || name === "await")) { this.raise(start, ("Cannot use " + name + " in class static initialization block")); } if (this.keywords.test(name)) { this.raise(start, ("Unexpected keyword '" + name + "'")); } if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) { return } var re = this.strict ? this.reservedWordsStrict : this.reservedWords; if (re.test(name)) { if (!this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); } }; // Parse the next token as an identifier. If `liberal` is true (used // when parsing properties), it will also convert keywords into // identifiers. pp$5.parseIdent = function(liberal) { var node = this.parseIdentNode(); this.next(!!liberal); this.finishNode(node, "Identifier"); if (!liberal) { this.checkUnreserved(node); if (node.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = node.start; } } return node }; pp$5.parseIdentNode = function() { var node = this.startNode(); if (this.type === types$1.name) { node.name = this.value; } else if (this.type.keyword) { node.name = this.type.keyword; // To fix https://github.com/acornjs/acorn/issues/575 // `class` and `function` keywords push new context into this.context. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { this.context.pop(); } } else { this.unexpected(); } return node }; pp$5.parsePrivateIdent = function() { var node = this.startNode(); if (this.type === types$1.privateId) { node.name = this.value; } else { this.unexpected(); } this.next(); this.finishNode(node, "PrivateIdentifier"); // For validating existence if (this.options.checkPrivateFields) { if (this.privateNameStack.length === 0) { this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); } else { this.privateNameStack[this.privateNameStack.length - 1].used.push(node); } } return node }; // Parses yield expression inside generator. pp$5.parseYield = function(forInit) { if (!this.yieldPos) { this.yieldPos = this.start; } var node = this.startNode(); this.next(); if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) { node.delegate = false; node.argument = null; } else { node.delegate = this.eat(types$1.star); node.argument = this.parseMaybeAssign(forInit); } return this.finishNode(node, "YieldExpression") }; pp$5.parseAwait = function(forInit) { if (!this.awaitPos) { this.awaitPos = this.start; } var node = this.startNode(); this.next(); node.argument = this.parseMaybeUnary(null, true, false, forInit); return this.finishNode(node, "AwaitExpression") }; var pp$4 = Parser$1.prototype; // This function is used to raise exceptions on parse errors. It // takes an offset integer (into the current `input`) to indicate // the location of the error, attaches the position to the end // of the error message, and then raises a `SyntaxError` with that // message. pp$4.raise = function(pos, message) { var loc = getLineInfo(this.input, pos); message += " (" + loc.line + ":" + loc.column + ")"; var err = new SyntaxError(message); err.pos = pos; err.loc = loc; err.raisedAt = this.pos; throw err }; pp$4.raiseRecoverable = pp$4.raise; pp$4.curPosition = function() { if (this.options.locations) { return new Position(this.curLine, this.pos - this.lineStart) } }; var pp$3 = Parser$1.prototype; var Scope$1 = 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 = []; // A switch to disallow the identifier reference 'arguments' this.inClassFieldInit = false; }; // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. pp$3.enterScope = function(flags) { this.scopeStack.push(new Scope$1(flags)); }; pp$3.exitScope = function() { this.scopeStack.pop(); }; // The spec says: // > At the top level of a function, or script, function declarations are // > treated like var declarations rather than like lexical declarations. pp$3.treatFunctionsAsVarInScope = function(scope) { return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) }; pp$3.declareName = function(name, bindingType, pos) { var redeclared = false; if (bindingType === BIND_LEXICAL) { var scope = this.currentScope(); redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; scope.lexical.push(name); if (this.inModule && (scope.flags & SCOPE_TOP)) { delete this.undefinedExports[name]; } } else if (bindingType === BIND_SIMPLE_CATCH) { var scope$1 = this.currentScope(); scope$1.lexical.push(name); } else if (bindingType === BIND_FUNCTION) { var scope$2 = this.currentScope(); if (this.treatFunctionsAsVar) { redeclared = scope$2.lexical.indexOf(name) > -1; } else { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } scope$2.functions.push(name); } else { for (var i = this.scopeStack.length - 1; i >= 0; --i) { var scope$3 = this.scopeStack[i]; if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { redeclared = true; break } scope$3.var.push(name); if (this.inModule && (scope$3.flags & SCOPE_TOP)) { delete this.undefinedExports[name]; } if (scope$3.flags & SCOPE_VAR) { break } } } if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } }; pp$3.checkLocalExport = function(id) { // scope.functions must be empty as Module code is always strict. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) { this.undefinedExports[id.name] = id; } }; pp$3.currentScope = function() { return this.scopeStack[this.scopeStack.length - 1] }; pp$3.currentVarScope = function() { for (var i = this.scopeStack.length - 1;; i--) { var scope = this.scopeStack[i]; if (scope.flags & SCOPE_VAR) { return scope } } }; // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. pp$3.currentThisScope = function() { for (var i = this.scopeStack.length - 1;; i--) { var scope = this.scopeStack[i]; if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } } }; var Node = function Node(parser, pos, loc) { this.type = ""; this.start = pos; this.end = 0; if (parser.options.locations) { this.loc = new SourceLocation(parser, loc); } if (parser.options.directSourceFile) { this.sourceFile = parser.options.directSourceFile; } if (parser.options.ranges) { this.range = [pos, 0]; } }; // Start an AST node, attaching a start offset. var pp$2 = Parser$1.prototype; pp$2.startNode = function() { return new Node(this, this.start, this.startLoc) }; pp$2.startNodeAt = function(pos, loc) { return new Node(this, pos, loc) }; // Finish an AST node, adding `type` and `end` properties. function finishNodeAt(node, type, pos, loc) { node.type = type; node.end = pos; if (this.options.locations) { node.loc.end = loc; } if (this.options.ranges) { node.range[1] = pos; } return node } pp$2.finishNode = function(node, type) { return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) }; // Finish node at given position pp$2.finishNodeAt = function(node, type, pos, loc) { return finishNodeAt.call(this, node, type, pos, loc) }; pp$2.copyNode = function(node) { var newNode = new Node(this, node.start, this.startLoc); for (var prop in node) { newNode[prop] = node[prop]; } return newNode }; // This file contains Unicode properties extracted from the ECMAScript specification. // The lists are extracted like so: // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) // #table-binary-unicode-properties var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; var ecma11BinaryProperties = ecma10BinaryProperties; var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; var ecma13BinaryProperties = ecma12BinaryProperties; var ecma14BinaryProperties = ecma13BinaryProperties; var unicodeBinaryProperties = { 9: ecma9BinaryProperties, 10: ecma10BinaryProperties, 11: ecma11BinaryProperties, 12: ecma12BinaryProperties, 13: ecma13BinaryProperties, 14: ecma14BinaryProperties }; // #table-binary-unicode-properties-of-strings var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"; var unicodeBinaryPropertiesOfStrings = { 9: "", 10: "", 11: "", 12: "", 13: "", 14: ecma14BinaryPropertiesOfStrings }; // #table-unicode-general-category-values var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; // #table-unicode-script-values var ecma9ScriptValues = "Adlam Adlm Ahom 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 Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; var ecma14ScriptValues = ecma13ScriptValues + " Hrkt Katakana_Or_Hiragana Kawi Nag_Mundari Nagm Unknown Zzzz"; var unicodeScriptValues = { 9: ecma9ScriptValues, 10: ecma10ScriptValues, 11: ecma11ScriptValues, 12: ecma12ScriptValues, 13: ecma13ScriptValues, 14: ecma14ScriptValues }; var data = {}; function buildUnicodeData(ecmaVersion) { var d = data[ecmaVersion] = { binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]), nonBinary: { General_Category: wordsRegexp(unicodeGeneralCategoryValues), Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) } }; d.nonBinary.Script_Extensions = d.nonBinary.Script; d.nonBinary.gc = d.nonBinary.General_Category; d.nonBinary.sc = d.nonBinary.Script; d.nonBinary.scx = d.nonBinary.Script_Extensions; } for (var i$1 = 0, list = [9, 10, 11, 12, 13, 14]; i$1 < list.length; i$1 += 1) { var ecmaVersion = list[i$1]; buildUnicodeData(ecmaVersion); } var pp$1 = Parser$1.prototype; var RegExpValidationState = function RegExpValidationState(parser) { this.parser = parser; this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : ""); this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion]; this.source = ""; this.flags = ""; this.start = 0; this.switchU = false; this.switchV = false; this.switchN = false; this.pos = 0; this.lastIntValue = 0; this.lastStringValue = ""; this.lastAssertionIsQuantifiable = false; this.numCapturingParens = 0; this.maxBackReference = 0; this.groupNames = []; this.backReferenceNames = []; }; RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { var unicodeSets = flags.indexOf("v") !== -1; var unicode = flags.indexOf("u") !== -1; this.start = start | 0; this.source = pattern + ""; this.flags = flags; if (unicodeSets && this.parser.options.ecmaVersion >= 15) { this.switchU = true; this.switchV = true; this.switchN = true; } else { this.switchU = unicode && this.parser.options.ecmaVersion >= 6; this.switchV = false; this.switchN = unicode && this.parser.options.ecmaVersion >= 9; } }; RegExpValidationState.prototype.raise = function raise (message) { this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); }; // If u flag is given, this returns the code point at the index (it combines a surrogate pair). // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). RegExpValidationState.prototype.at = function at (i, forceU) { if ( forceU === void 0 ) forceU = false; var s = this.source; var l = s.length; if (i >= l) { return -1 } var c = s.charCodeAt(i); if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { return c } var next = s.charCodeAt(i + 1); return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c }; RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { if ( forceU === void 0 ) forceU = false; var s = this.source; var l = s.length; if (i >= l) { return l } var c = s.charCodeAt(i), next; if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { return i + 1 } return i + 2 }; RegExpValidationState.prototype.current = function current (forceU) { if ( forceU === void 0 ) forceU = false; return this.at(this.pos, forceU) }; RegExpValidationState.prototype.lookahead = function lookahead (forceU) { if ( forceU === void 0 ) forceU = false; return this.at(this.nextIndex(this.pos, forceU), forceU) }; RegExpValidationState.prototype.advance = function advance (forceU) { if ( forceU === void 0 ) forceU = false; this.pos = this.nextIndex(this.pos, forceU); }; RegExpValidationState.prototype.eat = function eat (ch, forceU) { if ( forceU === void 0 ) forceU = false; if (this.current(forceU) === ch) { this.advance(forceU); return true } return false }; RegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) { if ( forceU === void 0 ) forceU = false; var pos = this.pos; for (var i = 0, list = chs; i < list.length; i += 1) { var ch = list[i]; var current = this.at(pos, forceU); if (current === -1 || current !== ch) { return false } pos = this.nextIndex(pos, forceU); } this.pos = pos; return true }; /** * Validate the flags part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp$1.validateRegExpFlags = function(state) { var validFlags = state.validFlags; var flags = state.flags; var u = false; var v = false; 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"); } if (flag === "u") { u = true; } if (flag === "v") { v = true; } } if (this.options.ecmaVersion >= 15 && u && v) { this.raise(state.start, "Invalid regular expression flag"); } }; /** * Validate the pattern part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp$1.validateRegExpPattern = function(state) { this.regexp_pattern(state); // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of // parsing contains a |GroupName|, reparse with the goal symbol // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* // exception if _P_ did not conform to the grammar, if any elements of _P_ // were not matched by the parse, or if any Early Error conditions exist. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { state.switchN = true; this.regexp_pattern(state); } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern pp$1.regexp_pattern = function(state) { state.pos = 0; state.lastIntValue = 0; state.lastStringValue = ""; state.lastAssertionIsQuantifiable = false; state.numCapturingParens = 0; state.maxBackReference = 0; state.groupNames.length = 0; state.backReferenceNames.length = 0; this.regexp_disjunction(state); if (state.pos !== state.source.length) { // Make the same messages as V8. if (state.eat(0x29 /* ) */)) { state.raise("Unmatched ')'"); } if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { state.raise("Lone quantifier brackets"); } } if (state.maxBackReference > state.numCapturingParens) { state.raise("Invalid escape"); } for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { var name = list[i]; if (state.groupNames.indexOf(name) === -1) { state.raise("Invalid named capture referenced"); } } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction pp$1.regexp_disjunction = function(state) { this.regexp_alternative(state); while (state.eat(0x7C /* | */)) { this.regexp_alternative(state); } // Make the same message as V8. if (this.regexp_eatQuantifier(state, true)) { state.raise("Nothing to repeat"); } if (state.eat(0x7B /* { */)) { state.raise("Lone quantifier brackets"); } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative pp$1.regexp_alternative = function(state) { while (state.pos < state.source.length && this.regexp_eatTerm(state)) { } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term pp$1.regexp_eatTerm = function(state) { if (this.regexp_eatAssertion(state)) { // Handle `QuantifiableAssertion Quantifier` alternative. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion // is a QuantifiableAssertion. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { // Make the same message as V8. if (state.switchU) { state.raise("Invalid quantifier"); } } return true } if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { this.regexp_eatQuantifier(state); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion pp$1.regexp_eatAssertion = function(state) { var start = state.pos; state.lastAssertionIsQuantifiable = false; // ^, $ if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { return true } // \b \B if (state.eat(0x5C /* \ */)) { if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { return true } state.pos = start; } // Lookahead / Lookbehind if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { var lookbehind = false; if (this.options.ecmaVersion >= 9) { lookbehind = state.eat(0x3C /* < */); } if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { this.regexp_disjunction(state); if (!state.eat(0x29 /* ) */)) { state.raise("Unterminated group"); } state.lastAssertionIsQuantifiable = !lookbehind; return true } } state.pos = start; return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier pp$1.regexp_eatQuantifier = function(state, noError) { if ( noError === void 0 ) noError = false; if (this.regexp_eatQuantifierPrefix(state, noError)) { state.eat(0x3F /* ? */); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix pp$1.regexp_eatQuantifierPrefix = function(state, noError) { return ( state.eat(0x2A /* * */) || state.eat(0x2B /* + */) || state.eat(0x3F /* ? */) || this.regexp_eatBracedQuantifier(state, noError) ) }; pp$1.regexp_eatBracedQuantifier = function(state, noError) { var start = state.pos; if (state.eat(0x7B /* { */)) { var min = 0, max = -1; if (this.regexp_eatDecimalDigits(state)) { min = state.lastIntValue; if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { max = state.lastIntValue; } if (state.eat(0x7D /* } */)) { // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term if (max !== -1 && max < min && !noError) { state.raise("numbers out of order in {} quantifier"); } return true } } if (state.switchU && !noError) { state.raise("Incomplete quantifier"); } state.pos = start; } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom pp$1.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$1.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$1.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$1.regexp_eatCapturingGroup = function(state) { if (state.eat(0x28 /* ( */)) { if (this.options.ecmaVersion >= 9) { this.regexp_groupSpecifier(state); } else if (state.current() === 0x3F /* ? */) { state.raise("Invalid group"); } this.regexp_disjunction(state); if (state.eat(0x29 /* ) */)) { state.numCapturingParens += 1; return true } state.raise("Unterminated group"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom pp$1.regexp_eatExtendedAtom = function(state) { return ( state.eat(0x2E /* . */) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state) ) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier pp$1.regexp_eatInvalidBracedQuantifier = function(state) { if (this.regexp_eatBracedQuantifier(state, true)) { state.raise("Nothing to repeat"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter pp$1.regexp_eatSyntaxCharacter = function(state) { var ch = state.current(); if (isSyntaxCharacter(ch)) { state.lastIntValue = ch; state.advance(); return true } return false }; function isSyntaxCharacter(ch) { return ( ch === 0x24 /* $ */ || ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || ch === 0x2E /* . */ || ch === 0x3F /* ? */ || ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || ch >= 0x7B /* { */ && ch <= 0x7D /* } */ ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter // But eat eager. pp$1.regexp_eatPatternCharacters = function(state) { var start = state.pos; var ch = 0; while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { state.advance(); } return state.pos !== start }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter pp$1.regexp_eatExtendedPatternCharacter = function(state) { var ch = state.current(); if ( ch !== -1 && ch !== 0x24 /* $ */ && !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && ch !== 0x2E /* . */ && ch !== 0x3F /* ? */ && ch !== 0x5B /* [ */ && ch !== 0x5E /* ^ */ && ch !== 0x7C /* | */ ) { state.advance(); return true } return false }; // GroupSpecifier :: // [empty] // `?` GroupName pp$1.regexp_groupSpecifier = function(state) { if (state.eat(0x3F /* ? */)) { if (this.regexp_eatGroupName(state)) { if (state.groupNames.indexOf(state.lastStringValue) !== -1) { state.raise("Duplicate capture group name"); } state.groupNames.push(state.lastStringValue); return } state.raise("Invalid group"); } }; // GroupName :: // `<` RegExpIdentifierName `>` // Note: this updates `state.lastStringValue` property with the eaten name. pp$1.regexp_eatGroupName = function(state) { state.lastStringValue = ""; if (state.eat(0x3C /* < */)) { if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { return true } state.raise("Invalid capture group name"); } return false }; // RegExpIdentifierName :: // RegExpIdentifierStart // RegExpIdentifierName RegExpIdentifierPart // Note: this updates `state.lastStringValue` property with the eaten name. pp$1.regexp_eatRegExpIdentifierName = function(state) { state.lastStringValue = ""; if (this.regexp_eatRegExpIdentifierStart(state)) { state.lastStringValue += codePointToString(state.lastIntValue); while (this.regexp_eatRegExpIdentifierPart(state)) { state.lastStringValue += codePointToString(state.lastIntValue); } return true } return false }; // RegExpIdentifierStart :: // UnicodeIDStart // `$` // `_` // `\` RegExpUnicodeEscapeSequence[+U] pp$1.regexp_eatRegExpIdentifierStart = function(state) { var start = state.pos; var forceU = this.options.ecmaVersion >= 11; var ch = state.current(forceU); state.advance(forceU); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue; } if (isRegExpIdentifierStart(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierStart(ch) { return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ } // RegExpIdentifierPart :: // UnicodeIDContinue // `$` // `_` // `\` RegExpUnicodeEscapeSequence[+U] // // pp$1.regexp_eatRegExpIdentifierPart = function(state) { var start = state.pos; var forceU = this.options.ecmaVersion >= 11; var ch = state.current(forceU); state.advance(forceU); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { ch = state.lastIntValue; } if (isRegExpIdentifierPart(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierPart(ch) { return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape pp$1.regexp_eatAtomEscape = function(state) { if ( this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || (state.switchN && this.regexp_eatKGroupName(state)) ) { return true } if (state.switchU) { // Make the same message as V8. if (state.current() === 0x63 /* c */) { state.raise("Invalid unicode escape"); } state.raise("Invalid escape"); } return false }; pp$1.regexp_eatBackReference = function(state) { var start = state.pos; if (this.regexp_eatDecimalEscape(state)) { var n = state.lastIntValue; if (state.switchU) { // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape if (n > state.maxBackReference) { state.maxBackReference = n; } return true } if (n <= state.numCapturingParens) { return true } state.pos = start; } return false }; pp$1.regexp_eatKGroupName = function(state) { if (state.eat(0x6B /* k */)) { if (this.regexp_eatGroupName(state)) { state.backReferenceNames.push(state.lastStringValue); return true } state.raise("Invalid named reference"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape pp$1.regexp_eatCharacterEscape = function(state) { return ( this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || this.regexp_eatIdentityEscape(state) ) }; pp$1.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$1.regexp_eatZero = function(state) { if (state.current() === 0x30 /* 0 */ && !isDecimalDigit$1(state.lookahead())) { state.lastIntValue = 0; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape pp$1.regexp_eatControlEscape = function(state) { var ch = state.current(); if (ch === 0x74 /* t */) { state.lastIntValue = 0x09; /* \t */ state.advance(); return true } if (ch === 0x6E /* n */) { state.lastIntValue = 0x0A; /* \n */ state.advance(); return true } if (ch === 0x76 /* v */) { state.lastIntValue = 0x0B; /* \v */ state.advance(); return true } if (ch === 0x66 /* f */) { state.lastIntValue = 0x0C; /* \f */ state.advance(); return true } if (ch === 0x72 /* r */) { state.lastIntValue = 0x0D; /* \r */ state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter pp$1.regexp_eatControlLetter = function(state) { var ch = state.current(); if (isControlLetter(ch)) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; function isControlLetter(ch) { return ( (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { if ( forceU === void 0 ) forceU = false; var start = state.pos; var switchU = forceU || state.switchU; if (state.eat(0x75 /* u */)) { if (this.regexp_eatFixedHexDigits(state, 4)) { var lead = state.lastIntValue; if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { var leadSurrogateEnd = state.pos; if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { var trail = state.lastIntValue; if (trail >= 0xDC00 && trail <= 0xDFFF) { state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; return true } } state.pos = leadSurrogateEnd; state.lastIntValue = lead; } return true } if ( switchU && state.eat(0x7B /* { */) && this.regexp_eatHexDigits(state) && state.eat(0x7D /* } */) && isValidUnicode(state.lastIntValue) ) { return true } if (switchU) { state.raise("Invalid unicode escape"); } state.pos = start; } return false }; function isValidUnicode(ch) { return ch >= 0 && ch <= 0x10FFFF } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape pp$1.regexp_eatIdentityEscape = function(state) { if (state.switchU) { if (this.regexp_eatSyntaxCharacter(state)) { return true } if (state.eat(0x2F /* / */)) { state.lastIntValue = 0x2F; /* / */ return true } return false } var ch = state.current(); if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { state.lastIntValue = ch; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape pp$1.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 }; // Return values used by character set parsing methods, needed to // forbid negation of sets that can match strings. var CharSetNone = 0; // Nothing parsed var CharSetOk = 1; // Construct parsed, cannot contain strings var CharSetString = 2; // Construct parsed, can contain strings // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape pp$1.regexp_eatCharacterClassEscape = function(state) { var ch = state.current(); if (isCharacterClassEscape(ch)) { state.lastIntValue = -1; state.advance(); return CharSetOk } var negate = false; if ( state.switchU && this.options.ecmaVersion >= 9 && ((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */) ) { state.lastIntValue = -1; state.advance(); var result; if ( state.eat(0x7B /* { */) && (result = this.regexp_eatUnicodePropertyValueExpression(state)) && state.eat(0x7D /* } */) ) { if (negate && result === CharSetString) { state.raise("Invalid property name"); } return result } state.raise("Invalid property name"); } return CharSetNone }; function isCharacterClassEscape(ch) { return ( ch === 0x64 /* d */ || ch === 0x44 /* D */ || ch === 0x73 /* s */ || ch === 0x53 /* S */ || ch === 0x77 /* w */ || ch === 0x57 /* W */ ) } // UnicodePropertyValueExpression :: // UnicodePropertyName `=` UnicodePropertyValue // LoneUnicodePropertyNameOrValue pp$1.regexp_eatUnicodePropertyValueExpression = function(state) { var start = state.pos; // UnicodePropertyName `=` UnicodePropertyValue if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { var name = state.lastStringValue; if (this.regexp_eatUnicodePropertyValue(state)) { var value = state.lastStringValue; this.regexp_validateUnicodePropertyNameAndValue(state, name, value); return CharSetOk } } state.pos = start; // LoneUnicodePropertyNameOrValue if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { var nameOrValue = state.lastStringValue; return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue) } return CharSetNone }; pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { if (!hasOwn(state.unicodeProperties.nonBinary, name)) { state.raise("Invalid property name"); } if (!state.unicodeProperties.nonBinary[name].test(value)) { state.raise("Invalid property value"); } }; pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk } if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString } state.raise("Invalid property name"); }; // UnicodePropertyName :: // UnicodePropertyNameCharacters pp$1.regexp_eatUnicodePropertyName = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyNameCharacter(ch = state.current())) { state.lastStringValue += codePointToString(ch); state.advance(); } return state.lastStringValue !== "" }; function isUnicodePropertyNameCharacter(ch) { return isControlLetter(ch) || ch === 0x5F /* _ */ } // UnicodePropertyValue :: // UnicodePropertyValueCharacters pp$1.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$1(ch) } // LoneUnicodePropertyNameOrValue :: // UnicodePropertyValueCharacters pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { return this.regexp_eatUnicodePropertyValue(state) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass pp$1.regexp_eatCharacterClass = function(state) { if (state.eat(0x5B /* [ */)) { var negate = state.eat(0x5E /* ^ */); var result = this.regexp_classContents(state); if (!state.eat(0x5D /* ] */)) { state.raise("Unterminated character class"); } if (negate && result === CharSetString) { state.raise("Negated character class may contain strings"); } return true } return false }; // https://tc39.es/ecma262/#prod-ClassContents // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges pp$1.regexp_classContents = function(state) { if (state.current() === 0x5D /* ] */) { return CharSetOk } if (state.switchV) { return this.regexp_classSetExpression(state) } this.regexp_nonEmptyClassRanges(state); return CharSetOk }; // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash pp$1.regexp_nonEmptyClassRanges = function(state) { while (this.regexp_eatClassAtom(state)) { var left = state.lastIntValue; if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { var right = state.lastIntValue; if (state.switchU && (left === -1 || right === -1)) { state.raise("Invalid character class"); } if (left !== -1 && right !== -1 && left > right) { state.raise("Range out of order in character class"); } } } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash pp$1.regexp_eatClassAtom = function(state) { var start = state.pos; if (state.eat(0x5C /* \ */)) { if (this.regexp_eatClassEscape(state)) { return true } if (state.switchU) { // Make the same message as V8. var ch$1 = state.current(); if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { state.raise("Invalid class escape"); } state.raise("Invalid escape"); } state.pos = start; } var ch = state.current(); if (ch !== 0x5D /* ] */) { state.lastIntValue = ch; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape pp$1.regexp_eatClassEscape = function(state) { var start = state.pos; if (state.eat(0x62 /* b */)) { state.lastIntValue = 0x08; /* */ return true } if (state.switchU && state.eat(0x2D /* - */)) { state.lastIntValue = 0x2D; /* - */ return true } if (!state.switchU && state.eat(0x63 /* c */)) { if (this.regexp_eatClassControlLetter(state)) { return true } state.pos = start; } return ( this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) ) }; // https://tc39.es/ecma262/#prod-ClassSetExpression // https://tc39.es/ecma262/#prod-ClassUnion // https://tc39.es/ecma262/#prod-ClassIntersection // https://tc39.es/ecma262/#prod-ClassSubtraction pp$1.regexp_classSetExpression = function(state) { var result = CharSetOk, subResult; if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) { if (subResult === CharSetString) { result = CharSetString; } // https://tc39.es/ecma262/#prod-ClassIntersection var start = state.pos; while (state.eatChars([0x26, 0x26] /* && */)) { if ( state.current() !== 0x26 /* & */ && (subResult = this.regexp_eatClassSetOperand(state)) ) { if (subResult !== CharSetString) { result = CharSetOk; } continue } state.raise("Invalid character in character class"); } if (start !== state.pos) { return result } // https://tc39.es/ecma262/#prod-ClassSubtraction while (state.eatChars([0x2D, 0x2D] /* -- */)) { if (this.regexp_eatClassSetOperand(state)) { continue } state.raise("Invalid character in character class"); } if (start !== state.pos) { return result } } else { state.raise("Invalid character in character class"); } // https://tc39.es/ecma262/#prod-ClassUnion for (;;) { if (this.regexp_eatClassSetRange(state)) { continue } subResult = this.regexp_eatClassSetOperand(state); if (!subResult) { return result } if (subResult === CharSetString) { result = CharSetString; } } }; // https://tc39.es/ecma262/#prod-ClassSetRange pp$1.regexp_eatClassSetRange = function(state) { var start = state.pos; if (this.regexp_eatClassSetCharacter(state)) { var left = state.lastIntValue; if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) { var right = state.lastIntValue; if (left !== -1 && right !== -1 && left > right) { state.raise("Range out of order in character class"); } return true } state.pos = start; } return false }; // https://tc39.es/ecma262/#prod-ClassSetOperand pp$1.regexp_eatClassSetOperand = function(state) { if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk } return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state) }; // https://tc39.es/ecma262/#prod-NestedClass pp$1.regexp_eatNestedClass = function(state) { var start = state.pos; if (state.eat(0x5B /* [ */)) { var negate = state.eat(0x5E /* ^ */); var result = this.regexp_classContents(state); if (state.eat(0x5D /* ] */)) { if (negate && result === CharSetString) { state.raise("Negated character class may contain strings"); } return result } state.pos = start; } if (state.eat(0x5C /* \ */)) { var result$1 = this.regexp_eatCharacterClassEscape(state); if (result$1) { return result$1 } state.pos = start; } return null }; // https://tc39.es/ecma262/#prod-ClassStringDisjunction pp$1.regexp_eatClassStringDisjunction = function(state) { var start = state.pos; if (state.eatChars([0x5C, 0x71] /* \q */)) { if (state.eat(0x7B /* { */)) { var result = this.regexp_classStringDisjunctionContents(state); if (state.eat(0x7D /* } */)) { return result } } else { // Make the same message as V8. state.raise("Invalid escape"); } state.pos = start; } return null }; // https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents pp$1.regexp_classStringDisjunctionContents = function(state) { var result = this.regexp_classString(state); while (state.eat(0x7C /* | */)) { if (this.regexp_classString(state) === CharSetString) { result = CharSetString; } } return result }; // https://tc39.es/ecma262/#prod-ClassString // https://tc39.es/ecma262/#prod-NonEmptyClassString pp$1.regexp_classString = function(state) { var count = 0; while (this.regexp_eatClassSetCharacter(state)) { count++; } return count === 1 ? CharSetOk : CharSetString }; // https://tc39.es/ecma262/#prod-ClassSetCharacter pp$1.regexp_eatClassSetCharacter = function(state) { var start = state.pos; if (state.eat(0x5C /* \ */)) { if ( this.regexp_eatCharacterEscape(state) || this.regexp_eatClassSetReservedPunctuator(state) ) { return true } if (state.eat(0x62 /* b */)) { state.lastIntValue = 0x08; /* */ return true } state.pos = start; return false } var ch = state.current(); if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { return false } if (isClassSetSyntaxCharacter(ch)) { return false } state.advance(); state.lastIntValue = ch; return true }; // https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator function isClassSetReservedDoublePunctuatorCharacter(ch) { return ( ch === 0x21 /* ! */ || ch >= 0x23 /* # */ && ch <= 0x26 /* & */ || ch >= 0x2A /* * */ && ch <= 0x2C /* , */ || ch === 0x2E /* . */ || ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ || ch === 0x5E /* ^ */ || ch === 0x60 /* ` */ || ch === 0x7E /* ~ */ ) } // https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter function isClassSetSyntaxCharacter(ch) { return ( ch === 0x28 /* ( */ || ch === 0x29 /* ) */ || ch === 0x2D /* - */ || ch === 0x2F /* / */ || ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ || ch >= 0x7B /* { */ && ch <= 0x7D /* } */ ) } // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator pp$1.regexp_eatClassSetReservedPunctuator = function(state) { var ch = state.current(); if (isClassSetReservedPunctuator(ch)) { state.lastIntValue = ch; state.advance(); return true } return false }; // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator function isClassSetReservedPunctuator(ch) { return ( ch === 0x21 /* ! */ || ch === 0x23 /* # */ || ch === 0x25 /* % */ || ch === 0x26 /* & */ || ch === 0x2C /* , */ || ch === 0x2D /* - */ || ch >= 0x3A /* : */ && ch <= 0x3E /* > */ || ch === 0x40 /* @ */ || ch === 0x60 /* ` */ || ch === 0x7E /* ~ */ ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter pp$1.regexp_eatClassControlLetter = function(state) { var ch = state.current(); if (isDecimalDigit$1(ch) || ch === 0x5F /* _ */) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp$1.regexp_eatHexEscapeSequence = function(state) { var start = state.pos; if (state.eat(0x78 /* x */)) { if (this.regexp_eatFixedHexDigits(state, 2)) { return true } if (state.switchU) { state.raise("Invalid escape"); } state.pos = start; } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits pp$1.regexp_eatDecimalDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isDecimalDigit$1(ch = state.current())) { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); state.advance(); } return state.pos !== start }; function isDecimalDigit$1(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits pp$1.regexp_eatHexDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isHexDigit$1(ch = state.current())) { state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance(); } return state.pos !== start }; function isHexDigit$1(ch) { return ( (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) ) } function hexToInt(ch) { if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { return 10 + (ch - 0x41 /* A */) } if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { return 10 + (ch - 0x61 /* a */) } return ch - 0x30 /* 0 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence // Allows only 0-377(octal) i.e. 0-255(decimal). pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) { if (this.regexp_eatOctalDigit(state)) { var n1 = state.lastIntValue; if (this.regexp_eatOctalDigit(state)) { var n2 = state.lastIntValue; if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; } else { state.lastIntValue = n1 * 8 + n2; } } else { state.lastIntValue = n1; } return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit pp$1.regexp_eatOctalDigit = function(state) { var ch = state.current(); if (isOctalDigit(ch)) { state.lastIntValue = ch - 0x30; /* 0 */ state.advance(); return true } state.lastIntValue = 0; return false }; function isOctalDigit(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp$1.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$1(ch)) { state.pos = start; return false } state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance(); } return true }; // Object type used to represent tokens. Note that normally, tokens // simply exist as properties on the parser object. This is only // used for the onToken callback and the external tokenizer. var Token$1 = function Token(p) { this.type = p.type; this.value = p.value; this.start = p.start; this.end = p.end; if (p.options.locations) { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } if (p.options.ranges) { this.range = [p.start, p.end]; } }; // ## Tokenizer var pp = Parser$1.prototype; // Move to the next token pp.next = function(ignoreEscapeSequenceInKeyword) { if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } if (this.options.onToken) { this.options.onToken(new Token$1(this)); } this.lastTokEnd = this.end; this.lastTokStart = this.start; this.lastTokEndLoc = this.endLoc; this.lastTokStartLoc = this.startLoc; this.nextToken(); }; pp.getToken = function() { this.next(); return new Token$1(this) }; // If we're in an ES6 environment, make parsers iterable if (typeof Symbol !== "undefined") { pp[Symbol.iterator] = function() { var this$1$1 = this; return { next: function () { var token = this$1$1.getToken(); return { done: token.type === types$1.eof, value: token } } } }; } // Toggle strict mode. Re-reads the next number or string to please // pedantic tests (`"use strict"; 010;` should fail). // Read a single token, updating the parser object's token-related // properties. pp.nextToken = function() { var curContext = this.curContext(); if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } this.start = this.pos; if (this.options.locations) { this.startLoc = this.curPosition(); } if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) } if (curContext.override) { return curContext.override(this) } else { this.readToken(this.fullCharCodeAtPos()); } }; pp.readToken = function(code) { // Identifier or keyword. '\uXXXX' sequences are allowed in // identifiers, so '\' also dispatches to that. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) { return this.readWord() } return this.getTokenFromCode(code) }; pp.fullCharCodeAtPos = function() { var code = this.input.charCodeAt(this.pos); if (code <= 0xd7ff || code >= 0xdc00) { return code } var next = this.input.charCodeAt(this.pos + 1); return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 }; pp.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) { for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) { ++this.curLine; pos = this.lineStart = nextBreak; } } if (this.options.onComment) { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition()); } }; pp.skipLineComment = function(startSkip) { var start = this.pos; var startLoc = this.options.onComment && this.curPosition(); var ch = this.input.charCodeAt(this.pos += startSkip); while (this.pos < this.input.length && !isNewLine(ch)) { ch = this.input.charCodeAt(++this.pos); } if (this.options.onComment) { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition()); } }; // Called at the start of the parse and after every token. Skips // whitespace and comments, and. pp.skipSpace = function() { loop: while (this.pos < this.input.length) { var ch = this.input.charCodeAt(this.pos); switch (ch) { case 32: case 160: // ' ' ++this.pos; break case 13: if (this.input.charCodeAt(this.pos + 1) === 10) { ++this.pos; } case 10: case 8232: case 8233: ++this.pos; if (this.options.locations) { ++this.curLine; this.lineStart = this.pos; } break case 47: // '/' switch (this.input.charCodeAt(this.pos + 1)) { case 42: // '*' this.skipBlockComment(); break case 47: this.skipLineComment(2); break default: break loop } break default: if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { ++this.pos; } else { break loop } } } }; // Called at the end of every token. Sets `end`, `val`, and // maintains `context` and `exprAllowed`, and skips the space after // the token, so that the next one's `start` will point at the // right position. pp.finishToken = function(type, val) { this.end = this.pos; if (this.options.locations) { this.endLoc = this.curPosition(); } var prevType = this.type; this.type = type; this.value = val; this.updateContext(prevType); }; // ### Token reading // This is the function that is called to fetch the next token. It // is somewhat obscure, because it works in character codes rather // than characters, and because operator parsing has been inlined // into it. // // All in the name of speed. // pp.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$1.ellipsis) } else { ++this.pos; return this.finishToken(types$1.dot) } }; pp.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$1.assign, 2) } return this.finishOp(types$1.slash, 1) }; pp.readToken_mult_modulo_exp = function(code) { // '%*' var next = this.input.charCodeAt(this.pos + 1); var size = 1; var tokentype = code === 42 ? types$1.star : types$1.modulo; // exponentiation operator ** and **= if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { ++size; tokentype = types$1.starstar; next = this.input.charCodeAt(this.pos + 2); } if (next === 61) { return this.finishOp(types$1.assign, size + 1) } return this.finishOp(tokentype, size) }; pp.readToken_pipe_amp = function(code) { // '|&' var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (this.options.ecmaVersion >= 12) { var next2 = this.input.charCodeAt(this.pos + 2); if (next2 === 61) { return this.finishOp(types$1.assign, 3) } } return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2) } if (next === 61) { return this.finishOp(types$1.assign, 2) } return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1) }; pp.readToken_caret = function() { // '^' var next = this.input.charCodeAt(this.pos + 1); if (next === 61) { return this.finishOp(types$1.assign, 2) } return this.finishOp(types$1.bitwiseXOR, 1) }; pp.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$1.incDec, 2) } if (next === 61) { return this.finishOp(types$1.assign, 2) } return this.finishOp(types$1.plusMin, 1) }; pp.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$1.assign, size + 1) } return this.finishOp(types$1.bitShift, size) } if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) { // `|close frame|-->|ws.close()|- - - * | +----------+ +-----------+ +----------+ | * +----------+ +-----------+ | * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING * +----------+ +-----------+ | * | | | +---+ | * +------------------------+-->|fin| - - - - * | +---+ | +---+ * - - - - -|fin|<---------------------+ * +---+ * * @param {Number} [code] Status code explaining why the connection is closing * @param {(String|Buffer)} [data] The reason why the connection is * closing * @public */ close(code, data) { if (this.readyState === WebSocket.CLOSED) return; if (this.readyState === WebSocket.CONNECTING) { const msg = 'WebSocket was closed before the connection was established'; abortHandshake$1(this, this._req, msg); return; } if (this.readyState === WebSocket.CLOSING) { if ( this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted) ) { this._socket.end(); } return; } this._readyState = WebSocket.CLOSING; this._sender.close(code, data, !this._isServer, (err) => { // // This error is handled by the `'error'` listener on the socket. We only // want to know if the close frame has been sent here. // if (err) return; this._closeFrameSent = true; if ( this._closeFrameReceived || this._receiver._writableState.errorEmitted ) { this._socket.end(); } }); // // Specify a timeout for the closing handshake to complete. // this._closeTimer = setTimeout( this._socket.destroy.bind(this._socket), closeTimeout ); } /** * Pause the socket. * * @public */ pause() { if ( this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED ) { return; } this._paused = true; this._socket.pause(); } /** * Send a ping. * * @param {*} [data] The data to send * @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Function} [cb] Callback which is executed when the ping is sent * @public */ ping(data, mask, cb) { if (this.readyState === WebSocket.CONNECTING) { throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); } if (typeof data === 'function') { cb = data; data = mask = undefined; } else if (typeof mask === 'function') { cb = mask; mask = undefined; } if (typeof data === 'number') data = data.toString(); if (this.readyState !== WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === undefined) mask = !this._isServer; this._sender.ping(data || EMPTY_BUFFER, mask, cb); } /** * Send a pong. * * @param {*} [data] The data to send * @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Function} [cb] Callback which is executed when the pong is sent * @public */ pong(data, mask, cb) { if (this.readyState === WebSocket.CONNECTING) { throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); } if (typeof data === 'function') { cb = data; data = mask = undefined; } else if (typeof mask === 'function') { cb = mask; mask = undefined; } if (typeof data === 'number') data = data.toString(); if (this.readyState !== WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === undefined) mask = !this._isServer; this._sender.pong(data || EMPTY_BUFFER, mask, cb); } /** * Resume the socket. * * @public */ resume() { if ( this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED ) { return; } this._paused = false; if (!this._receiver._writableState.needDrain) this._socket.resume(); } /** * Send a data message. * * @param {*} data The message to send * @param {Object} [options] Options object * @param {Boolean} [options.binary] Specifies whether `data` is binary or * text * @param {Boolean} [options.compress] Specifies whether or not to compress * `data` * @param {Boolean} [options.fin=true] Specifies whether the fragment is the * last one * @param {Boolean} [options.mask] Specifies whether or not to mask `data` * @param {Function} [cb] Callback which is executed when data is written out * @public */ send(data, options, cb) { if (this.readyState === WebSocket.CONNECTING) { throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); } if (typeof options === 'function') { cb = options; options = {}; } if (typeof data === 'number') data = data.toString(); if (this.readyState !== WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } const opts = { binary: typeof data !== 'string', mask: !this._isServer, compress: true, fin: true, ...options }; if (!this._extensions[PerMessageDeflate$1.extensionName]) { opts.compress = false; } this._sender.send(data || EMPTY_BUFFER, opts, cb); } /** * Forcibly close the connection. * * @public */ terminate() { if (this.readyState === WebSocket.CLOSED) return; if (this.readyState === WebSocket.CONNECTING) { const msg = 'WebSocket was closed before the connection was established'; abortHandshake$1(this, this._req, msg); return; } if (this._socket) { this._readyState = WebSocket.CLOSING; this._socket.destroy(); } } }; /** * @constant {Number} CONNECTING * @memberof WebSocket */ Object.defineProperty(WebSocket$1, 'CONNECTING', { enumerable: true, value: readyStates.indexOf('CONNECTING') }); /** * @constant {Number} CONNECTING * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket$1.prototype, 'CONNECTING', { enumerable: true, value: readyStates.indexOf('CONNECTING') }); /** * @constant {Number} OPEN * @memberof WebSocket */ Object.defineProperty(WebSocket$1, 'OPEN', { enumerable: true, value: readyStates.indexOf('OPEN') }); /** * @constant {Number} OPEN * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket$1.prototype, 'OPEN', { enumerable: true, value: readyStates.indexOf('OPEN') }); /** * @constant {Number} CLOSING * @memberof WebSocket */ Object.defineProperty(WebSocket$1, 'CLOSING', { enumerable: true, value: readyStates.indexOf('CLOSING') }); /** * @constant {Number} CLOSING * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket$1.prototype, 'CLOSING', { enumerable: true, value: readyStates.indexOf('CLOSING') }); /** * @constant {Number} CLOSED * @memberof WebSocket */ Object.defineProperty(WebSocket$1, 'CLOSED', { enumerable: true, value: readyStates.indexOf('CLOSED') }); /** * @constant {Number} CLOSED * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket$1.prototype, 'CLOSED', { enumerable: true, value: readyStates.indexOf('CLOSED') }); [ 'binaryType', 'bufferedAmount', 'extensions', 'isPaused', 'protocol', 'readyState', 'url' ].forEach((property) => { Object.defineProperty(WebSocket$1.prototype, property, { enumerable: true }); }); // // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface // ['open', 'error', 'close', 'message'].forEach((method) => { Object.defineProperty(WebSocket$1.prototype, `on${method}`, { enumerable: true, get() { for (const listener of this.listeners(method)) { if (listener[kForOnEventAttribute]) return listener[kListener]; } return null; }, set(handler) { for (const listener of this.listeners(method)) { if (listener[kForOnEventAttribute]) { this.removeListener(method, listener); break; } } if (typeof handler !== 'function') return; this.addEventListener(method, handler, { [kForOnEventAttribute]: true }); } }); }); WebSocket$1.prototype.addEventListener = addEventListener; WebSocket$1.prototype.removeEventListener = removeEventListener; var websocket = WebSocket$1; /** * Initialize a WebSocket client. * * @param {WebSocket} websocket The client to initialize * @param {(String|URL)} address The URL to which to connect * @param {Array} protocols The subprotocols * @param {Object} [options] Connection options * @param {Boolean} [options.followRedirects=false] Whether or not to follow * redirects * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the * handshake request * @param {Number} [options.maxPayload=104857600] The maximum allowed message * size * @param {Number} [options.maxRedirects=10] The maximum number of redirects * allowed * @param {String} [options.origin] Value of the `Origin` or * `Sec-WebSocket-Origin` header * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable * permessage-deflate * @param {Number} [options.protocolVersion=13] Value of the * `Sec-WebSocket-Version` header * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages * @private */ function initAsClient(websocket, address, protocols, options) { const opts = { protocolVersion: protocolVersions[1], maxPayload: 100 * 1024 * 1024, skipUTF8Validation: false, perMessageDeflate: true, followRedirects: false, maxRedirects: 10, ...options, createConnection: undefined, socketPath: undefined, hostname: undefined, protocol: undefined, timeout: undefined, method: 'GET', host: undefined, path: undefined, port: undefined }; if (!protocolVersions.includes(opts.protocolVersion)) { throw new RangeError( `Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(', ')})` ); } let parsedUrl; if (address instanceof URL$2) { parsedUrl = address; websocket._url = address.href; } else { try { parsedUrl = new URL$2(address); } catch (e) { throw new SyntaxError(`Invalid URL: ${address}`); } websocket._url = address; } const isSecure = parsedUrl.protocol === 'wss:'; const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; let invalidUrlMessage; if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { invalidUrlMessage = 'The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"'; } else if (isIpcUrl && !parsedUrl.pathname) { invalidUrlMessage = "The URL's pathname is empty"; } else if (parsedUrl.hash) { invalidUrlMessage = 'The URL contains a fragment identifier'; } if (invalidUrlMessage) { const err = new SyntaxError(invalidUrlMessage); if (websocket._redirects === 0) { throw err; } else { emitErrorAndClose(websocket, err); return; } } const defaultPort = isSecure ? 443 : 80; const key = randomBytes(16).toString('base64'); const request = isSecure ? https$2.request : http$3.request; const protocolSet = new Set(); let perMessageDeflate; opts.createConnection = isSecure ? tlsConnect : netConnect; opts.defaultPort = opts.defaultPort || defaultPort; opts.port = parsedUrl.port || defaultPort; opts.host = parsedUrl.hostname.startsWith('[') ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; opts.headers = { ...opts.headers, 'Sec-WebSocket-Version': opts.protocolVersion, 'Sec-WebSocket-Key': key, Connection: 'Upgrade', Upgrade: 'websocket' }; opts.path = parsedUrl.pathname + parsedUrl.search; opts.timeout = opts.handshakeTimeout; if (opts.perMessageDeflate) { perMessageDeflate = new PerMessageDeflate$1( opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, false, opts.maxPayload ); opts.headers['Sec-WebSocket-Extensions'] = format({ [PerMessageDeflate$1.extensionName]: perMessageDeflate.offer() }); } if (protocols.length) { for (const protocol of protocols) { if ( typeof protocol !== 'string' || !subprotocolRegex.test(protocol) || protocolSet.has(protocol) ) { throw new SyntaxError( 'An invalid or duplicated subprotocol was specified' ); } protocolSet.add(protocol); } opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); } if (opts.origin) { if (opts.protocolVersion < 13) { opts.headers['Sec-WebSocket-Origin'] = opts.origin; } else { opts.headers.Origin = opts.origin; } } if (parsedUrl.username || parsedUrl.password) { opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; } if (isIpcUrl) { const parts = opts.path.split(':'); opts.socketPath = parts[0]; opts.path = parts[1]; } let req; if (opts.followRedirects) { if (websocket._redirects === 0) { websocket._originalIpc = isIpcUrl; websocket._originalSecure = isSecure; websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host; const headers = options && options.headers; // // Shallow copy the user provided options so that headers can be changed // without mutating the original object. // options = { ...options, headers: {} }; if (headers) { for (const [key, value] of Object.entries(headers)) { options.headers[key.toLowerCase()] = value; } } } else if (websocket.listenerCount('redirect') === 0) { const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath; if (!isSameHost || (websocket._originalSecure && !isSecure)) { // // Match curl 7.77.0 behavior and drop the following headers. These // headers are also dropped when following a redirect to a subdomain. // delete opts.headers.authorization; delete opts.headers.cookie; if (!isSameHost) delete opts.headers.host; opts.auth = undefined; } } // // Match curl 7.77.0 behavior and make the first `Authorization` header win. // If the `Authorization` header is set, then there is nothing to do as it // will take precedence. // if (opts.auth && !options.headers.authorization) { options.headers.authorization = 'Basic ' + Buffer.from(opts.auth).toString('base64'); } req = websocket._req = request(opts); if (websocket._redirects) { // // Unlike what is done for the `'upgrade'` event, no early exit is // triggered here if the user calls `websocket.close()` or // `websocket.terminate()` from a listener of the `'redirect'` event. This // is because the user can also call `request.destroy()` with an error // before calling `websocket.close()` or `websocket.terminate()` and this // would result in an error being emitted on the `request` object with no // `'error'` event listeners attached. // websocket.emit('redirect', websocket.url, req); } } else { req = websocket._req = request(opts); } if (opts.timeout) { req.on('timeout', () => { abortHandshake$1(websocket, req, 'Opening handshake has timed out'); }); } req.on('error', (err) => { if (req === null || req[kAborted]) return; req = websocket._req = null; emitErrorAndClose(websocket, err); }); req.on('response', (res) => { const location = res.headers.location; const statusCode = res.statusCode; if ( location && opts.followRedirects && statusCode >= 300 && statusCode < 400 ) { if (++websocket._redirects > opts.maxRedirects) { abortHandshake$1(websocket, req, 'Maximum redirects exceeded'); return; } req.abort(); let addr; try { addr = new URL$2(location, address); } catch (e) { const err = new SyntaxError(`Invalid URL: ${location}`); emitErrorAndClose(websocket, err); return; } initAsClient(websocket, addr, protocols, options); } else if (!websocket.emit('unexpected-response', req, res)) { abortHandshake$1( websocket, req, `Unexpected server response: ${res.statusCode}` ); } }); req.on('upgrade', (res, socket, head) => { websocket.emit('upgrade', res); // // The user may have closed the connection from a listener of the // `'upgrade'` event. // if (websocket.readyState !== WebSocket$1.CONNECTING) return; req = websocket._req = null; if (res.headers.upgrade.toLowerCase() !== 'websocket') { abortHandshake$1(websocket, socket, 'Invalid Upgrade header'); return; } const digest = createHash$1('sha1') .update(key + GUID$1) .digest('base64'); if (res.headers['sec-websocket-accept'] !== digest) { abortHandshake$1(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); return; } const serverProt = res.headers['sec-websocket-protocol']; let protError; if (serverProt !== undefined) { if (!protocolSet.size) { protError = 'Server sent a subprotocol but none was requested'; } else if (!protocolSet.has(serverProt)) { protError = 'Server sent an invalid subprotocol'; } } else if (protocolSet.size) { protError = 'Server sent no subprotocol'; } if (protError) { abortHandshake$1(websocket, socket, protError); return; } if (serverProt) websocket._protocol = serverProt; const secWebSocketExtensions = res.headers['sec-websocket-extensions']; if (secWebSocketExtensions !== undefined) { if (!perMessageDeflate) { const message = 'Server sent a Sec-WebSocket-Extensions header but no extension ' + 'was requested'; abortHandshake$1(websocket, socket, message); return; } let extensions; try { extensions = parse$1$1(secWebSocketExtensions); } catch (err) { const message = 'Invalid Sec-WebSocket-Extensions header'; abortHandshake$1(websocket, socket, message); return; } const extensionNames = Object.keys(extensions); if ( extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate$1.extensionName ) { const message = 'Server indicated an extension that was not requested'; abortHandshake$1(websocket, socket, message); return; } try { perMessageDeflate.accept(extensions[PerMessageDeflate$1.extensionName]); } catch (err) { const message = 'Invalid Sec-WebSocket-Extensions header'; abortHandshake$1(websocket, socket, message); return; } websocket._extensions[PerMessageDeflate$1.extensionName] = perMessageDeflate; } websocket.setSocket(socket, head, { generateMask: opts.generateMask, maxPayload: opts.maxPayload, skipUTF8Validation: opts.skipUTF8Validation }); }); if (opts.finishRequest) { opts.finishRequest(req, websocket); } else { req.end(); } } /** * Emit the `'error'` and `'close'` events. * * @param {WebSocket} websocket The WebSocket instance * @param {Error} The error to emit * @private */ function emitErrorAndClose(websocket, err) { websocket._readyState = WebSocket$1.CLOSING; websocket.emit('error', err); websocket.emitClose(); } /** * Create a `net.Socket` and initiate a connection. * * @param {Object} options Connection options * @return {net.Socket} The newly created socket used to start the connection * @private */ function netConnect(options) { options.path = options.socketPath; return net.connect(options); } /** * Create a `tls.TLSSocket` and initiate a connection. * * @param {Object} options Connection options * @return {tls.TLSSocket} The newly created socket used to start the connection * @private */ function tlsConnect(options) { options.path = undefined; if (!options.servername && options.servername !== '') { options.servername = net.isIP(options.host) ? '' : options.host; } return tls.connect(options); } /** * Abort the handshake and emit an error. * * @param {WebSocket} websocket The WebSocket instance * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to * abort or the socket to destroy * @param {String} message The error message * @private */ function abortHandshake$1(websocket, stream, message) { websocket._readyState = WebSocket$1.CLOSING; const err = new Error(message); Error.captureStackTrace(err, abortHandshake$1); if (stream.setHeader) { stream[kAborted] = true; stream.abort(); if (stream.socket && !stream.socket.destroyed) { // // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if // called after the request completed. See // https://github.com/websockets/ws/issues/1869. // stream.socket.destroy(); } process.nextTick(emitErrorAndClose, websocket, err); } else { stream.destroy(err); stream.once('error', websocket.emit.bind(websocket, 'error')); stream.once('close', websocket.emitClose.bind(websocket)); } } /** * Handle cases where the `ping()`, `pong()`, or `send()` methods are called * when the `readyState` attribute is `CLOSING` or `CLOSED`. * * @param {WebSocket} websocket The WebSocket instance * @param {*} [data] The data to send * @param {Function} [cb] Callback * @private */ function sendAfterClose(websocket, data, cb) { if (data) { const length = toBuffer(data).length; // // The `_bufferedAmount` property is used only when the peer is a client and // the opening handshake fails. Under these circumstances, in fact, the // `setSocket()` method is not called, so the `_socket` and `_sender` // properties are set to `null`. // if (websocket._socket) websocket._sender._bufferedBytes += length; else websocket._bufferedAmount += length; } if (cb) { const err = new Error( `WebSocket is not open: readyState ${websocket.readyState} ` + `(${readyStates[websocket.readyState]})` ); process.nextTick(cb, err); } } /** * The listener of the `Receiver` `'conclude'` event. * * @param {Number} code The status code * @param {Buffer} reason The reason for closing * @private */ function receiverOnConclude(code, reason) { const websocket = this[kWebSocket$1]; websocket._closeFrameReceived = true; websocket._closeMessage = reason; websocket._closeCode = code; if (websocket._socket[kWebSocket$1] === undefined) return; websocket._socket.removeListener('data', socketOnData); process.nextTick(resume, websocket._socket); if (code === 1005) websocket.close(); else websocket.close(code, reason); } /** * The listener of the `Receiver` `'drain'` event. * * @private */ function receiverOnDrain() { const websocket = this[kWebSocket$1]; if (!websocket.isPaused) websocket._socket.resume(); } /** * The listener of the `Receiver` `'error'` event. * * @param {(RangeError|Error)} err The emitted error * @private */ function receiverOnError(err) { const websocket = this[kWebSocket$1]; if (websocket._socket[kWebSocket$1] !== undefined) { websocket._socket.removeListener('data', socketOnData); // // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See // https://github.com/websockets/ws/issues/1940. // process.nextTick(resume, websocket._socket); websocket.close(err[kStatusCode]); } websocket.emit('error', err); } /** * The listener of the `Receiver` `'finish'` event. * * @private */ function receiverOnFinish() { this[kWebSocket$1].emitClose(); } /** * The listener of the `Receiver` `'message'` event. * * @param {Buffer|ArrayBuffer|Buffer[])} data The message * @param {Boolean} isBinary Specifies whether the message is binary or not * @private */ function receiverOnMessage(data, isBinary) { this[kWebSocket$1].emit('message', data, isBinary); } /** * The listener of the `Receiver` `'ping'` event. * * @param {Buffer} data The data included in the ping frame * @private */ function receiverOnPing(data) { const websocket = this[kWebSocket$1]; websocket.pong(data, !websocket._isServer, NOOP); websocket.emit('ping', data); } /** * The listener of the `Receiver` `'pong'` event. * * @param {Buffer} data The data included in the pong frame * @private */ function receiverOnPong(data) { this[kWebSocket$1].emit('pong', data); } /** * Resume a readable stream * * @param {Readable} stream The readable stream * @private */ function resume(stream) { stream.resume(); } /** * The listener of the `net.Socket` `'close'` event. * * @private */ function socketOnClose() { const websocket = this[kWebSocket$1]; this.removeListener('close', socketOnClose); this.removeListener('data', socketOnData); this.removeListener('end', socketOnEnd); websocket._readyState = WebSocket$1.CLOSING; let chunk; // // The close frame might not have been received or the `'end'` event emitted, // for example, if the socket was destroyed due to an error. Ensure that the // `receiver` stream is closed after writing any remaining buffered data to // it. If the readable side of the socket is in flowing mode then there is no // buffered data as everything has been already written and `readable.read()` // will return `null`. If instead, the socket is paused, any possible buffered // data will be read as a single chunk. // if ( !this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null ) { websocket._receiver.write(chunk); } websocket._receiver.end(); this[kWebSocket$1] = undefined; clearTimeout(websocket._closeTimer); if ( websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted ) { websocket.emitClose(); } else { websocket._receiver.on('error', receiverOnFinish); websocket._receiver.on('finish', receiverOnFinish); } } /** * The listener of the `net.Socket` `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function socketOnData(chunk) { if (!this[kWebSocket$1]._receiver.write(chunk)) { this.pause(); } } /** * The listener of the `net.Socket` `'end'` event. * * @private */ function socketOnEnd() { const websocket = this[kWebSocket$1]; websocket._readyState = WebSocket$1.CLOSING; websocket._receiver.end(); this.end(); } /** * The listener of the `net.Socket` `'error'` event. * * @private */ function socketOnError$1() { const websocket = this[kWebSocket$1]; this.removeListener('error', socketOnError$1); this.on('error', NOOP); if (websocket) { websocket._readyState = WebSocket$1.CLOSING; this.destroy(); } } const { tokenChars } = validationExports; /** * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. * * @param {String} header The field value of the header * @return {Set} The subprotocol names * @public */ function parse$5(header) { const protocols = new Set(); let start = -1; let end = -1; let i = 0; for (i; i < header.length; i++) { const code = header.charCodeAt(i); if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if ( i !== 0 && (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ ) { if (end === -1 && start !== -1) end = i; } else if (code === 0x2c /* ',' */) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; const protocol = header.slice(start, end); if (protocols.has(protocol)) { throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); } protocols.add(protocol); start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } if (start === -1 || end !== -1) { throw new SyntaxError('Unexpected end of input'); } const protocol = header.slice(start, i); if (protocols.has(protocol)) { throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); } protocols.add(protocol); return protocols; } var subprotocol$1 = { parse: parse$5 }; /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls|https$" }] */ const EventEmitter = require$$0$5; const http$2 = require$$1$1; const { createHash } = require$$3$1$1; const extension = extension$1; const PerMessageDeflate = permessageDeflate; const subprotocol = subprotocol$1; const WebSocket = websocket; const { GUID, kWebSocket } = constants$7; const keyRegex = /^[+/0-9A-Za-z]{22}==$/; const RUNNING = 0; const CLOSING = 1; const CLOSED = 2; /** * Class representing a WebSocket server. * * @extends EventEmitter */ class WebSocketServer extends EventEmitter { /** * Create a `WebSocketServer` instance. * * @param {Object} options Configuration options * @param {Number} [options.backlog=511] The maximum length of the queue of * pending connections * @param {Boolean} [options.clientTracking=true] Specifies whether or not to * track clients * @param {Function} [options.handleProtocols] A hook to handle protocols * @param {String} [options.host] The hostname where to bind the server * @param {Number} [options.maxPayload=104857600] The maximum allowed message * size * @param {Boolean} [options.noServer=false] Enable no server mode * @param {String} [options.path] Accept only connections matching this path * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable * permessage-deflate * @param {Number} [options.port] The port where to bind the server * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S * server to use * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages * @param {Function} [options.verifyClient] A hook to reject connections * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` * class to use. It must be the `WebSocket` class or class that extends it * @param {Function} [callback] A listener for the `listening` event */ constructor(options, callback) { super(); options = { maxPayload: 100 * 1024 * 1024, skipUTF8Validation: false, perMessageDeflate: false, handleProtocols: null, clientTracking: true, verifyClient: null, noServer: false, backlog: null, // use default (511 as implemented in net.js) server: null, host: null, path: null, port: null, WebSocket, ...options }; if ( (options.port == null && !options.server && !options.noServer) || (options.port != null && (options.server || options.noServer)) || (options.server && options.noServer) ) { throw new TypeError( 'One and only one of the "port", "server", or "noServer" options ' + 'must be specified' ); } if (options.port != null) { this._server = http$2.createServer((req, res) => { const body = http$2.STATUS_CODES[426]; res.writeHead(426, { 'Content-Length': body.length, 'Content-Type': 'text/plain' }); res.end(body); }); this._server.listen( options.port, options.host, options.backlog, callback ); } else if (options.server) { this._server = options.server; } if (this._server) { const emitConnection = this.emit.bind(this, 'connection'); this._removeListeners = addListeners(this._server, { listening: this.emit.bind(this, 'listening'), error: this.emit.bind(this, 'error'), upgrade: (req, socket, head) => { this.handleUpgrade(req, socket, head, emitConnection); } }); } if (options.perMessageDeflate === true) options.perMessageDeflate = {}; if (options.clientTracking) { this.clients = new Set(); this._shouldEmitClose = false; } this.options = options; this._state = RUNNING; } /** * Returns the bound address, the address family name, and port of the server * as reported by the operating system if listening on an IP socket. * If the server is listening on a pipe or UNIX domain socket, the name is * returned as a string. * * @return {(Object|String|null)} The address of the server * @public */ address() { if (this.options.noServer) { throw new Error('The server is operating in "noServer" mode'); } if (!this._server) return null; return this._server.address(); } /** * Stop the server from accepting new connections and emit the `'close'` event * when all existing connections are closed. * * @param {Function} [cb] A one-time listener for the `'close'` event * @public */ close(cb) { if (this._state === CLOSED) { if (cb) { this.once('close', () => { cb(new Error('The server is not running')); }); } process.nextTick(emitClose, this); return; } if (cb) this.once('close', cb); if (this._state === CLOSING) return; this._state = CLOSING; if (this.options.noServer || this.options.server) { if (this._server) { this._removeListeners(); this._removeListeners = this._server = null; } if (this.clients) { if (!this.clients.size) { process.nextTick(emitClose, this); } else { this._shouldEmitClose = true; } } else { process.nextTick(emitClose, this); } } else { const server = this._server; this._removeListeners(); this._removeListeners = this._server = null; // // The HTTP/S server was created internally. Close it, and rely on its // `'close'` event. // server.close(() => { emitClose(this); }); } } /** * See if a given request should be handled by this server instance. * * @param {http.IncomingMessage} req Request object to inspect * @return {Boolean} `true` if the request is valid, else `false` * @public */ shouldHandle(req) { if (this.options.path) { const index = req.url.indexOf('?'); const pathname = index !== -1 ? req.url.slice(0, index) : req.url; if (pathname !== this.options.path) return false; } return true; } /** * Handle a HTTP Upgrade request. * * @param {http.IncomingMessage} req The request object * @param {(net.Socket|tls.Socket)} socket The network socket between the * server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @public */ handleUpgrade(req, socket, head, cb) { socket.on('error', socketOnError); const key = req.headers['sec-websocket-key']; const version = +req.headers['sec-websocket-version']; if (req.method !== 'GET') { const message = 'Invalid HTTP method'; abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); return; } if (req.headers.upgrade.toLowerCase() !== 'websocket') { const message = 'Invalid Upgrade header'; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } if (!key || !keyRegex.test(key)) { const message = 'Missing or invalid Sec-WebSocket-Key header'; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } if (version !== 8 && version !== 13) { const message = 'Missing or invalid Sec-WebSocket-Version header'; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } if (!this.shouldHandle(req)) { abortHandshake(socket, 400); return; } const secWebSocketProtocol = req.headers['sec-websocket-protocol']; let protocols = new Set(); if (secWebSocketProtocol !== undefined) { try { protocols = subprotocol.parse(secWebSocketProtocol); } catch (err) { const message = 'Invalid Sec-WebSocket-Protocol header'; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } } const secWebSocketExtensions = req.headers['sec-websocket-extensions']; const extensions = {}; if ( this.options.perMessageDeflate && secWebSocketExtensions !== undefined ) { const perMessageDeflate = new PerMessageDeflate( this.options.perMessageDeflate, true, this.options.maxPayload ); try { const offers = extension.parse(secWebSocketExtensions); if (offers[PerMessageDeflate.extensionName]) { perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); extensions[PerMessageDeflate.extensionName] = perMessageDeflate; } } catch (err) { const message = 'Invalid or unacceptable Sec-WebSocket-Extensions header'; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } } // // Optionally call external client verification handler. // if (this.options.verifyClient) { const info = { origin: req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], secure: !!(req.socket.authorized || req.socket.encrypted), req }; if (this.options.verifyClient.length === 2) { this.options.verifyClient(info, (verified, code, message, headers) => { if (!verified) { return abortHandshake(socket, code || 401, message, headers); } this.completeUpgrade( extensions, key, protocols, req, socket, head, cb ); }); return; } if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); } this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); } /** * Upgrade the connection to WebSocket. * * @param {Object} extensions The accepted extensions * @param {String} key The value of the `Sec-WebSocket-Key` header * @param {Set} protocols The subprotocols * @param {http.IncomingMessage} req The request object * @param {(net.Socket|tls.Socket)} socket The network socket between the * server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @throws {Error} If called more than once with the same socket * @private */ completeUpgrade(extensions, key, protocols, req, socket, head, cb) { // // Destroy the socket if the client has already sent a FIN packet. // if (!socket.readable || !socket.writable) return socket.destroy(); if (socket[kWebSocket]) { throw new Error( 'server.handleUpgrade() was called more than once with the same ' + 'socket, possibly due to a misconfiguration' ); } if (this._state > RUNNING) return abortHandshake(socket, 503); const digest = createHash('sha1') .update(key + GUID) .digest('base64'); const headers = [ 'HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', `Sec-WebSocket-Accept: ${digest}` ]; const ws = new this.options.WebSocket(null); if (protocols.size) { // // Optionally call external protocol selection handler. // const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value; if (protocol) { headers.push(`Sec-WebSocket-Protocol: ${protocol}`); ws._protocol = protocol; } } if (extensions[PerMessageDeflate.extensionName]) { const params = extensions[PerMessageDeflate.extensionName].params; const value = extension.format({ [PerMessageDeflate.extensionName]: [params] }); headers.push(`Sec-WebSocket-Extensions: ${value}`); ws._extensions = extensions; } // // Allow external modification/inspection of handshake headers. // this.emit('headers', headers, req); socket.write(headers.concat('\r\n').join('\r\n')); socket.removeListener('error', socketOnError); ws.setSocket(socket, head, { maxPayload: this.options.maxPayload, skipUTF8Validation: this.options.skipUTF8Validation }); if (this.clients) { this.clients.add(ws); ws.on('close', () => { this.clients.delete(ws); if (this._shouldEmitClose && !this.clients.size) { process.nextTick(emitClose, this); } }); } cb(ws, req); } } var websocketServer = WebSocketServer; /** * Add event listeners on an `EventEmitter` using a map of * pairs. * * @param {EventEmitter} server The event emitter * @param {Object.} map The listeners to add * @return {Function} A function that will remove the added listeners when * called * @private */ function addListeners(server, map) { for (const event of Object.keys(map)) server.on(event, map[event]); return function removeListeners() { for (const event of Object.keys(map)) { server.removeListener(event, map[event]); } }; } /** * Emit a `'close'` event on an `EventEmitter`. * * @param {EventEmitter} server The event emitter * @private */ function emitClose(server) { server._state = CLOSED; server.emit('close'); } /** * Handle socket errors. * * @private */ function socketOnError() { this.destroy(); } /** * Close the connection when preconditions are not fulfilled. * * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request * @param {Number} code The HTTP response status code * @param {String} [message] The HTTP response body * @param {Object} [headers] Additional HTTP response headers * @private */ function abortHandshake(socket, code, message, headers) { // // The socket is writable unless the user destroyed or ended it before calling // `server.handleUpgrade()` or in the `verifyClient` function, which is a user // error. Handling this does not make much sense as the worst that can happen // is that some of the data written by the user might be discarded due to the // call to `socket.end()` below, which triggers an `'error'` event that in // turn causes the socket to be destroyed. // message = message || http$2.STATUS_CODES[code]; headers = { Connection: 'close', 'Content-Type': 'text/html', 'Content-Length': Buffer.byteLength(message), ...headers }; socket.once('finish', socket.destroy); socket.end( `HTTP/1.1 ${code} ${http$2.STATUS_CODES[code]}\r\n` + Object.keys(headers) .map((h) => `${h}: ${headers[h]}`) .join('\r\n') + '\r\n\r\n' + message ); } /** * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least * one listener for it, otherwise call `abortHandshake()`. * * @param {WebSocketServer} server The WebSocket server * @param {http.IncomingMessage} req The request object * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request * @param {Number} code The HTTP response status code * @param {String} message The HTTP response body * @private */ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) { if (server.listenerCount('wsClientError')) { const err = new Error(message); Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); server.emit('wsClientError', err, socket, req); } else { abortHandshake(socket, code, message); } } var WebSocketServerRaw_ = /*@__PURE__*/getDefaultExportFromCjs$1(websocketServer); /* In Bun, the `ws` module is overridden to hook into the native code. Using the bundled `js` version * of `ws` will not work as Bun's req.socket does not allow reading/writing to the underlying socket. */ process.versions.bun ? // @ts-expect-error: Bun defines `import.meta.require` import.meta.require('ws').WebSocketServer : WebSocketServerRaw_; var httpProxy$3 = {exports: {}}; var eventemitter3 = {exports: {}}; (function (module) { var has = Object.prototype.hasOwnProperty , prefix = '~'; /** * Constructor to create a storage for our `EE` objects. * An `Events` instance is a plain object whose properties are event names. * * @constructor * @private */ function Events() {} // // We try to not inherit from `Object.prototype`. In some engines creating an // instance in this way is faster than calling `Object.create(null)` directly. // If `Object.create(null)` is not supported we prefix the event names with a // character to make sure that the built-in object properties are not // overridden or used as an attack vector. // if (Object.create) { Events.prototype = Object.create(null); // // This hack is needed because the `__proto__` property is still inherited in // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. // if (!new Events().__proto__) prefix = false; } /** * Representation of a single event listener. * * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} [once=false] Specify if the listener is a one-time listener. * @constructor * @private */ function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } /** * Add a listener for a given event. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} once Specify if the listener is a one-time listener. * @returns {EventEmitter} * @private */ function addListener(emitter, event, fn, context, once) { if (typeof fn !== 'function') { throw new TypeError('The listener must be a function'); } var listener = new EE(fn, context || emitter, once) , evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } /** * Clear event by name. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} evt The Event name. * @private */ function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; } /** * Minimal `EventEmitter` interface that is molded against the Node.js * `EventEmitter` interface. * * @constructor * @public */ function EventEmitter() { this._events = new Events(); this._eventsCount = 0; } /** * Return an array listing the events for which the emitter has registered * listeners. * * @returns {Array} * @public */ EventEmitter.prototype.eventNames = function eventNames() { var names = [] , events , name; if (this._eventsCount === 0) return names; for (name in (events = this._events)) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; /** * Return the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Array} The registered listeners. * @public */ EventEmitter.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event , handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { ee[i] = handlers[i].fn; } return ee; }; /** * Return the number of listeners listening to a given event. * * @param {(String|Symbol)} event The event name. * @returns {Number} The number of listeners. * @public */ EventEmitter.prototype.listenerCount = function listenerCount(event) { var evt = prefix ? prefix + event : event , listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; /** * Calls each of the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Boolean} `true` if the event had listeners, else `false`. * @public */ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt] , len = arguments.length , args , i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len -1); i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length , j; for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; /** * Add a listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.on = function on(event, fn, context) { return addListener(this, event, fn, context, false); }; /** * Add a one-time listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.once = function once(event, fn, context) { return addListener(this, event, fn, context, true); }; /** * Remove the listeners of a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn Only remove the listeners that match this function. * @param {*} context Only remove the listeners that have this context. * @param {Boolean} once Only remove one-time listeners. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if ( listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context) ) { clearEvent(this, evt); } } else { for (var i = 0, events = [], length = listeners.length; i < length; i++) { if ( listeners[i].fn !== fn || (once && !listeners[i].once) || (context && listeners[i].context !== context) ) { events.push(listeners[i]); } } // // Reset the array, or remove it completely if we have no more listeners. // if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; /** * Remove all listeners, or those of the specified event. * * @param {(String|Symbol)} [event] The event name. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events(); this._eventsCount = 0; } return this; }; // // Alias methods names because people roll like that. // EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; // // Expose the prefix. // EventEmitter.prefixed = prefix; // // Allow `EventEmitter` to be imported as module namespace. // EventEmitter.EventEmitter = EventEmitter; // // Expose the module. // { module.exports = EventEmitter; } } (eventemitter3)); var eventemitter3Exports = eventemitter3.exports; var common$3 = {}; /** * Check if we're required to add a port number. * * @see https://url.spec.whatwg.org/#default-port * @param {Number|String} port Port number we need to check * @param {String} protocol Protocol we need to check against. * @returns {Boolean} Is it a default port for the given protocol * @api private */ var requiresPort = function required(port, protocol) { protocol = protocol.split(':')[0]; port = +port; if (!port) return false; switch (protocol) { case 'http': case 'ws': return port !== 80; case 'https': case 'wss': return port !== 443; case 'ftp': return port !== 21; case 'gopher': return port !== 70; case 'file': return false; } return port !== 0; }; (function (exports) { var common = exports, url = require$$0$9, extend = require$$0$6._extend, required = requiresPort; var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i, isSSL = /^https|wss/; /** * Simple Regex for testing if protocol is https */ common.isSSL = isSSL; /** * Copies the right headers from `options` and `req` to * `outgoing` which is then used to fire the proxied * request. * * Examples: * * common.setupOutgoing(outgoing, options, req) * // => { host: ..., hostname: ...} * * @param {Object} Outgoing Base object to be filled with required properties * @param {Object} Options Config object passed to the proxy * @param {ClientRequest} Req Request Object * @param {String} Forward String to select forward or target *  * @return {Object} Outgoing Object with all required properties set * * @api private */ common.setupOutgoing = function(outgoing, options, req, forward) { outgoing.port = options[forward || 'target'].port || (isSSL.test(options[forward || 'target'].protocol) ? 443 : 80); ['host', 'hostname', 'socketPath', 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers', 'secureProtocol'].forEach( function(e) { outgoing[e] = options[forward || 'target'][e]; } ); outgoing.method = options.method || req.method; outgoing.headers = extend({}, req.headers); if (options.headers){ extend(outgoing.headers, options.headers); } if (options.auth) { outgoing.auth = options.auth; } if (options.ca) { outgoing.ca = options.ca; } if (isSSL.test(options[forward || 'target'].protocol)) { outgoing.rejectUnauthorized = (typeof options.secure === "undefined") ? true : options.secure; } outgoing.agent = options.agent || false; outgoing.localAddress = options.localAddress; // // Remark: If we are false and not upgrading, set the connection: close. This is the right thing to do // as node core doesn't handle this COMPLETELY properly yet. // if (!outgoing.agent) { outgoing.headers = outgoing.headers || {}; if (typeof outgoing.headers.connection !== 'string' || !upgradeHeader.test(outgoing.headers.connection) ) { outgoing.headers.connection = 'close'; } } // the final path is target path + relative path requested by user: var target = options[forward || 'target']; var targetPath = target && options.prependPath !== false ? (target.path || '') : ''; // // Remark: Can we somehow not use url.parse as a perf optimization? // var outgoingPath = !options.toProxy ? (url.parse(req.url).path || '') : req.url; // // Remark: ignorePath will just straight up ignore whatever the request's // path is. This can be labeled as FOOT-GUN material if you do not know what // you are doing and are using conflicting options. // outgoingPath = !options.ignorePath ? outgoingPath : ''; outgoing.path = common.urlJoin(targetPath, outgoingPath); if (options.changeOrigin) { outgoing.headers.host = required(outgoing.port, options[forward || 'target'].protocol) && !hasPort(outgoing.host) ? outgoing.host + ':' + outgoing.port : outgoing.host; } return outgoing; }; /** * Set the proper configuration for sockets, * set no delay and set keep alive, also set * the timeout to 0. * * Examples: * * common.setupSocket(socket) * // => Socket * * @param {Socket} Socket instance to setup *  * @return {Socket} Return the configured socket. * * @api private */ common.setupSocket = function(socket) { socket.setTimeout(0); socket.setNoDelay(true); socket.setKeepAlive(true, 0); return socket; }; /** * Get the port number from the host. Or guess it based on the connection type. * * @param {Request} req Incoming HTTP request. * * @return {String} The port number. * * @api private */ common.getPort = function(req) { var res = req.headers.host ? req.headers.host.match(/:(\d+)/) : ''; return res ? res[1] : common.hasEncryptedConnection(req) ? '443' : '80'; }; /** * Check if the request has an encrypted connection. * * @param {Request} req Incoming HTTP request. * * @return {Boolean} Whether the connection is encrypted or not. * * @api private */ common.hasEncryptedConnection = function(req) { return Boolean(req.connection.encrypted || req.connection.pair); }; /** * OS-agnostic join (doesn't break on URLs like path.join does on Windows)> * * @return {String} The generated path. * * @api private */ common.urlJoin = function() { // // We do not want to mess with the query string. All we want to touch is the path. // var args = Array.prototype.slice.call(arguments), lastIndex = args.length - 1, last = args[lastIndex], lastSegs = last.split('?'), retSegs; args[lastIndex] = lastSegs.shift(); // // Join all strings, but remove empty strings so we don't get extra slashes from // joining e.g. ['', 'am'] // retSegs = [ args.filter(Boolean).join('/') .replace(/\/+/g, '/') .replace('http:/', 'http://') .replace('https:/', 'https://') ]; // Only join the query string if it exists so we don't have trailing a '?' // on every request // Handle case where there could be multiple ? in the URL. retSegs.push.apply(retSegs, lastSegs); return retSegs.join('?') }; /** * Rewrites or removes the domain of a cookie header * * @param {String|Array} Header * @param {Object} Config, mapping of domain to rewritten domain. * '*' key to match any domain, null value to remove the domain. * * @api private */ common.rewriteCookieProperty = function rewriteCookieProperty(header, config, property) { if (Array.isArray(header)) { return header.map(function (headerElement) { return rewriteCookieProperty(headerElement, config, property); }); } return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", 'i'), function(match, prefix, previousValue) { var newValue; if (previousValue in config) { newValue = config[previousValue]; } else if ('*' in config) { newValue = config['*']; } else { //no match, return previous value return match; } if (newValue) { //replace value return prefix + newValue; } else { //remove value return ''; } }); }; /** * Check the host and see if it potentially has a port in it (keep it simple) * * @returns {Boolean} Whether we have one or not * * @api private */ function hasPort(host) { return !!~host.indexOf(':'); }} (common$3)); var url$1 = require$$0$9, common$2 = common$3; var redirectRegex = /^201|30(1|2|7|8)$/; /*! * Array of passes. * * A `pass` is just a function that is executed on `req, res, options` * so that you can easily add new checks while still keeping the base * flexible. */ var webOutgoing = { // <-- /** * If is a HTTP 1.0 request, remove chunk headers * * @param {ClientRequest} Req Request object * @param {IncomingMessage} Res Response object * @param {proxyResponse} Res Response object from the proxy request * * @api private */ removeChunked: function removeChunked(req, res, proxyRes) { if (req.httpVersion === '1.0') { delete proxyRes.headers['transfer-encoding']; } }, /** * If is a HTTP 1.0 request, set the correct connection header * or if connection header not present, then use `keep-alive` * * @param {ClientRequest} Req Request object * @param {IncomingMessage} Res Response object * @param {proxyResponse} Res Response object from the proxy request * * @api private */ setConnection: function setConnection(req, res, proxyRes) { if (req.httpVersion === '1.0') { proxyRes.headers.connection = req.headers.connection || 'close'; } else if (req.httpVersion !== '2.0' && !proxyRes.headers.connection) { proxyRes.headers.connection = req.headers.connection || 'keep-alive'; } }, setRedirectHostRewrite: function setRedirectHostRewrite(req, res, proxyRes, options) { if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite) && proxyRes.headers['location'] && redirectRegex.test(proxyRes.statusCode)) { var target = url$1.parse(options.target); var u = url$1.parse(proxyRes.headers['location']); // make sure the redirected host matches the target host before rewriting if (target.host != u.host) { return; } if (options.hostRewrite) { u.host = options.hostRewrite; } else if (options.autoRewrite) { u.host = req.headers['host']; } if (options.protocolRewrite) { u.protocol = options.protocolRewrite; } proxyRes.headers['location'] = u.format(); } }, /** * Copy headers from proxyResponse to response * set each header in response object. * * @param {ClientRequest} Req Request object * @param {IncomingMessage} Res Response object * @param {proxyResponse} Res Response object from the proxy request * @param {Object} Options options.cookieDomainRewrite: Config to rewrite cookie domain * * @api private */ writeHeaders: function writeHeaders(req, res, proxyRes, options) { var rewriteCookieDomainConfig = options.cookieDomainRewrite, rewriteCookiePathConfig = options.cookiePathRewrite, preserveHeaderKeyCase = options.preserveHeaderKeyCase, rawHeaderKeyMap, setHeader = function(key, header) { if (header == undefined) return; if (rewriteCookieDomainConfig && key.toLowerCase() === 'set-cookie') { header = common$2.rewriteCookieProperty(header, rewriteCookieDomainConfig, 'domain'); } if (rewriteCookiePathConfig && key.toLowerCase() === 'set-cookie') { header = common$2.rewriteCookieProperty(header, rewriteCookiePathConfig, 'path'); } res.setHeader(String(key).trim(), header); }; if (typeof rewriteCookieDomainConfig === 'string') { //also test for '' rewriteCookieDomainConfig = { '*': rewriteCookieDomainConfig }; } if (typeof rewriteCookiePathConfig === 'string') { //also test for '' rewriteCookiePathConfig = { '*': rewriteCookiePathConfig }; } // message.rawHeaders is added in: v0.11.6 // https://nodejs.org/api/http.html#http_message_rawheaders if (preserveHeaderKeyCase && proxyRes.rawHeaders != undefined) { rawHeaderKeyMap = {}; for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) { var key = proxyRes.rawHeaders[i]; rawHeaderKeyMap[key.toLowerCase()] = key; } } Object.keys(proxyRes.headers).forEach(function(key) { var header = proxyRes.headers[key]; if (preserveHeaderKeyCase && rawHeaderKeyMap) { key = rawHeaderKeyMap[key] || key; } setHeader(key, header); }); }, /** * Set the statusCode from the proxyResponse * * @param {ClientRequest} Req Request object * @param {IncomingMessage} Res Response object * @param {proxyResponse} Res Response object from the proxy request * * @api private */ writeStatusCode: function writeStatusCode(req, res, proxyRes) { // From Node.js docs: response.writeHead(statusCode[, statusMessage][, headers]) if(proxyRes.statusMessage) { res.statusCode = proxyRes.statusCode; res.statusMessage = proxyRes.statusMessage; } else { res.statusCode = proxyRes.statusCode; } } }; var followRedirects$1 = {exports: {}}; var debug$3; var debug_1 = function () { if (!debug$3) { try { /* eslint global-require: off */ debug$3 = srcExports$1("follow-redirects"); } catch (error) { /* */ } if (typeof debug$3 !== "function") { debug$3 = function () { /* */ }; } } debug$3.apply(null, arguments); }; var url = require$$0$9; var URL$1 = url.URL; var http$1 = require$$1$1; var https$1 = require$$1$2; var Writable = require$$0$7.Writable; var assert = require$$5; var debug$2 = debug_1; // Create handlers that pass events from native requests var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; var eventHandlers = Object.create(null); events.forEach(function (event) { eventHandlers[event] = function (arg1, arg2, arg3) { this._redirectable.emit(event, arg1, arg2, arg3); }; }); // Error types with codes var RedirectionError = createErrorType( "ERR_FR_REDIRECTION_FAILURE", "Redirected request failed" ); var TooManyRedirectsError = createErrorType( "ERR_FR_TOO_MANY_REDIRECTS", "Maximum number of redirects exceeded" ); var MaxBodyLengthExceededError = createErrorType( "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", "Request body larger than maxBodyLength limit" ); var WriteAfterEndError = createErrorType( "ERR_STREAM_WRITE_AFTER_END", "write after end" ); // An HTTP(S) request that can be redirected function RedirectableRequest(options, responseCallback) { // Initialize the request Writable.call(this); this._sanitizeOptions(options); this._options = options; this._ended = false; this._ending = false; this._redirectCount = 0; this._redirects = []; this._requestBodyLength = 0; this._requestBodyBuffers = []; // Attach a callback if passed if (responseCallback) { this.on("response", responseCallback); } // React to responses of native requests var self = this; this._onNativeResponse = function (response) { self._processResponse(response); }; // Perform the first request this._performRequest(); } RedirectableRequest.prototype = Object.create(Writable.prototype); RedirectableRequest.prototype.abort = function () { abortRequest(this._currentRequest); this.emit("abort"); }; // Writes buffered data to the current native request RedirectableRequest.prototype.write = function (data, encoding, callback) { // Writing is not allowed if end has been called if (this._ending) { throw new WriteAfterEndError(); } // Validate input and shift parameters if necessary if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { throw new TypeError("data should be a string, Buffer or Uint8Array"); } if (typeof encoding === "function") { callback = encoding; encoding = null; } // Ignore empty buffers, since writing them doesn't invoke the callback // https://github.com/nodejs/node/issues/22066 if (data.length === 0) { if (callback) { callback(); } return; } // Only write when we don't exceed the maximum body length if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { this._requestBodyLength += data.length; this._requestBodyBuffers.push({ data: data, encoding: encoding }); this._currentRequest.write(data, encoding, callback); } // Error when we exceed the maximum body length else { this.emit("error", new MaxBodyLengthExceededError()); this.abort(); } }; // Ends the current native request RedirectableRequest.prototype.end = function (data, encoding, callback) { // Shift parameters if necessary if (typeof data === "function") { callback = data; data = encoding = null; } else if (typeof encoding === "function") { callback = encoding; encoding = null; } // Write data if needed and end if (!data) { this._ended = this._ending = true; this._currentRequest.end(null, null, callback); } else { var self = this; var currentRequest = this._currentRequest; this.write(data, encoding, function () { self._ended = true; currentRequest.end(null, null, callback); }); this._ending = true; } }; // Sets a header value on the current native request RedirectableRequest.prototype.setHeader = function (name, value) { this._options.headers[name] = value; this._currentRequest.setHeader(name, value); }; // Clears a header value on the current native request RedirectableRequest.prototype.removeHeader = function (name) { delete this._options.headers[name]; this._currentRequest.removeHeader(name); }; // Global timeout for all underlying requests RedirectableRequest.prototype.setTimeout = function (msecs, callback) { var self = this; // Destroys the socket on timeout function destroyOnTimeout(socket) { socket.setTimeout(msecs); socket.removeListener("timeout", socket.destroy); socket.addListener("timeout", socket.destroy); } // Sets up a timer to trigger a timeout event function startTimer(socket) { if (self._timeout) { clearTimeout(self._timeout); } self._timeout = setTimeout(function () { self.emit("timeout"); clearTimer(); }, msecs); destroyOnTimeout(socket); } // Stops a timeout from triggering function clearTimer() { // Clear the timeout if (self._timeout) { clearTimeout(self._timeout); self._timeout = null; } // Clean up all attached listeners self.removeListener("abort", clearTimer); self.removeListener("error", clearTimer); self.removeListener("response", clearTimer); if (callback) { self.removeListener("timeout", callback); } if (!self.socket) { self._currentRequest.removeListener("socket", startTimer); } } // Attach callback if passed if (callback) { this.on("timeout", callback); } // Start the timer if or when the socket is opened if (this.socket) { startTimer(this.socket); } else { this._currentRequest.once("socket", startTimer); } // Clean up on events this.on("socket", destroyOnTimeout); this.on("abort", clearTimer); this.on("error", clearTimer); this.on("response", clearTimer); return this; }; // Proxy all other public ClientRequest methods [ "flushHeaders", "getHeader", "setNoDelay", "setSocketKeepAlive", ].forEach(function (method) { RedirectableRequest.prototype[method] = function (a, b) { return this._currentRequest[method](a, b); }; }); // Proxy all public ClientRequest properties ["aborted", "connection", "socket"].forEach(function (property) { Object.defineProperty(RedirectableRequest.prototype, property, { get: function () { return this._currentRequest[property]; }, }); }); RedirectableRequest.prototype._sanitizeOptions = function (options) { // Ensure headers are always present if (!options.headers) { options.headers = {}; } // Since http.request treats host as an alias of hostname, // but the url module interprets host as hostname plus port, // eliminate the host property to avoid confusion. if (options.host) { // Use hostname if set, because it has precedence if (!options.hostname) { options.hostname = options.host; } delete options.host; } // Complete the URL object when necessary if (!options.pathname && options.path) { var searchPos = options.path.indexOf("?"); if (searchPos < 0) { options.pathname = options.path; } else { options.pathname = options.path.substring(0, searchPos); options.search = options.path.substring(searchPos); } } }; // Executes the next native request (initial or redirect) RedirectableRequest.prototype._performRequest = function () { // Load the native protocol var protocol = this._options.protocol; var nativeProtocol = this._options.nativeProtocols[protocol]; if (!nativeProtocol) { this.emit("error", new TypeError("Unsupported protocol " + protocol)); return; } // If specified, use the agent corresponding to the protocol // (HTTP and HTTPS use different types of agents) if (this._options.agents) { var scheme = protocol.slice(0, -1); this._options.agent = this._options.agents[scheme]; } // Create the native request var request = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse); this._currentUrl = url.format(this._options); // Set up event handlers request._redirectable = this; for (var e = 0; e < events.length; e++) { request.on(events[e], eventHandlers[events[e]]); } // End a redirected request // (The first request must be ended explicitly with RedirectableRequest#end) if (this._isRedirect) { // Write the request entity and end. var i = 0; var self = this; var buffers = this._requestBodyBuffers; (function writeNext(error) { // Only write if this request has not been redirected yet /* istanbul ignore else */ if (request === self._currentRequest) { // Report any write errors /* istanbul ignore if */ if (error) { self.emit("error", error); } // Write the next buffer if there are still left else if (i < buffers.length) { var buffer = buffers[i++]; /* istanbul ignore else */ if (!request.finished) { request.write(buffer.data, buffer.encoding, writeNext); } } // End the request if `end` has been called on us else if (self._ended) { request.end(); } } }()); } }; // Processes a response from the current native request RedirectableRequest.prototype._processResponse = function (response) { // Store the redirected response var statusCode = response.statusCode; if (this._options.trackRedirects) { this._redirects.push({ url: this._currentUrl, headers: response.headers, statusCode: statusCode, }); } // RFC7231§6.4: The 3xx (Redirection) class of status code indicates // that further action needs to be taken by the user agent in order to // fulfill the request. If a Location header field is provided, // the user agent MAY automatically redirect its request to the URI // referenced by the Location field value, // even if the specific status code is not understood. // If the response is not a redirect; return it as-is var location = response.headers.location; if (!location || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) { response.responseUrl = this._currentUrl; response.redirects = this._redirects; this.emit("response", response); // Clean up this._requestBodyBuffers = []; return; } // The response is a redirect, so abort the current request abortRequest(this._currentRequest); // Discard the remainder of the response to avoid waiting for data response.destroy(); // RFC7231§6.4: A client SHOULD detect and intervene // in cyclical redirections (i.e., "infinite" redirection loops). if (++this._redirectCount > this._options.maxRedirects) { this.emit("error", new TooManyRedirectsError()); return; } // Store the request headers if applicable var requestHeaders; var beforeRedirect = this._options.beforeRedirect; if (beforeRedirect) { requestHeaders = Object.assign({ // The Host header was set by nativeProtocol.request Host: response.req.getHeader("host"), }, this._options.headers); } // RFC7231§6.4: Automatic redirection needs to done with // care for methods not known to be safe, […] // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change // the request method from POST to GET for the subsequent request. var method = this._options.method; if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || // RFC7231§6.4.4: The 303 (See Other) status code indicates that // the server is redirecting the user agent to a different resource […] // A user agent can perform a retrieval request targeting that URI // (a GET or HEAD request if using HTTP) […] (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { this._options.method = "GET"; // Drop a possible entity and headers related to it this._requestBodyBuffers = []; removeMatchingHeaders(/^content-/i, this._options.headers); } // Drop the Host header, as the redirect might lead to a different host var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); // If the redirect is relative, carry over the host of the last request var currentUrlParts = url.parse(this._currentUrl); var currentHost = currentHostHeader || currentUrlParts.host; var currentUrl = /^\w+:/.test(location) ? this._currentUrl : url.format(Object.assign(currentUrlParts, { host: currentHost })); // Determine the URL of the redirection var redirectUrl; try { redirectUrl = url.resolve(currentUrl, location); } catch (cause) { this.emit("error", new RedirectionError(cause)); return; } // Create the redirected request debug$2("redirecting to", redirectUrl); this._isRedirect = true; var redirectUrlParts = url.parse(redirectUrl); Object.assign(this._options, redirectUrlParts); // Drop confidential headers when redirecting to a less secure protocol // or to a different domain that is not a superdomain if (redirectUrlParts.protocol !== currentUrlParts.protocol && redirectUrlParts.protocol !== "https:" || redirectUrlParts.host !== currentHost && !isSubdomain(redirectUrlParts.host, currentHost)) { removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers); } // Evaluate the beforeRedirect callback if (typeof beforeRedirect === "function") { var responseDetails = { headers: response.headers, statusCode: statusCode, }; var requestDetails = { url: currentUrl, method: method, headers: requestHeaders, }; try { beforeRedirect(this._options, responseDetails, requestDetails); } catch (err) { this.emit("error", err); return; } this._sanitizeOptions(this._options); } // Perform the redirected request try { this._performRequest(); } catch (cause) { this.emit("error", new RedirectionError(cause)); } }; // Wraps the key/value object of protocols with redirect functionality function wrap(protocols) { // Default settings var exports = { maxRedirects: 21, maxBodyLength: 10 * 1024 * 1024, }; // Wrap each protocol var nativeProtocols = {}; Object.keys(protocols).forEach(function (scheme) { var protocol = scheme + ":"; var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); // Executes a request, following redirects function request(input, options, callback) { // Parse parameters if (typeof input === "string") { var urlStr = input; try { input = urlToOptions(new URL$1(urlStr)); } catch (err) { /* istanbul ignore next */ input = url.parse(urlStr); } } else if (URL$1 && (input instanceof URL$1)) { input = urlToOptions(input); } else { callback = options; options = input; input = { protocol: protocol }; } if (typeof options === "function") { callback = options; options = null; } // Set defaults options = Object.assign({ maxRedirects: exports.maxRedirects, maxBodyLength: exports.maxBodyLength, }, input, options); options.nativeProtocols = nativeProtocols; assert.equal(options.protocol, protocol, "protocol mismatch"); debug$2("options", options); return new RedirectableRequest(options, callback); } // Executes a GET request, following redirects function get(input, options, callback) { var wrappedRequest = wrappedProtocol.request(input, options, callback); wrappedRequest.end(); return wrappedRequest; } // Expose the properties on the wrapped protocol Object.defineProperties(wrappedProtocol, { request: { value: request, configurable: true, enumerable: true, writable: true }, get: { value: get, configurable: true, enumerable: true, writable: true }, }); }); return exports; } /* istanbul ignore next */ function noop$1() { /* empty */ } // from https://github.com/nodejs/node/blob/master/lib/internal/url.js function urlToOptions(urlObject) { var options = { protocol: urlObject.protocol, hostname: urlObject.hostname.startsWith("[") ? /* istanbul ignore next */ urlObject.hostname.slice(1, -1) : urlObject.hostname, hash: urlObject.hash, search: urlObject.search, pathname: urlObject.pathname, path: urlObject.pathname + urlObject.search, href: urlObject.href, }; if (urlObject.port !== "") { options.port = Number(urlObject.port); } return options; } function removeMatchingHeaders(regex, headers) { var lastValue; for (var header in headers) { if (regex.test(header)) { lastValue = headers[header]; delete headers[header]; } } return (lastValue === null || typeof lastValue === "undefined") ? undefined : String(lastValue).trim(); } function createErrorType(code, defaultMessage) { function CustomError(cause) { Error.captureStackTrace(this, this.constructor); if (!cause) { this.message = defaultMessage; } else { this.message = defaultMessage + ": " + cause.message; this.cause = cause; } } CustomError.prototype = new Error(); CustomError.prototype.constructor = CustomError; CustomError.prototype.name = "Error [" + code + "]"; CustomError.prototype.code = code; return CustomError; } function abortRequest(request) { for (var e = 0; e < events.length; e++) { request.removeListener(events[e], eventHandlers[events[e]]); } request.on("error", noop$1); request.abort(); } function isSubdomain(subdomain, domain) { const dot = subdomain.length - domain.length - 1; return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); } // Exports followRedirects$1.exports = wrap({ http: http$1, https: https$1 }); followRedirects$1.exports.wrap = wrap; var followRedirectsExports = followRedirects$1.exports; var httpNative = require$$1$1, httpsNative = require$$1$2, web_o = webOutgoing, common$1 = common$3, followRedirects = followRedirectsExports; web_o = Object.keys(web_o).map(function(pass) { return web_o[pass]; }); var nativeAgents = { http: httpNative, https: httpsNative }; /*! * Array of passes. * * A `pass` is just a function that is executed on `req, res, options` * so that you can easily add new checks while still keeping the base * flexible. */ var webIncoming = { /** * Sets `content-length` to '0' if request is of DELETE type. * * @param {ClientRequest} Req Request object * @param {IncomingMessage} Res Response object * @param {Object} Options Config object passed to the proxy * * @api private */ deleteLength: function deleteLength(req, res, options) { if((req.method === 'DELETE' || req.method === 'OPTIONS') && !req.headers['content-length']) { req.headers['content-length'] = '0'; delete req.headers['transfer-encoding']; } }, /** * Sets timeout in request socket if it was specified in options. * * @param {ClientRequest} Req Request object * @param {IncomingMessage} Res Response object * @param {Object} Options Config object passed to the proxy * * @api private */ timeout: function timeout(req, res, options) { if(options.timeout) { req.socket.setTimeout(options.timeout); } }, /** * Sets `x-forwarded-*` headers if specified in config. * * @param {ClientRequest} Req Request object * @param {IncomingMessage} Res Response object * @param {Object} Options Config object passed to the proxy * * @api private */ XHeaders: function XHeaders(req, res, options) { if(!options.xfwd) return; var encrypted = req.isSpdy || common$1.hasEncryptedConnection(req); var values = { for : req.connection.remoteAddress || req.socket.remoteAddress, port : common$1.getPort(req), proto: encrypted ? 'https' : 'http' }; ['for', 'port', 'proto'].forEach(function(header) { req.headers['x-forwarded-' + header] = (req.headers['x-forwarded-' + header] || '') + (req.headers['x-forwarded-' + header] ? ',' : '') + values[header]; }); req.headers['x-forwarded-host'] = req.headers['x-forwarded-host'] || req.headers['host'] || ''; }, /** * Does the actual proxying. If `forward` is enabled fires up * a ForwardStream, same happens for ProxyStream. The request * just dies otherwise. * * @param {ClientRequest} Req Request object * @param {IncomingMessage} Res Response object * @param {Object} Options Config object passed to the proxy * * @api private */ stream: function stream(req, res, options, _, server, clb) { // And we begin! server.emit('start', req, res, options.target || options.forward); var agents = options.followRedirects ? followRedirects : nativeAgents; var http = agents.http; var https = agents.https; if(options.forward) { // If forward enable, so just pipe the request var forwardReq = (options.forward.protocol === 'https:' ? https : http).request( common$1.setupOutgoing(options.ssl || {}, options, req, 'forward') ); // error handler (e.g. ECONNRESET, ECONNREFUSED) // Handle errors on incoming request as well as it makes sense to var forwardError = createErrorHandler(forwardReq, options.forward); req.on('error', forwardError); forwardReq.on('error', forwardError); (options.buffer || req).pipe(forwardReq); if(!options.target) { return res.end(); } } // Request initalization var proxyReq = (options.target.protocol === 'https:' ? https : http).request( common$1.setupOutgoing(options.ssl || {}, options, req) ); // Enable developers to modify the proxyReq before headers are sent proxyReq.on('socket', function(socket) { if(server && !proxyReq.getHeader('expect')) { server.emit('proxyReq', proxyReq, req, res, options); } }); // allow outgoing socket to timeout so that we could // show an error page at the initial request if(options.proxyTimeout) { proxyReq.setTimeout(options.proxyTimeout, function() { proxyReq.abort(); }); } // Ensure we abort proxy if request is aborted req.on('aborted', function () { proxyReq.abort(); }); // handle errors in proxy and incoming request, just like for forward proxy var proxyError = createErrorHandler(proxyReq, options.target); req.on('error', proxyError); proxyReq.on('error', proxyError); function createErrorHandler(proxyReq, url) { return function proxyError(err) { if (req.socket.destroyed && err.code === 'ECONNRESET') { server.emit('econnreset', err, req, res, url); return proxyReq.abort(); } if (clb) { clb(err, req, res, url); } else { server.emit('error', err, req, res, url); } } } (options.buffer || req).pipe(proxyReq); proxyReq.on('response', function(proxyRes) { if(server) { server.emit('proxyRes', proxyRes, req, res); } if(!res.headersSent && !options.selfHandleResponse) { for(var i=0; i < web_o.length; i++) { if(web_o[i](req, res, proxyRes, options)) { break; } } } if (!res.finished) { // Allow us to listen when the proxy has completed proxyRes.on('end', function () { if (server) server.emit('end', req, res, proxyRes); }); // We pipe to the response unless its expected to be handled by the user if (!options.selfHandleResponse) proxyRes.pipe(res); } else { if (server) server.emit('end', req, res, proxyRes); } }); } }; var http = require$$1$1, https = require$$1$2, common$d = common$3; /*! * Array of passes. * * A `pass` is just a function that is executed on `req, socket, options` * so that you can easily add new checks while still keeping the base * flexible. */ /* * Websockets Passes * */ var wsIncoming = { /** * WebSocket requests must have the `GET` method and * the `upgrade:websocket` header * * @param {ClientRequest} Req Request object * @param {Socket} Websocket * * @api private */ checkMethodAndHeader : function checkMethodAndHeader(req, socket) { if (req.method !== 'GET' || !req.headers.upgrade) { socket.destroy(); return true; } if (req.headers.upgrade.toLowerCase() !== 'websocket') { socket.destroy(); return true; } }, /** * Sets `x-forwarded-*` headers if specified in config. * * @param {ClientRequest} Req Request object * @param {Socket} Websocket * @param {Object} Options Config object passed to the proxy * * @api private */ XHeaders : function XHeaders(req, socket, options) { if(!options.xfwd) return; var values = { for : req.connection.remoteAddress || req.socket.remoteAddress, port : common$d.getPort(req), proto: common$d.hasEncryptedConnection(req) ? 'wss' : 'ws' }; ['for', 'port', 'proto'].forEach(function(header) { req.headers['x-forwarded-' + header] = (req.headers['x-forwarded-' + header] || '') + (req.headers['x-forwarded-' + header] ? ',' : '') + values[header]; }); }, /** * Does the actual proxying. Make the request and upgrade it * send the Switching Protocols request and pipe the sockets. * * @param {ClientRequest} Req Request object * @param {Socket} Websocket * @param {Object} Options Config object passed to the proxy * * @api private */ stream : function stream(req, socket, options, head, server, clb) { var createHttpHeader = function(line, headers) { return Object.keys(headers).reduce(function (head, key) { var value = headers[key]; if (!Array.isArray(value)) { head.push(key + ': ' + value); return head; } for (var i = 0; i < value.length; i++) { head.push(key + ': ' + value[i]); } return head; }, [line]) .join('\r\n') + '\r\n\r\n'; }; common$d.setupSocket(socket); if (head && head.length) socket.unshift(head); var proxyReq = (common$d.isSSL.test(options.target.protocol) ? https : http).request( common$d.setupOutgoing(options.ssl || {}, options, req) ); // Enable developers to modify the proxyReq before headers are sent if (server) { server.emit('proxyReqWs', proxyReq, req, socket, options, head); } // Error Handler proxyReq.on('error', onOutgoingError); proxyReq.on('response', function (res) { // if upgrade event isn't going to happen, close the socket if (!res.upgrade) { socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers)); res.pipe(socket); } }); proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) { proxySocket.on('error', onOutgoingError); // Allow us to listen when the websocket has completed proxySocket.on('end', function () { server.emit('close', proxyRes, proxySocket, proxyHead); }); // The pipe below will end proxySocket if socket closes cleanly, but not // if it errors (eg, vanishes from the net and starts returning // EHOSTUNREACH). We need to do that explicitly. socket.on('error', function () { proxySocket.end(); }); common$d.setupSocket(proxySocket); if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead); // // Remark: Handle writing the headers to the socket when switching protocols // Also handles when a header is an array // socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers)); proxySocket.pipe(socket).pipe(proxySocket); server.emit('open', proxySocket); server.emit('proxySocket', proxySocket); //DEPRECATED. }); return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT function onOutgoingError(err) { if (clb) { clb(err, req, socket); } else { server.emit('error', err, req, socket); } socket.end(); } } }; (function (module) { var httpProxy = module.exports, extend = require$$0$6._extend, parse_url = require$$0$9.parse, EE3 = eventemitter3Exports, http = require$$1$1, https = require$$1$2, web = webIncoming, ws = wsIncoming; httpProxy.Server = ProxyServer; /** * Returns a function that creates the loader for * either `ws` or `web`'s passes. * * Examples: * * httpProxy.createRightProxy('ws') * // => [Function] * * @param {String} Type Either 'ws' or 'web' *  * @return {Function} Loader Function that when called returns an iterator for the right passes * * @api private */ function createRightProxy(type) { return function(options) { return function(req, res /*, [head], [opts] */) { var passes = (type === 'ws') ? this.wsPasses : this.webPasses, args = [].slice.call(arguments), cntr = args.length - 1, head, cbl; /* optional args parse begin */ if(typeof args[cntr] === 'function') { cbl = args[cntr]; cntr--; } var requestOptions = options; if( !(args[cntr] instanceof Buffer) && args[cntr] !== res ) { //Copy global options requestOptions = extend({}, options); //Overwrite with request options extend(requestOptions, args[cntr]); cntr--; } if(args[cntr] instanceof Buffer) { head = args[cntr]; } /* optional args parse end */ ['target', 'forward'].forEach(function(e) { if (typeof requestOptions[e] === 'string') requestOptions[e] = parse_url(requestOptions[e]); }); if (!requestOptions.target && !requestOptions.forward) { return this.emit('error', new Error('Must provide a proper URL as target')); } for(var i=0; i < passes.length; i++) { /** * Call of passes functions * pass(req, res, options, head) * * In WebSockets case the `res` variable * refer to the connection socket * pass(req, socket, options, head) */ if(passes[i](req, res, requestOptions, head, this, cbl)) { // passes can return a truthy value to halt the loop break; } } }; }; } httpProxy.createRightProxy = createRightProxy; function ProxyServer(options) { EE3.call(this); options = options || {}; options.prependPath = options.prependPath === false ? false : true; this.web = this.proxyRequest = createRightProxy('web')(options); this.ws = this.proxyWebsocketRequest = createRightProxy('ws')(options); this.options = options; this.webPasses = Object.keys(web).map(function(pass) { return web[pass]; }); this.wsPasses = Object.keys(ws).map(function(pass) { return ws[pass]; }); this.on('error', this.onError, this); } require$$0$6.inherits(ProxyServer, EE3); ProxyServer.prototype.onError = function (err) { // // Remark: Replicate node core behavior using EE3 // so we force people to handle their own errors // if(this.listeners('error').length === 1) { throw err; } }; ProxyServer.prototype.listen = function(port, hostname) { var self = this, closure = function(req, res) { self.web(req, res); }; this._server = this.options.ssl ? https.createServer(this.options.ssl, closure) : http.createServer(closure); if(this.options.ws) { this._server.on('upgrade', function(req, socket, head) { self.ws(req, socket, head); }); } this._server.listen(port, hostname); return this; }; ProxyServer.prototype.close = function(callback) { var self = this; if (this._server) { this._server.close(done); } // Wrap callback to nullify server after all open connections are closed. function done() { self._server = null; if (callback) { callback.apply(null, arguments); } } }; ProxyServer.prototype.before = function(type, passName, callback) { if (type !== 'ws' && type !== 'web') { throw new Error('type must be `web` or `ws`'); } var passes = (type === 'ws') ? this.wsPasses : this.webPasses, i = false; passes.forEach(function(v, idx) { if(v.name === passName) i = idx; }); if(i === false) throw new Error('No such pass'); passes.splice(i, 0, callback); }; ProxyServer.prototype.after = function(type, passName, callback) { if (type !== 'ws' && type !== 'web') { throw new Error('type must be `web` or `ws`'); } var passes = (type === 'ws') ? this.wsPasses : this.webPasses, i = false; passes.forEach(function(v, idx) { if(v.name === passName) i = idx; }); if(i === false) throw new Error('No such pass'); passes.splice(i++, 0, callback); }; } (httpProxy$3)); var httpProxyExports = httpProxy$3.exports; // Use explicit /index.js to help browserify negociation in require '/lib/http-proxy' (!) var ProxyServer = httpProxyExports.Server; /** * Creates the proxy server. * * Examples: * * httpProxy.createProxyServer({ .. }, 8000) * // => '{ web: [Function], ws: [Function] ... }' * * @param {Object} Options Config object passed to the proxy * * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests * * @api public */ function createProxyServer(options) { /* * `options` is needed and it must have the following layout: * * { * target : * forward: * agent : * ssl : * ws : * xfwd : * secure : * toProxy: * prependPath: * ignorePath: * localAddress : * changeOrigin: * preserveHeaderKeyCase: * auth : Basic authentication i.e. 'user:password' to compute an Authorization header. * hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects, Default: null. * autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false. * protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null. * } * * NOTE: `options.ws` and `options.ssl` are optional. * `options.target and `options.forward` cannot be * both missing * } */ return new ProxyServer(options); } ProxyServer.createProxyServer = createProxyServer; ProxyServer.createServer = createProxyServer; ProxyServer.createProxy = createProxyServer; createDebugger('vite:proxy'); var lib$3 = {exports: {}}; (function (module, exports) { var url = require$$0$9; module.exports = function historyApiFallback(options) { options = options || {}; var logger = getLogger(options); return function(req, res, next) { var headers = req.headers; if (req.method !== 'GET' && req.method !== 'HEAD') { logger( 'Not rewriting', req.method, req.url, 'because the method is not GET or HEAD.' ); return next(); } else if (!headers || typeof headers.accept !== 'string') { logger( 'Not rewriting', req.method, req.url, 'because the client did not send an HTTP accept header.' ); return next(); } else if (headers.accept.indexOf('application/json') === 0) { logger( 'Not rewriting', req.method, req.url, 'because the client prefers JSON.' ); return next(); } else if (!acceptsHtml(headers.accept, options)) { logger( 'Not rewriting', req.method, req.url, 'because the client does not accept HTML.' ); return next(); } var parsedUrl = url.parse(req.url); var rewriteTarget; options.rewrites = options.rewrites || []; for (var i = 0; i < options.rewrites.length; i++) { var rewrite = options.rewrites[i]; var match = parsedUrl.pathname.match(rewrite.from); if (match !== null) { rewriteTarget = evaluateRewriteRule(parsedUrl, match, rewrite.to, req); if(rewriteTarget.charAt(0) !== '/') { logger( 'We recommend using an absolute path for the rewrite target.', 'Received a non-absolute rewrite target', rewriteTarget, 'for URL', req.url ); } logger('Rewriting', req.method, req.url, 'to', rewriteTarget); req.url = rewriteTarget; return next(); } } var pathname = parsedUrl.pathname; if (pathname.lastIndexOf('.') > pathname.lastIndexOf('/') && options.disableDotRule !== true) { logger( 'Not rewriting', req.method, req.url, 'because the path includes a dot (.) character.' ); return next(); } rewriteTarget = options.index || '/index.html'; logger('Rewriting', req.method, req.url, 'to', rewriteTarget); req.url = rewriteTarget; next(); }; }; function evaluateRewriteRule(parsedUrl, match, rule, req) { if (typeof rule === 'string') { return rule; } else if (typeof rule !== 'function') { throw new Error('Rewrite rule can only be of type string or function.'); } return rule({ parsedUrl: parsedUrl, match: match, request: req }); } function acceptsHtml(header, options) { options.htmlAcceptHeaders = options.htmlAcceptHeaders || ['text/html', '*/*']; for (var i = 0; i < options.htmlAcceptHeaders.length; i++) { if (header.indexOf(options.htmlAcceptHeaders[i]) !== -1) { return true; } } return false; } function getLogger(options) { if (options && options.logger) { return options.logger; } else if (options && options.verbose) { // eslint-disable-next-line no-console return console.log.bind(console); } return function(){}; } } (lib$3)); createDebugger('vite:cache'); createDebugger('vite:time'); createDebugger('vite:config'); promisify$5(fs$l__default.realpath); createRequire$1(import.meta.url); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var src = {exports: {}}; var browser = {exports: {}}; /** * Helpers. */ var ms; var hasRequiredMs; function requireMs () { if (hasRequiredMs) return ms; hasRequiredMs = 1; var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ ms = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + 'd'; } if (msAbs >= h) { return Math.round(ms / h) + 'h'; } if (msAbs >= m) { return Math.round(ms / m) + 'm'; } if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, 'day'); } if (msAbs >= h) { return plural(ms, msAbs, h, 'hour'); } if (msAbs >= m) { return plural(ms, msAbs, m, 'minute'); } if (msAbs >= s) { return plural(ms, msAbs, s, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } return ms; } var common; var hasRequiredCommon; function requireCommon () { if (hasRequiredCommon) return common; hasRequiredCommon = 1; /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = requireMs(); createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; let i; const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); const len = split.length; for (i = 0; i < len; i++) { if (!split[i]) { // ignore empty strings continue; } namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } let i; let len; for (i = 0, len = createDebug.skips.length; i < len; i++) { if (createDebug.skips[i].test(name)) { return false; } } for (i = 0, len = createDebug.names.length; i < len; i++) { if (createDebug.names[i].test(name)) { return true; } } return false; } /** * Convert regexp to namespace * * @param {RegExp} regxep * @return {String} namespace * @api private */ function toNamespace(regexp) { return regexp.toString() .substring(2, regexp.toString().length - 2) .replace(/\.\*\?$/, '*'); } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } common = setup; return common; } /* eslint-env browser */ var hasRequiredBrowser; function requireBrowser () { if (hasRequiredBrowser) return browser.exports; hasRequiredBrowser = 1; (function (module, exports) { /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = requireCommon()(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; } (browser, browser.exports)); return browser.exports; } var node = {exports: {}}; var hasFlag; var hasRequiredHasFlag; function requireHasFlag () { if (hasRequiredHasFlag) return hasFlag; hasRequiredHasFlag = 1; hasFlag = (flag, argv) => { argv = argv || process.argv; const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const pos = argv.indexOf(prefix + flag); const terminatorPos = argv.indexOf('--'); return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); }; return hasFlag; } var supportsColor_1; var hasRequiredSupportsColor; function requireSupportsColor () { if (hasRequiredSupportsColor) return supportsColor_1; hasRequiredSupportsColor = 1; const os = require$$2$1; const hasFlag = requireHasFlag(); const env = process.env; let forceColor; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { forceColor = false; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { forceColor = true; } if ('FORCE_COLOR' in env) { forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor(stream) { if (forceColor === false) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (stream && !stream.isTTY && forceColor !== true) { return 0; } const min = forceColor ? 1 : 0; if (process.platform === 'win32') { // Node.js 7.5.0 is the first version of Node.js to include a patch to // libuv that enables 256 color output on Windows. Anything earlier and it // won't work. However, here we target Node.js 8 at minimum as it is an LTS // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows // release that supports 256 colors. Windows 10 build 14931 is the first release // that supports 16m/TrueColor. const osRelease = os.release().split('.'); if ( Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env) { const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } if (env.TERM === 'dumb') { return min; } return min; } function getSupportLevel(stream) { const level = supportsColor(stream); return translateLevel(level); } supportsColor_1 = { supportsColor: getSupportLevel, stdout: getSupportLevel(process.stdout), stderr: getSupportLevel(process.stderr) }; return supportsColor_1; } /** * Module dependencies. */ var hasRequiredNode; function requireNode () { if (hasRequiredNode) return node.exports; hasRequiredNode = 1; (function (module, exports) { const tty = require$$0$3__default; const util = require$$0$6; /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.destroy = util.deprecate( () => {}, 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' ); /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = requireSupportsColor(); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.format()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util.format(...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = requireCommon()(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; } (node, node.exports)); return node.exports; } /** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { src.exports = requireBrowser(); } else { src.exports = requireNode(); } var srcExports = src.exports; var debug$1 = /*@__PURE__*/getDefaultExportFromCjs(srcExports); const debug = debug$1('vite-plugin-svelte-inspector'); /** @type {import('.').Options} */ const defaultInspectorOptions = { toggleKeyCombo: process.platform === 'darwin' ? 'meta-shift' : 'control-shift', navKeys: { parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' }, openKey: 'Enter', holdMode: true, showToggleButton: 'active', toggleButtonPos: 'top-right', customStyles: true }; /** * @param {import('vite').ResolvedConfig} config * @returns {Partial | boolean | void} */ function parseEnvironmentOptions(config) { const env = loadEnv(config.mode, config.envDir ?? process.cwd(), 'SVELTE_INSPECTOR'); const options = env?.SVELTE_INSPECTOR_OPTIONS; const toggle = env?.SVELTE_INSPECTOR_TOGGLE; if (options) { try { const parsed = JSON.parse(options); const parsedType = typeof parsed; if (parsedType === 'boolean') { return parsed; } else if (parsedType === 'object') { if (Array.isArray(parsed)) { throw new Error('invalid type, expected object map but got array'); } const parsedKeys = Object.keys(parsed); const defaultKeys = Object.keys(defaultInspectorOptions); const unknownKeys = parsedKeys.filter((k) => !defaultKeys.includes(k)); if (unknownKeys.length) { config.logger.warn( `[vite-plugin-svelte-inspector] ignoring unknown options in environment SVELTE_INSPECTOR_OPTIONS: ${unknownKeys.join( ', ' )}` ); for (const key of unknownKeys) { delete parsed[key]; } } debug('loaded environment config', parsed); return parsed; } } catch (e) { config.logger.error( `[vite-plugin-svelte-inspector] failed to parse inspector options from environment SVELTE_INSPECTOR_OPTIONS="${options}"\n${e}` ); } } else if (toggle) { const keyConfig = { toggleKeyCombo: toggle }; debug('loaded environment config', keyConfig); return keyConfig; } } const postfixRE = /[?#].*$/s; /** * @param {string} url */ function cleanUrl(url) { return url.replace(postfixRE, ''); } function getInspectorPath() { const pluginPath = normalizePath$3(require$$0$4.dirname(fileURLToPath$1(import.meta.url))); return pluginPath.replace( /\/vite-plugin-svelte-inspector\/src$/, '/vite-plugin-svelte-inspector/src/runtime/' ); } /** @type {import('.').svelteInspector} */ function svelteInspector(options) { const inspectorPath = getInspectorPath(); debug(`svelte inspector path: ${inspectorPath}`); /** @type {import('vite').ResolvedConfig} */ let viteConfig; /** @type {import('.').Options} */ let inspectorOptions; let disabled = false; return { name: 'vite-plugin-svelte-inspector', apply: 'serve', enforce: 'pre', configResolved(config) { viteConfig = config; const environmentOptions = parseEnvironmentOptions(config); if (environmentOptions === false) { debug(`environment options set to false, inspector disabled`); disabled = true; return; } // Handle config from svelte.config.js through vite-plugin-svelte const vps = config.plugins.find((p) => p.name === 'vite-plugin-svelte'); const configFileOptions = vps?.api?.options?.inspector; // vite-plugin-svelte can only pass options through it's `api` instead of `options`. // that means this plugin could be created but should be disabled, so we check this case here. if (vps && !options && !configFileOptions && !environmentOptions) { debug(`vite-plugin-svelte didn't pass options, inspector disabled`); disabled = true; return; } if (environmentOptions === true) { inspectorOptions = defaultInspectorOptions; } else { inspectorOptions = { ...defaultInspectorOptions, ...configFileOptions, ...options, ...(environmentOptions || {}) }; } inspectorOptions.__internal = { base: config.base?.replace(/\/$/, '') || '' }; }, async resolveId(importee, _, options) { if (options?.ssr || disabled) { return; } if (importee.startsWith('virtual:svelte-inspector-options')) { return importee; } else if (importee.startsWith('virtual:svelte-inspector-path:')) { return importee.replace('virtual:svelte-inspector-path:', inspectorPath); } }, async load(id, options) { if (options?.ssr || disabled) { return; } if (id === 'virtual:svelte-inspector-options') { return `export default ${JSON.stringify(inspectorOptions ?? {})}`; } else if (id.startsWith(inspectorPath)) { // read file ourselves to avoid getting shut out by vites fs.allow check const file = cleanUrl(id); if (require$$0__default__default.existsSync(id)) { return await require$$0__default__default.promises.readFile(file, 'utf-8'); } else { viteConfig.logger.error( `[vite-plugin-svelte-inspector] failed to find svelte-inspector: ${id}` ); } } }, transform(code, id, options) { if (options?.ssr || disabled) { return; } if (id.includes('vite/dist/client/client.mjs')) { return { code: `${code}\nimport('virtual:svelte-inspector-path:load-inspector.js')` }; } } }; } // contains synchronous API only so it can be exported as CJS and ESM /** @type {import('..').isDepIncluded} */ function isDepIncluded(dep, optimizeDepsInclude) { return optimizeDepsInclude.some((id) => parseIncludeStr(id) === dep) } /** @type {import('..').isDepExcluded} */ function isDepExcluded(dep, optimizeDepsExclude) { dep = parseIncludeStr(dep); return optimizeDepsExclude.some( (id) => id === dep || dep.startsWith(`${id}/`) ) } /** @type {import('..').isDepNoExternaled} */ function isDepNoExternaled(dep, ssrNoExternal) { if (ssrNoExternal === true) { return true } else { return isMatch(dep, ssrNoExternal) } } /** @type {import('..').isDepExternaled} */ function isDepExternaled(dep, ssrExternal) { return ssrExternal.includes(dep) } /** * @param {string} raw could be "foo" or "foo > bar" etc */ function parseIncludeStr(raw) { const lastArrow = raw.lastIndexOf('>'); return lastArrow === -1 ? raw : raw.slice(lastArrow + 1).trim() } /** * @param {string} target * @param {string | RegExp | (string | RegExp)[]} pattern */ function isMatch(target, pattern) { if (Array.isArray(pattern)) { return pattern.some((p) => isMatch(target, p)) } else if (typeof pattern === 'string') { return target === pattern } else if (pattern instanceof RegExp) { return pattern.test(target) } } var sync$2 = { isDepIncluded, isDepExcluded, isDepNoExternaled, isDepExternaled }; /** @type {import('pnpapi')} */ let pnp; if (process.versions.pnp) { try { const { createRequire } = (await import('module')).default; pnp = createRequire(import.meta.url)('pnpapi'); } catch {} } /** @type {import('..').crawlFrameworkPkgs} */ async function crawlFrameworkPkgs(options) { const pkgJsonPath = await findClosestPkgJsonPath(options.root); if (!pkgJsonPath) { // @ts-expect-error don't throw in deno as package.json is not required if (typeof Deno !== 'undefined') { return { optimizeDeps: { include: [], exclude: [] }, ssr: { noExternal: [], external: [] } } } else { throw new Error(`Cannot find package.json from ${options.root}`) } } const pkgJson = await readJson(pkgJsonPath).catch((e) => { throw new Error(`Unable to read ${pkgJsonPath}`, { cause: e }) }); /** @type {string[]} */ let optimizeDepsInclude = []; /** @type {string[]} */ let optimizeDepsExclude = []; /** @type {string[]} */ let ssrNoExternal = []; /** @type {string[]} */ let ssrExternal = []; await crawl(pkgJsonPath, pkgJson); // respect vite user config if (options.viteUserConfig) { // remove includes that are explicitly excluded in optimizeDeps const _optimizeDepsExclude = options.viteUserConfig?.optimizeDeps?.exclude; if (_optimizeDepsExclude) { optimizeDepsInclude = optimizeDepsInclude.filter( (dep) => !sync$2.isDepExcluded(dep, _optimizeDepsExclude) ); } // remove excludes that are explicitly included in optimizeDeps const _optimizeDepsInclude = options.viteUserConfig?.optimizeDeps?.include; if (_optimizeDepsInclude) { optimizeDepsExclude = optimizeDepsExclude.filter( (dep) => !sync$2.isDepIncluded(dep, _optimizeDepsInclude) ); } // remove noExternals that are explicitly externalized const _ssrExternal = options.viteUserConfig?.ssr?.external; if (_ssrExternal) { ssrNoExternal = ssrNoExternal.filter( (dep) => !sync$2.isDepExternaled(dep, _ssrExternal) ); } // remove externals that are explicitly noExternal const _ssrNoExternal = options.viteUserConfig?.ssr?.noExternal; if (_ssrNoExternal) { ssrExternal = ssrExternal.filter( (dep) => !sync$2.isDepNoExternaled(dep, _ssrNoExternal) ); } } return { optimizeDeps: { include: optimizeDepsInclude, exclude: optimizeDepsExclude }, ssr: { noExternal: ssrNoExternal, external: ssrExternal } } /** * crawl the package.json dependencies for framework packages. rules: * 1. a framework package should be `optimizeDeps.exclude` and `ssr.noExternal`. * 2. the deps of the framework package should be `optimizeDeps.include` and `ssr.external` * unless the dep is also a framework package, in which case do no1 & no2 recursively. * 3. any non-framework packages that aren't imported by a framework package can be skipped entirely. * 4. a semi-framework package is like a framework package, except it isn't `optimizeDeps.exclude`, * but only applies `ssr.noExternal`. * @param {string} pkgJsonPath * @param {Record} pkgJson * @param {string[]} [parentDepNames] */ async function crawl(pkgJsonPath, pkgJson, parentDepNames = []) { const isRoot = parentDepNames.length === 0; /** @type {string[]} */ let deps = [ ...Object.keys(pkgJson.dependencies || {}), ...(isRoot ? Object.keys(pkgJson.devDependencies || {}) : []) ]; deps = deps.filter((dep) => { // skip circular deps if (parentDepNames.includes(dep)) { return false } const isFrameworkPkg = options.isFrameworkPkgByName?.(dep); const isSemiFrameworkPkg = options.isSemiFrameworkPkgByName?.(dep); if (isFrameworkPkg) { // framework packages should be excluded from optimization as esbuild can't handle them. // otherwise it'll cause https://github.com/vitejs/vite/issues/3910 optimizeDepsExclude.push(dep); // framework packages should be noExternal so that they go through vite's transformation // pipeline, since nodejs can't support them. ssrNoExternal.push(dep); } else if (isSemiFrameworkPkg) { // semi-framework packages should do the same except for optimization exclude as they // aren't needed to work (they don't contain raw framework components) ssrNoExternal.push(dep); } // only those that are explictly false can skip crawling since we don't need to do anything // special for them if (isFrameworkPkg === false || isSemiFrameworkPkg === false) { return false } // if `true`, we need to crawl the nested deps to deep include and ssr externalize them in dev. // if `undefined`, it's the same as "i don't know". we need to crawl and find the package.json // to find out. else { return true } }); const promises = deps.map(async (dep) => { const depPkgJsonPath = await findDepPkgJsonPath(dep, pkgJsonPath); if (!depPkgJsonPath) return const depPkgJson = await readJson(depPkgJsonPath).catch(() => {}); if (!depPkgJson) return // fast path if this dep is already a framework dep based on the filter condition above const cachedIsFrameworkPkg = ssrNoExternal.includes(dep); if (cachedIsFrameworkPkg) { return crawl(depPkgJsonPath, depPkgJson, parentDepNames.concat(dep)) } // check if this dep is a framework dep, if so, track and crawl it const isFrameworkPkg = options.isFrameworkPkgByJson?.(depPkgJson); const isSemiFrameworkPkg = options.isSemiFrameworkPkgByJson?.(depPkgJson); if (isFrameworkPkg || isSemiFrameworkPkg) { // see explanation in filter condition above if (isFrameworkPkg) { optimizeDepsExclude.push(dep); ssrNoExternal.push(dep); } else if (isSemiFrameworkPkg) { ssrNoExternal.push(dep); } return crawl(depPkgJsonPath, depPkgJson, parentDepNames.concat(dep)) } // if we're crawling in a non-root state, the parent is 100% a framework package // because of the above if block. in this case, if it's dep of a non-framework // package, handle special cases for them. if (!isRoot) { // deep include it if it's a CJS package, so it becomes ESM and vite is happy. if (await pkgNeedsOptimization(depPkgJson, depPkgJsonPath)) { optimizeDepsInclude.push(parentDepNames.concat(dep).join(' > ')); } // also externalize it in dev so it doesn't trip vite's SSR transformation. // we do in dev only as build cannot access deep external packages in strict // dependency installations, such as pnpm. if (!options.isBuild && !ssrExternal.includes(dep)) { ssrExternal.push(dep); } } }); await Promise.all(promises); } } /** @type {import('..').findDepPkgJsonPath} */ async function findDepPkgJsonPath(dep, parent) { if (pnp) { try { const depRoot = pnp.resolveToUnqualified(dep, parent); if (!depRoot) return undefined return path$o$1.join(depRoot, 'package.json') } catch { return undefined } } let root = parent; while (root) { const pkg = path$o$1.join(root, 'node_modules', dep, 'package.json'); try { await fsp.access(pkg); // use 'node:fs' version to match 'vite:resolve' and avoid realpath.native quirk // https://github.com/sveltejs/vite-plugin-svelte/issues/525#issuecomment-1355551264 return fs$l__default.realpathSync(pkg) } catch {} const nextRoot = path$o$1.dirname(root); if (nextRoot === root) break root = nextRoot; } return undefined } /** @type {import('..').findClosestPkgJsonPath} */ async function findClosestPkgJsonPath(dir, predicate = undefined) { if (dir.endsWith('package.json')) { dir = path$o$1.dirname(dir); } while (dir) { const pkg = path$o$1.join(dir, 'package.json'); try { const stat = await fsp.stat(pkg); if (stat.isFile() && (!predicate || (await predicate(pkg)))) { return pkg } } catch {} const nextDir = path$o$1.dirname(dir); if (nextDir === dir) break dir = nextDir; } return undefined } /** @type {import('..').pkgNeedsOptimization} */ async function pkgNeedsOptimization(pkgJson, pkgJsonPath) { // only optimize if is cjs, using the below as heuristic // see https://github.com/sveltejs/vite-plugin-svelte/issues/162 if (pkgJson.module || pkgJson.exports) return false // if have main, ensure entry is js so vite can prebundle it // see https://github.com/sveltejs/vite-plugin-svelte/issues/233 if (pkgJson.main) { const entryExt = path$o$1.extname(pkgJson.main); return !entryExt || entryExt === '.js' || entryExt === '.cjs' } // check if has implicit index.js entrypoint to prebundle // see https://github.com/sveltejs/vite-plugin-svelte/issues/281 // see https://github.com/solidjs/vite-plugin-solid/issues/70#issuecomment-1306488154 try { await fsp.access(path$o$1.join(path$o$1.dirname(pkgJsonPath), 'index.js')); return true } catch { return false } } /** * @param {string} findDepPkgJsonPath * @returns {Promise>} */ async function readJson(findDepPkgJsonPath) { return JSON.parse(await fsp.readFile(findDepPkgJsonPath, 'utf8')) } let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true; if (typeof process !== 'undefined') { ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {}); isTTY = process.stdout && process.stdout.isTTY; } const $ = { enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && ( FORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY ) }; function init(x, y) { let rgx = new RegExp(`\\x1b\\[${y}m`, 'g'); let open = `\x1b[${x}m`, close = `\x1b[${y}m`; return function (txt) { if (!$.enabled || txt == null) return txt; return open + (!!~(''+txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close; }; } const red = init(31, 39); const yellow = init(33, 39); const cyan = init(36, 39); /* eslint-disable no-console */ /** @type {import('../types/log.d.ts').LogLevel[]} */ const levels = ['debug', 'info', 'warn', 'error', 'silent']; const prefix = 'vite-plugin-svelte'; /** @type {Record} */ const loggers = { debug: { log: debug$1(`vite:${prefix}`), enabled: false, isDebug: true }, info: { color: cyan, log: console.log, enabled: true }, warn: { color: yellow, log: console.warn, enabled: true }, error: { color: red, log: console.error, enabled: true }, silent: { enabled: false } }; /** @type {import('../types/log.d.ts').LogLevel} */ let _level = 'info'; /** * @param {import('../types/log.d.ts').LogLevel} level * @returns {void} */ function setLevel(level) { if (level === _level) { return; } const levelIndex = levels.indexOf(level); if (levelIndex > -1) { _level = level; for (let i = 0; i < levels.length; i++) { loggers[levels[i]].enabled = i >= levelIndex; } } else { _log(loggers.error, `invalid log level: ${level} `); } } /** * @param {any} logger * @param {string} message * @param {any} [payload] * @param {string} [namespace] * @returns */ function _log(logger, message, payload, namespace) { if (!logger.enabled) { return; } if (logger.isDebug) { const log = namespace ? logger.log.extend(namespace) : logger.log; payload !== undefined ? log(message, payload) : log(message); } else { logger.log( logger.color( `${new Date().toLocaleTimeString()} [${prefix}${ namespace ? `:${namespace}` : '' }] ${message}` ) ); if (payload) { logger.log(payload); } } } /** * @param {import('../types/log.d.ts').LogLevel} level * @returns {import('../types/log.d.ts').LogFn} */ function createLogger(level) { const logger = loggers[level]; const logFn = /** @type {import('../types/log.d.ts').LogFn} */ (_log.bind(null, logger)); /** @type {Set} */ const logged = new Set(); /** @type {import('../types/log.d.ts').SimpleLogFn} */ const once = function (message, payload, namespace) { if (!logger.enabled || logged.has(message)) { return; } logged.add(message); logFn.apply(null, [message, payload, namespace]); }; Object.defineProperty(logFn, 'enabled', { get() { return logger.enabled; } }); Object.defineProperty(logFn, 'once', { get() { return once; } }); return logFn; } const log = { debug: createLogger('debug'), info: createLogger('info'), warn: createLogger('warn'), error: createLogger('error'), setLevel }; /** * @param {import('../types/id.d.ts').SvelteRequest | import('../types/id.d.ts').SvelteModuleRequest} svelteRequest * @param {import('svelte/types/compiler/interfaces').Warning[]} warnings * @param {import('../types/options.d.ts').ResolvedOptions} options */ function logCompilerWarnings(svelteRequest, warnings, options) { const { emitCss, onwarn, isBuild } = options; const sendViaWS = !isBuild && options.experimental?.sendWarningsToBrowser; let warn = isBuild ? warnBuild : warnDev; /** @type {import('svelte/types/compiler/interfaces').Warning[]} */ const handledByDefaultWarn = []; const notIgnored = warnings?.filter((w) => !ignoreCompilerWarning(w, isBuild, emitCss)); const extra = buildExtraWarnings(warnings, isBuild); const allWarnings = [...notIgnored, ...extra]; if (sendViaWS) { const _warn = warn; /** @type {(w: import('svelte/types/compiler/interfaces').Warning) => void} */ warn = (w) => { handledByDefaultWarn.push(w); _warn(w); }; } allWarnings.forEach((warning) => { if (onwarn) { onwarn(warning, warn); } else { warn(warning); } }); if (sendViaWS) { /** @type {import('../types/log.d.ts').SvelteWarningsMessage} */ const message = { id: svelteRequest.id, filename: svelteRequest.filename, normalizedFilename: svelteRequest.normalizedFilename, timestamp: svelteRequest.timestamp, warnings: handledByDefaultWarn, // allWarnings filtered by warnings where onwarn did not call the default handler allWarnings, // includes warnings filtered by onwarn and our extra vite plugin svelte warnings rawWarnings: warnings // raw compiler output }; log.debug(`sending svelte:warnings message for ${svelteRequest.normalizedFilename}`); options.server?.ws?.send('svelte:warnings', message); } } /** * @param {import('svelte/types/compiler/interfaces').Warning} warning * @param {boolean} isBuild * @param {boolean} [emitCss] * @returns {boolean} */ function ignoreCompilerWarning(warning, isBuild, emitCss) { return ( (!emitCss && warning.code === 'css-unused-selector') || // same as rollup-plugin-svelte (!isBuild && isNoScopableElementWarning(warning)) ); } /** * * @param {import('svelte/types/compiler/interfaces').Warning} warning * @returns {boolean} */ function isNoScopableElementWarning(warning) { // see https://github.com/sveltejs/vite-plugin-svelte/issues/153 return warning.code === 'css-unused-selector' && warning.message.includes('"*"'); } /** * * @param {import('svelte/types/compiler/interfaces').Warning[]} warnings * @param {boolean} isBuild * @returns {import('svelte/types/compiler/interfaces').Warning[]} */ function buildExtraWarnings(warnings, isBuild) { const extraWarnings = []; if (!isBuild) { const noScopableElementWarnings = warnings.filter((w) => isNoScopableElementWarning(w)); if (noScopableElementWarnings.length > 0) { // in case there are multiple, use last one as that is the one caused by our *{} rule const noScopableElementWarning = noScopableElementWarnings[noScopableElementWarnings.length - 1]; extraWarnings.push({ ...noScopableElementWarning, code: 'vite-plugin-svelte-css-no-scopable-elements', message: "No scopable elements found in template. If you're using global styles in the style tag, you should move it into an external stylesheet file and import it in JS. See https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md#where-should-i-put-my-global-styles." }); } } return extraWarnings; } /** * @param {import('svelte/types/compiler/interfaces').Warning} w */ function warnDev(w) { log.info.enabled && log.info(buildExtendedLogMessage(w)); } /** * @param {import('svelte/types/compiler/interfaces').Warning} w */ function warnBuild(w) { log.warn.enabled && log.warn(buildExtendedLogMessage(w), w.frame); } /** * @param {import('svelte/types/compiler/interfaces').Warning} w */ function buildExtendedLogMessage(w) { const parts = []; if (w.filename) { parts.push(w.filename); } if (w.start) { parts.push(':', w.start.line, ':', w.start.column); } if (w.message) { if (parts.length > 0) { parts.push(' '); } parts.push(w.message); } return parts.join(''); } /** * @param {string} namespace * @returns {boolean} */ function isDebugNamespaceEnabled(namespace) { return debug$1.enabled(`vite:${prefix}:${namespace}`); } /** * convert an error thrown by svelte.compile to a RollupError so that vite displays it in a user friendly way * @param {import('svelte/types/compiler/interfaces').Warning & Error} error a svelte compiler error, which is a mix of Warning and an error * @param {import('../types/options.d.ts').ResolvedOptions} options * @returns {import('vite').Rollup.RollupError} the converted error */ function toRollupError(error, options) { const { filename, frame, start, code, name, stack } = error; /** @type {import('vite').Rollup.RollupError} */ const rollupError = { name, // needed otherwise sveltekit coalesce_to_error turns it into a string id: filename, message: buildExtendedLogMessage(error), // include filename:line:column so that it's clickable frame: formatFrameForVite(frame), code, stack: options.isBuild || options.isDebug || !frame ? stack : '' }; if (start) { rollupError.loc = { line: start.line, column: start.column, file: filename }; } return rollupError; } /** * convert an error thrown by svelte.compile to an esbuild PartialMessage * @param {import('svelte/types/compiler/interfaces').Warning & Error} error a svelte compiler error, which is a mix of Warning and an error * @param {import('../types/options.d.ts').ResolvedOptions} options * @returns {import('esbuild').PartialMessage} the converted error */ function toESBuildError(error, options) { const { filename, frame, start, stack } = error; /** @type {import('esbuild').PartialMessage} */ const partialMessage = { text: buildExtendedLogMessage(error) }; if (start) { partialMessage.location = { line: start.line, column: start.column, file: filename, lineText: lineFromFrame(start.line, frame) // needed to get a meaningful error message on cli }; } if (options.isBuild || options.isDebug || !frame) { partialMessage.detail = stack; } return partialMessage; } /** * extract line with number from codeframe * * @param {number} lineNo * @param {string} [frame] * @returns {string} */ function lineFromFrame(lineNo, frame) { if (!frame) { return ''; } const lines = frame.split('\n'); const errorLine = lines.find((line) => line.trimStart().startsWith(`${lineNo}: `)); return errorLine ? errorLine.substring(errorLine.indexOf(': ') + 3) : ''; } /** * vite error overlay expects a specific format to show frames * this reformats svelte frame (colon separated, less whitespace) * to one that vite displays on overlay ( pipe separated, more whitespace) * e.g. * ``` * 1: foo * 2: bar; * ^ * 3: baz * ``` * to * ``` * 1 | foo * 2 | bar; * ^ * 3 | baz * ``` * @see https://github.com/vitejs/vite/blob/96591bf9989529de839ba89958755eafe4c445ae/packages/vite/src/client/overlay.ts#L116 * @param {string} [frame] * @returns {string} */ function formatFrameForVite(frame) { if (!frame) { return ''; } return frame .split('\n') .map((line) => (line.match(/^\s+\^/) ? ' ' + line : ' ' + line.replace(':', ' | '))) .join('\n'); } /** * Vite-specific HMR handling * * @param {Function} compileSvelte * @param {import('vite').HmrContext} ctx * @param {import('./types/id.d.ts').SvelteRequest} svelteRequest * @param {import('./utils/vite-plugin-svelte-cache').VitePluginSvelteCache} cache * @param {import('./types/options.d.ts').ResolvedOptions} options * @returns {Promise} */ async function handleHotUpdate(compileSvelte, ctx, svelteRequest, cache, options) { if (!cache.has(svelteRequest)) { // file hasn't been requested yet (e.g. async component) log.debug(`handleHotUpdate called before initial transform for ${svelteRequest.id}`); return; } const { read, server, modules } = ctx; const cachedJS = cache.getJS(svelteRequest); const cachedCss = cache.getCSS(svelteRequest); const content = await read(); /** @type {import('./types/compile.d.ts').CompileData} */ let compileData; try { compileData = await compileSvelte(svelteRequest, content, options); cache.update(compileData); } catch (e) { cache.setError(svelteRequest, e); throw toRollupError(e, options); } const affectedModules = [...modules]; const cssIdx = modules.findIndex((m) => m.id === svelteRequest.cssId); if (cssIdx > -1) { const cssUpdated = cssChanged(cachedCss, compileData.compiled.css); if (!cssUpdated) { log.debug(`skipping unchanged css for ${svelteRequest.cssId}`); affectedModules.splice(cssIdx, 1); } } const jsIdx = modules.findIndex((m) => m.id === svelteRequest.id); if (jsIdx > -1) { const jsUpdated = jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename); if (!jsUpdated) { log.debug(`skipping unchanged js for ${svelteRequest.id}`); affectedModules.splice(jsIdx, 1); // transform won't be called, log warnings here logCompilerWarnings(svelteRequest, compileData.compiled.warnings, options); } } // TODO is this enough? see also: https://github.com/vitejs/vite/issues/2274 const ssrModulesToInvalidate = affectedModules.filter((m) => !!m.ssrTransformResult); if (ssrModulesToInvalidate.length > 0) { log.debug(`invalidating modules ${ssrModulesToInvalidate.map((m) => m.id).join(', ')}`); ssrModulesToInvalidate.forEach((moduleNode) => server.moduleGraph.invalidateModule(moduleNode)); } if (affectedModules.length > 0) { log.debug( `handleHotUpdate for ${svelteRequest.id} result: ${affectedModules .map((m) => m.id) .join(', ')}` ); } return affectedModules; } /** * @param {import('./types/compile.d.ts').Code} [prev] * @param {import('./types/compile.d.ts').Code} [next] * @returns {boolean} */ function cssChanged(prev, next) { return !isCodeEqual(prev?.code, next?.code); } /** * @param {import('./types/compile.d.ts').Code} [prev] * @param {import('./types/compile.d.ts').Code} [next] * @param {string} [filename] * @returns {boolean} */ function jsChanged(prev, next, filename) { const prevJs = prev?.code; const nextJs = next?.code; const isStrictEqual = isCodeEqual(prevJs, nextJs); if (isStrictEqual) { return false; } const isLooseEqual = isCodeEqual(normalizeJsCode$1(prevJs), normalizeJsCode$1(nextJs)); if (!isStrictEqual && isLooseEqual) { log.warn( `ignoring compiler output js change for ${filename} as it is equal to previous output after normalization` ); } return !isLooseEqual; } /** * @param {string} [prev] * @param {string} [next] * @returns {boolean} */ function isCodeEqual(prev, next) { if (!prev && !next) { return true; } if ((!prev && next) || (prev && !next)) { return false; } return prev === next; } /** * remove code that only changes metadata and does not require a js update for the component to keep working * * 1) add_location() calls. These add location metadata to elements, only used by some dev tools * 2) ... maybe more (or less) in the future * * @param {string} [code] * @returns {string | undefined} */ function normalizeJsCode$1(code) { if (!code) { return code; } return code.replace(/\s*\badd_location\s*\([^)]*\)\s*;?/g, ''); } const globalName = '___SVELTE_HMR_HOT_API'; const globalAdapterName = '___SVELTE_HMR_HOT_API_PROXY_ADAPTER'; const defaultHotOptions = { // preserve all local state preserveLocalState: false, // escape hatchs from preservation of local state // // disable preservation of state for this component noPreserveStateKey: ['@hmr:reset', '@!hmr'], // enable preservation of state for all variables in this component preserveAllLocalStateKey: '@hmr:keep-all', // enable preservation of state for a given variable (must be inline or // above the target variable or variables; can be repeated) preserveLocalStateKey: '@hmr:keep', // don't reload on fatal error noReload: false, // try to recover after runtime errors during component init // defaults to false because some runtime errors are fatal and require a full reload optimistic: false, // auto accept modules of components that have named exports (i.e. exports // from context="module") acceptNamedExports: true, // auto accept modules of components have accessors (either accessors compile // option, or ) -- this means that if you // set accessors compile option globally, you must also set this option to // true, or no component will be hot reloaded (but there are a lot of edge // cases that HMR can't support correctly with accessors) acceptAccessors: true, // only inject CSS instead of recreating components when only CSS changes injectCss: false, // to mitigate FOUC between dispose (remove stylesheet) and accept cssEjectDelay: 100, // Svelte Native mode native: false, // name of the adapter import binding importAdapterName: globalAdapterName, // disable runtime error overlay noOverlay: false, // set to true on systems that supports them, to avoid useless caught / // managed (but still...) exceptions, by using Svelte's current_component // instead of get_current_component allowLiveBinding: false, // use acceptExports instead of accept, to fix support of context:module partialAccept: false, }; const defaultHotApi = 'hot-api-esm.js'; const json = JSON.stringify; const posixify = file => file.replace(/[/\\]/g, '/'); const renderApplyHmr = ({ id, cssId, nonCssHash, hotOptions: { injectCss, partialAccept, _accept = partialAccept ? "acceptExports(['default'])" : 'accept()', }, hotOptionsJson, hotApiImport, adapterImport, importAdapterName, meta, acceptable, preserveLocalState, emitCss, imports = [ `import * as ${globalName} from ${JSON.stringify(hotApiImport)}`, `import { adapter as ${importAdapterName} } from ${JSON.stringify(adapterImport)}`, ], }) => // this silly formatting keeps all original characters in their position, // thus saving us from having to provide a sourcemap // // NOTE the `if (false) accept()` line is for tools that wants to see the // accept call in the actual accepted module to enable HMR (Vite and, I // believe, Snowpack 3) // `${imports.join(';')};${` if (${meta} && ${meta}.hot) { ${acceptable ? `if (false) ${meta}.hot.${_accept};` : ''}; $2 = ${globalName}.applyHmr({ m: ${meta}, id: ${json(id)}, hotOptions: ${hotOptionsJson}, Component: $2, ProxyAdapter: ${importAdapterName}, acceptable: ${json(acceptable)}, preserveLocalState: ${json(preserveLocalState)}, ${cssId ? `cssId: ${json(cssId)},` : ''} ${nonCssHash ? `nonCssHash: ${json(nonCssHash)},` : ''} emitCss: ${json(emitCss)}, }); } ` .split('\n') .map(x => x.trim()) .filter(Boolean) .join(' ')} export default $2; ${ // NOTE when doing CSS only voodoo, we have to inject the stylesheet as soon // as the component is loaded because Svelte normally do that when a component // is instantiated, but we might already have instances in the large when a // component is loaded with HMR cssId && injectCss && !emitCss ? ` if (typeof add_css !== 'undefined' && !document.getElementById(${json( cssId )})) add_css();` : `` } `; // replace from last occurrence of the splitter const replaceLast = (string, splitter, regex, replacer) => { const lastIndex = string.lastIndexOf(splitter); return ( string.slice(0, lastIndex) + string.slice(lastIndex).replace(regex, replacer) ) }; // https://github.com/darkskyapp/string-hash/blob/master/index.js // (via https://github.com/sveltejs/svelte/blob/91d758e35b2b2154512ddd11e6b6d9d65708a99e/src/compiler/compile/utils/hash.ts#L2) const stringHashcode = str => { let hash = 5381; let i = str.length; while (i--) hash = ((hash << 5) - hash) ^ str.charCodeAt(i); return (hash >>> 0).toString(36) }; const normalizeJsCode = (code, cssHash) => code // ignore css hashes in the code (that have changed, necessarily) .replace(new RegExp('\\b' + cssHash + '\\b', 'g'), '') // Svelte now adds locations in dev mode, code locations can change when // CSS change, but we're unaffected (not real behaviour changes) .replace(/\badd_location\s*\([^)]*\)\s*;?/g, ''); const parseCssId = (code, compileOptions = {}, parseHash, originalCode) => { // the regex matching is very pretty conservative 'cause I don't want to // match something else by error... I'm probably make it more lax if I have // to fix it 3 times in a single week ¯\_(ツ)_/¯ let match = /^function add_css\(\) \{[\s\S]*?^}/m.exec(code); if (!match) { // guard: injectCss is off, no need to compute hashes if (!parseHash) return {} // guard: compile.css is true, so we should have found the add_css function, // something unexpected is unraveling here, fall back to caution if (compileOptions.css) return {} // trying to get CSS id the same way as Svelte does it match = /]*>([\s\S]*)<\/\s*style\s*>/.exec(originalCode); const cssHash = match && match[1] ? stringHashcode(match[1]) : null; if (!cssHash) return {} return { cssId: `svelte-${cssHash}-style`, nonCssHash: stringHashcode(normalizeJsCode(code, cssHash)), } } const codeExceptCSS = code.slice(0, match.index) + code.slice(match.index + match[0].length); match = /\bstyle\.id\s*=\s*(['"])([^'"]*)\1/.exec(match[0]); const cssId = match ? match[2] : null; if (!parseHash || !cssId) return { cssId } const cssHash = cssId.split('-')[1]; const nonCssHash = stringHashcode(normalizeJsCode(codeExceptCSS, cssHash)); return { cssId, nonCssHash } }; const isNamedExport = v => v.export_name && v.module; const isProp = v => v.export_name && !v.module; const resolvePackageImport = (name = 'svelte-hmr', version = '') => { const versionSpec = version ? '@' + version : ''; return target => `${name}${versionSpec}/${target}` }; const createMakeHot$1 = ({ resolveAbsoluteImport, pkg = {} }) => ({ // NOTE hotOptions can be customized by end user through plugin options, while // options passed to this function can only customized by the plugin implementer // // meta can be 'import.meta' or 'module' // const createMakeHot = (hotApi = defaultHotApi, options) => { walk, meta = 'import.meta', hotApi: customHotApi = '', adapter: customAdapter = '', // use absolute file paths to import runtime deps of svelte-hmr // - pnpm needs absolute paths because svelte-hmr, being a transitive dep via // the bundler plugin, is not directly importable from user's project // (see https://github.com/rixo/svelte-hmr/issues/11) // - Snowpack source=remote needs a version number, otherwise it will try to // load import, resulting in a possible version mismatch between the code // transform and the runtime // (see: https://github.com/rixo/svelte-hmr/issues/27#issuecomment-800142127) absoluteImports = true, versionNonAbsoluteImports = true, hotOptions: hotOptionsArg = {}, }) => { const hotOptions = { ...defaultHotOptions, ...hotOptionsArg }; const hotOptionsJson = JSON.stringify(hotOptions); // NOTE Native adapter cannot be required in code (as opposed to this // generated code) because it requires modules from NativeScript's code that // are not resolvable for non-native users (and those missing modules would // prevent webpack from building). // // careful with relative paths // (see https://github.com/rixo/svelte-hmr/issues/11) const defaultAdapter = hotOptions.native ? 'svelte-native/proxy-adapter-native.js' : 'proxy-adapter-dom.js'; const resolveImport = absoluteImports ? resolveAbsoluteImport : resolvePackageImport(pkg.name, versionNonAbsoluteImports && pkg.version); const adapterImport = posixify( customAdapter || resolveImport('runtime/' + defaultAdapter) ); const hotApiImport = posixify( customHotApi || resolveImport('runtime/' + defaultHotApi) ); const resolvePreserveLocalStateKey = ({ preserveLocalStateKey, compiled, }) => { const containsKey = comments => comments && comments.some(({ value }) => value.includes(preserveLocalStateKey)); const variables = new Set(); const addReference = node => { if (!node.name) { // eslint-disable-next-line no-console console.warn('Incorrect identifier for preserveLocalStateKey'); } variables.add(node.name); }; const processNodes = targets => targets.forEach(processNode); const processNode = node => { switch (node.type) { case 'Identifier': variables.add(node.name); return true case 'UpdateExpression': addReference(node.argument); return true case 'VariableDeclarator': addReference(node.id); return true case 'AssignmentExpression': processNode(node.left); return true case 'ExpressionStatement': processNode(node.expression); return true case 'VariableDeclaration': processNodes(node.declarations); return true case 'SequenceExpression': // ++, -- processNodes(node.expressions); return true } return false }; const stack = []; if (compiled.ast.instance) { walk(compiled.ast.instance, { leave() { stack.shift(); }, enter(node) { stack.unshift(node); if ( containsKey(node.leadingComments) || containsKey(node.trailingComments) ) { stack .slice(0, 3) .reverse() .some(processNode); } }, }); } return [...variables] }; const resolvePreserveLocalState = ({ hotOptions, originalCode, compiled, }) => { const { preserveLocalState, noPreserveStateKey, preserveLocalStateKey, preserveAllLocalStateKey, } = hotOptions; if (originalCode) { const hasKey = key => { const test = k => originalCode.indexOf(k) !== -1; return Array.isArray(key) ? key.some(test) : test(key) }; // noPreserveStateKey if (noPreserveStateKey && hasKey(noPreserveStateKey)) { return false } // preserveAllLocalStateKey if (preserveAllLocalStateKey && hasKey(preserveAllLocalStateKey)) { return true } // preserveLocalStateKey if (preserveLocalStateKey && hasKey(preserveLocalStateKey)) { // returns an array of variable names to preserve return resolvePreserveLocalStateKey({ preserveLocalStateKey, compiled }) } } // preserveLocalState if (preserveLocalState) { return true } return false }; const hasAccessorsOption = compiled => { if (!compiled.ast || !compiled.ast.html) return let accessors = false; walk(compiled.ast.html, { enter(node) { if (accessors) return if (node.type !== 'Options') return if (!node.attributes) return accessors = node.attributes.some( ({ name, value }) => name === 'accessors' && value ); }, }); return accessors }; const isAcceptable = (hotOptions, compileOptions, compiled) => { if (!compiled || !compileOptions) { // this should never happen, since it's the bundler plugins that control // what version of svelte-hmr they embark, and they should be kept up to // date with our API // // eslint-disable-next-line no-console console.warn( 'WARNING Your bundler plugin is outdated for this version of svelte-hmr' ); return true } const { vars } = compiled; // if the module has named exports (in context="module"), then we can't // auto accept the component, since all the consumers need to be aware of // the change (e.g. rerender with the new exports value) if (!hotOptions.acceptNamedExports && vars.some(isNamedExport)) { return false } // ...same for accessors: if accessible props change, then we need to // rerender/rerun all the consumers to reflect the change // // NOTE we can still accept components with no props, since they won't // have accessors... this is actually all we can safely accept in this case // if ( !hotOptions.acceptAccessors && // we test is we have props first, because searching for the // tag in the AST is probably the most expensive here vars.some(isProp) && (compileOptions.accessors || hasAccessorsOption(compiled)) ) { return false } return true }; const parseMakeHotArgs = args => { // case: named args (object) if (args.length === 1) return args[0] // case: legacy (positional) const [ id, compiledCode, hotOptions, compiled, originalCode, compileOptions, ] = args; return { id, compiledCode, hotOptions, compiled, originalCode, compileOptions, } }; function makeHot(...args) { const { id, compiledCode, compiled, originalCode, compileOptions, } = parseMakeHotArgs(args); const { importAdapterName, injectCss } = hotOptions; const emitCss = compileOptions && (compileOptions.css === false || compileOptions.css === 'external'); const preserveLocalState = resolvePreserveLocalState({ hotOptions, originalCode, compiled, }); const replacement = renderApplyHmr({ id, // adds cssId & nonCssHash ...((injectCss || !emitCss) && parseCssId(compiledCode, compileOptions, injectCss, originalCode)), hotOptions, hotOptionsJson, preserveLocalState, hotApiImport, adapterImport, importAdapterName, meta, acceptable: isAcceptable(hotOptions, compileOptions, compiled), // CSS is handled outside of Svelte: don't tamper with it! emitCss, }); // NOTE export default can appear in strings in use code // see: https://github.com/rixo/svelte-hmr/issues/34 return replaceLast( compiledCode, 'export default', /(\n?export default ([^;]*);)/, (match, $1, $2) => replacement.replace(/\$2/g, () => $2) ) } // rollup-plugin-svelte-hot needs hotApi path (for tests) // makeHot.hotApi = hotApi Object.defineProperty(makeHot, 'hotApi', { get() { // TODO makeHot.hotApi has been lost in 0.12 => 0.13... still needed? debugger // eslint-disable-line no-debugger return undefined }, }); return makeHot }; var makeHot = createMakeHot$1; var name$1 = "svelte-hmr"; var version$1 = "0.15.3"; var description = "Bundler agnostic HMR utils for Svelte 3"; var main = "index.js"; var author = "rixo "; var license = "ISC"; var homepage = "https://github.com/sveltejs/svelte-hmr"; var bugs = { url: "https://github.com/sveltejs/svelte-hmr/issues" }; var repository = { type: "git", url: "https://github.com/sveltejs/svelte-hmr", directory: "packages/svelte-hmr" }; var files = [ "index.js", "lib", "runtime" ]; var engines = { node: "^12.20 || ^14.13.1 || >= 16" }; var peerDependencies = { svelte: "^3.19.0 || ^4.0.0" }; var devDependencies = { dotenv: "^10.0.0", prettier: "^1.19.1", svelte: "^3.59.2", "tap-mocha-reporter": "^5.0.3", zoar: "^0.3.0", zorax: "^0.0.14" }; var scripts = { lint: "eslint '**/*.{js,cjs,mjs}'", "lint:fix": "pnpm run lint --fix", format: "prettier '**/*.{js,cjs,mjs}' --check", "format:fix": "pnpm run format --write", "test:fancy": "zoar --pipe 'tap-mocha-reporter spec'", test: "zoar --exit" }; var require$$2 = { name: name$1, version: version$1, description: description, main: main, author: author, license: license, homepage: homepage, bugs: bugs, repository: repository, files: files, engines: engines, peerDependencies: peerDependencies, devDependencies: devDependencies, scripts: scripts }; const __dirname = dirname$2(fileURLToPath$1(import.meta.url)); const createMakeHotFactory = makeHot; const { resolve } = require$$0$4; const { name, version } = require$$2; const resolveAbsoluteImport = target => resolve(__dirname, target); const createMakeHot = createMakeHotFactory({ pkg: { name, version }, resolveAbsoluteImport, }); var svelteHmr = { createMakeHot }; const hashes = Object.create(null); //TODO shorter? const hash_length = 12; /** * replaces +/= in base64 output so they don't interfere * * @param {string} input * @returns {string} base64 hash safe to use in any context */ function safeBase64Hash(input) { if (hashes[input]) { return hashes[input]; } //TODO if performance really matters, use a faster one like xx-hash etc. // should be evenly distributed because short input length and similarities in paths could cause collisions otherwise // OR DON'T USE A HASH AT ALL, what about a simple counter? const md5 = crypto$2.createHash('md5'); md5.update(input); const hash = toSafe(md5.digest('base64')).slice(0, hash_length); hashes[input] = hash; return hash; } /** @type {Record} */ const replacements = { '+': '-', '/': '_', '=': '' }; const replaceRE = new RegExp(`[${Object.keys(replacements).join('')}]`, 'g'); /** * @param {string} base64 * @returns {string} */ function toSafe(base64) { return base64.replace(replaceRE, (x) => replacements[x]); } const comma = ','.charCodeAt(0); const semicolon$1 = ';'.charCodeAt(0); const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; const intToChar = new Uint8Array(64); // 64 possible chars. const charToInt = new Uint8Array(128); // z is 122 in ASCII for (let i = 0; i < chars.length; i++) { const c = chars.charCodeAt(i); intToChar[i] = c; charToInt[c] = i; } // Provide a fallback for older environments. const td = typeof TextDecoder !== 'undefined' ? /* #__PURE__ */ new TextDecoder() : typeof Buffer !== 'undefined' ? { decode(buf) { const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); return out.toString(); }, } : { decode(buf) { let out = ''; for (let i = 0; i < buf.length; i++) { out += String.fromCharCode(buf[i]); } return out; }, }; function encode(decoded) { const state = new Int32Array(5); const bufLength = 1024 * 16; const subLength = bufLength - 36; const buf = new Uint8Array(bufLength); const sub = buf.subarray(0, subLength); let pos = 0; let out = ''; for (let i = 0; i < decoded.length; i++) { const line = decoded[i]; if (i > 0) { if (pos === bufLength) { out += td.decode(buf); pos = 0; } buf[pos++] = semicolon$1; } if (line.length === 0) continue; state[0] = 0; for (let j = 0; j < line.length; j++) { const segment = line[j]; // We can push up to 5 ints, each int can take at most 7 chars, and we // may push a comma. if (pos > subLength) { out += td.decode(sub); buf.copyWithin(0, subLength, pos); pos -= subLength; } if (j > 0) buf[pos++] = comma; pos = encodeInteger(buf, pos, state, segment, 0); // genColumn if (segment.length === 1) continue; pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn if (segment.length === 4) continue; pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex } } return out + td.decode(buf.subarray(0, pos)); } function encodeInteger(buf, pos, state, segment, j) { const next = segment[j]; let num = next - state[j]; state[j] = next; num = num < 0 ? (-num << 1) | 1 : num << 1; do { let clamped = num & 0b011111; num >>>= 5; if (num > 0) clamped |= 0b100000; buf[pos++] = intToChar[clamped]; } while (num > 0); return pos; } class BitSet { constructor(arg) { this.bits = arg instanceof BitSet ? arg.bits.slice() : []; } add(n) { this.bits[n >> 5] |= 1 << (n & 31); } has(n) { return !!(this.bits[n >> 5] & (1 << (n & 31))); } } class Chunk { constructor(start, end, content) { this.start = start; this.end = end; this.original = content; this.intro = ''; this.outro = ''; this.content = content; this.storeName = false; this.edited = false; { this.previous = null; this.next = null; } } appendLeft(content) { this.outro += content; } appendRight(content) { this.intro = this.intro + content; } clone() { const chunk = new Chunk(this.start, this.end, this.original); chunk.intro = this.intro; chunk.outro = this.outro; chunk.content = this.content; chunk.storeName = this.storeName; chunk.edited = this.edited; return chunk; } contains(index) { return this.start < index && index < this.end; } eachNext(fn) { let chunk = this; while (chunk) { fn(chunk); chunk = chunk.next; } } eachPrevious(fn) { let chunk = this; while (chunk) { fn(chunk); chunk = chunk.previous; } } edit(content, storeName, contentOnly) { this.content = content; if (!contentOnly) { this.intro = ''; this.outro = ''; } this.storeName = storeName; this.edited = true; return this; } prependLeft(content) { this.outro = content + this.outro; } prependRight(content) { this.intro = content + this.intro; } split(index) { const sliceIndex = index - this.start; const originalBefore = this.original.slice(0, sliceIndex); const originalAfter = this.original.slice(sliceIndex); this.original = originalBefore; const newChunk = new Chunk(index, this.end, originalAfter); newChunk.outro = this.outro; this.outro = ''; this.end = index; if (this.edited) { // after split we should save the edit content record into the correct chunk // to make sure sourcemap correct // For example: // ' test'.trim() // split -> ' ' + 'test' // ✔️ edit -> '' + 'test' // ✖️ edit -> 'test' + '' // TODO is this block necessary?... newChunk.edit('', false); this.content = ''; } else { this.content = originalBefore; } newChunk.next = this.next; if (newChunk.next) newChunk.next.previous = newChunk; newChunk.previous = this; this.next = newChunk; return newChunk; } toString() { return this.intro + this.content + this.outro; } trimEnd(rx) { this.outro = this.outro.replace(rx, ''); if (this.outro.length) return true; const trimmed = this.content.replace(rx, ''); if (trimmed.length) { if (trimmed !== this.content) { this.split(this.start + trimmed.length).edit('', undefined, true); if (this.edited) { // save the change, if it has been edited this.edit(trimmed, this.storeName, true); } } return true; } else { this.edit('', undefined, true); this.intro = this.intro.replace(rx, ''); if (this.intro.length) return true; } } trimStart(rx) { this.intro = this.intro.replace(rx, ''); if (this.intro.length) return true; const trimmed = this.content.replace(rx, ''); if (trimmed.length) { if (trimmed !== this.content) { const newChunk = this.split(this.end - trimmed.length); if (this.edited) { // save the change, if it has been edited newChunk.edit(trimmed, this.storeName, true); } this.edit('', undefined, true); } return true; } else { this.edit('', undefined, true); this.outro = this.outro.replace(rx, ''); if (this.outro.length) return true; } } } function getBtoa() { if (typeof window !== 'undefined' && typeof window.btoa === 'function') { return (str) => window.btoa(unescape(encodeURIComponent(str))); } else if (typeof Buffer === 'function') { return (str) => Buffer.from(str, 'utf-8').toString('base64'); } else { return () => { throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); }; } } const btoa$1 = /*#__PURE__*/ getBtoa(); class SourceMap { constructor(properties) { this.version = 3; this.file = properties.file; this.sources = properties.sources; this.sourcesContent = properties.sourcesContent; this.names = properties.names; this.mappings = encode(properties.mappings); if (typeof properties.x_google_ignoreList !== 'undefined') { this.x_google_ignoreList = properties.x_google_ignoreList; } } toString() { return JSON.stringify(this); } toUrl() { return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString()); } } function guessIndent(code) { const lines = code.split('\n'); const tabbed = lines.filter((line) => /^\t+/.test(line)); const spaced = lines.filter((line) => /^ {2,}/.test(line)); if (tabbed.length === 0 && spaced.length === 0) { return null; } // More lines tabbed than spaced? Assume tabs, and // default to tabs in the case of a tie (or nothing // to go on) if (tabbed.length >= spaced.length) { return '\t'; } // Otherwise, we need to guess the multiple const min = spaced.reduce((previous, current) => { const numSpaces = /^ +/.exec(current)[0].length; return Math.min(numSpaces, previous); }, Infinity); return new Array(min + 1).join(' '); } function getRelativePath(from, to) { const fromParts = from.split(/[/\\]/); const toParts = to.split(/[/\\]/); fromParts.pop(); // get dirname while (fromParts[0] === toParts[0]) { fromParts.shift(); toParts.shift(); } if (fromParts.length) { let i = fromParts.length; while (i--) fromParts[i] = '..'; } return fromParts.concat(toParts).join('/'); } const toString = Object.prototype.toString; function isObject$1(thing) { return toString.call(thing) === '[object Object]'; } function getLocator(source) { const originalLines = source.split('\n'); const lineOffsets = []; for (let i = 0, pos = 0; i < originalLines.length; i++) { lineOffsets.push(pos); pos += originalLines[i].length + 1; } return function locate(index) { let i = 0; let j = lineOffsets.length; while (i < j) { const m = (i + j) >> 1; if (index < lineOffsets[m]) { j = m; } else { i = m + 1; } } const line = i - 1; const column = index - lineOffsets[line]; return { line, column }; }; } const wordRegex = /\w/; class Mappings { constructor(hires) { this.hires = hires; this.generatedCodeLine = 0; this.generatedCodeColumn = 0; this.raw = []; this.rawSegments = this.raw[this.generatedCodeLine] = []; this.pending = null; } addEdit(sourceIndex, content, loc, nameIndex) { if (content.length) { let contentLineEnd = content.indexOf('\n', 0); let previousContentLineEnd = -1; while (contentLineEnd >= 0) { const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; if (nameIndex >= 0) { segment.push(nameIndex); } this.rawSegments.push(segment); this.generatedCodeLine += 1; this.raw[this.generatedCodeLine] = this.rawSegments = []; this.generatedCodeColumn = 0; previousContentLineEnd = contentLineEnd; contentLineEnd = content.indexOf('\n', contentLineEnd + 1); } const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; if (nameIndex >= 0) { segment.push(nameIndex); } this.rawSegments.push(segment); this.advance(content.slice(previousContentLineEnd + 1)); } else if (this.pending) { this.rawSegments.push(this.pending); this.advance(content); } this.pending = null; } addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { let originalCharIndex = chunk.start; let first = true; // when iterating each char, check if it's in a word boundary let charInHiresBoundary = false; while (originalCharIndex < chunk.end) { if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; if (this.hires === 'boundary') { // in hires "boundary", group segments per word boundary than per char if (wordRegex.test(original[originalCharIndex])) { // for first char in the boundary found, start the boundary by pushing a segment if (!charInHiresBoundary) { this.rawSegments.push(segment); charInHiresBoundary = true; } } else { // for non-word char, end the boundary by pushing a segment this.rawSegments.push(segment); charInHiresBoundary = false; } } else { this.rawSegments.push(segment); } } if (original[originalCharIndex] === '\n') { loc.line += 1; loc.column = 0; this.generatedCodeLine += 1; this.raw[this.generatedCodeLine] = this.rawSegments = []; this.generatedCodeColumn = 0; first = true; } else { loc.column += 1; this.generatedCodeColumn += 1; first = false; } originalCharIndex += 1; } this.pending = null; } advance(str) { if (!str) return; const lines = str.split('\n'); if (lines.length > 1) { for (let i = 0; i < lines.length - 1; i++) { this.generatedCodeLine++; this.raw[this.generatedCodeLine] = this.rawSegments = []; } this.generatedCodeColumn = 0; } this.generatedCodeColumn += lines[lines.length - 1].length; } } const n = '\n'; const warned = { insertLeft: false, insertRight: false, storeName: false, }; class MagicString { constructor(string, options = {}) { const chunk = new Chunk(0, string.length, string); Object.defineProperties(this, { original: { writable: true, value: string }, outro: { writable: true, value: '' }, intro: { writable: true, value: '' }, firstChunk: { writable: true, value: chunk }, lastChunk: { writable: true, value: chunk }, lastSearchedChunk: { writable: true, value: chunk }, byStart: { writable: true, value: {} }, byEnd: { writable: true, value: {} }, filename: { writable: true, value: options.filename }, indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, sourcemapLocations: { writable: true, value: new BitSet() }, storedNames: { writable: true, value: {} }, indentStr: { writable: true, value: undefined }, ignoreList: { writable: true, value: options.ignoreList }, }); this.byStart[0] = chunk; this.byEnd[string.length] = chunk; } addSourcemapLocation(char) { this.sourcemapLocations.add(char); } append(content) { if (typeof content !== 'string') throw new TypeError('outro content must be a string'); this.outro += content; return this; } appendLeft(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byEnd[index]; if (chunk) { chunk.appendLeft(content); } else { this.intro += content; } return this; } appendRight(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byStart[index]; if (chunk) { chunk.appendRight(content); } else { this.outro += content; } return this; } clone() { const cloned = new MagicString(this.original, { filename: this.filename }); let originalChunk = this.firstChunk; let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); while (originalChunk) { cloned.byStart[clonedChunk.start] = clonedChunk; cloned.byEnd[clonedChunk.end] = clonedChunk; const nextOriginalChunk = originalChunk.next; const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); if (nextClonedChunk) { clonedChunk.next = nextClonedChunk; nextClonedChunk.previous = clonedChunk; clonedChunk = nextClonedChunk; } originalChunk = nextOriginalChunk; } cloned.lastChunk = clonedChunk; if (this.indentExclusionRanges) { cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); } cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); cloned.intro = this.intro; cloned.outro = this.outro; return cloned; } generateDecodedMap(options) { options = options || {}; const sourceIndex = 0; const names = Object.keys(this.storedNames); const mappings = new Mappings(options.hires); const locate = getLocator(this.original); if (this.intro) { mappings.advance(this.intro); } this.firstChunk.eachNext((chunk) => { const loc = locate(chunk.start); if (chunk.intro.length) mappings.advance(chunk.intro); if (chunk.edited) { mappings.addEdit( sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1, ); } else { mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); } if (chunk.outro.length) mappings.advance(chunk.outro); }); return { file: options.file ? options.file.split(/[/\\]/).pop() : undefined, sources: [ options.source ? getRelativePath(options.file || '', options.source) : options.file || '', ], sourcesContent: options.includeContent ? [this.original] : undefined, names, mappings: mappings.raw, x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined, }; } generateMap(options) { return new SourceMap(this.generateDecodedMap(options)); } _ensureindentStr() { if (this.indentStr === undefined) { this.indentStr = guessIndent(this.original); } } _getRawIndentString() { this._ensureindentStr(); return this.indentStr; } getIndentString() { this._ensureindentStr(); return this.indentStr === null ? '\t' : this.indentStr; } indent(indentStr, options) { const pattern = /^[^\r\n]/gm; if (isObject$1(indentStr)) { options = indentStr; indentStr = undefined; } if (indentStr === undefined) { this._ensureindentStr(); indentStr = this.indentStr || '\t'; } if (indentStr === '') return this; // noop options = options || {}; // Process exclusion ranges const isExcluded = {}; if (options.exclude) { const exclusions = typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; exclusions.forEach((exclusion) => { for (let i = exclusion[0]; i < exclusion[1]; i += 1) { isExcluded[i] = true; } }); } let shouldIndentNextCharacter = options.indentStart !== false; const replacer = (match) => { if (shouldIndentNextCharacter) return `${indentStr}${match}`; shouldIndentNextCharacter = true; return match; }; this.intro = this.intro.replace(pattern, replacer); let charIndex = 0; let chunk = this.firstChunk; while (chunk) { const end = chunk.end; if (chunk.edited) { if (!isExcluded[charIndex]) { chunk.content = chunk.content.replace(pattern, replacer); if (chunk.content.length) { shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; } } } else { charIndex = chunk.start; while (charIndex < end) { if (!isExcluded[charIndex]) { const char = this.original[charIndex]; if (char === '\n') { shouldIndentNextCharacter = true; } else if (char !== '\r' && shouldIndentNextCharacter) { shouldIndentNextCharacter = false; if (charIndex === chunk.start) { chunk.prependRight(indentStr); } else { this._splitChunk(chunk, charIndex); chunk = chunk.next; chunk.prependRight(indentStr); } } } charIndex += 1; } } charIndex = chunk.end; chunk = chunk.next; } this.outro = this.outro.replace(pattern, replacer); return this; } insert() { throw new Error( 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)', ); } insertLeft(index, content) { if (!warned.insertLeft) { console.warn( 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead', ); // eslint-disable-line no-console warned.insertLeft = true; } return this.appendLeft(index, content); } insertRight(index, content) { if (!warned.insertRight) { console.warn( 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead', ); // eslint-disable-line no-console warned.insertRight = true; } return this.prependRight(index, content); } move(start, end, index) { if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself'); this._split(start); this._split(end); this._split(index); const first = this.byStart[start]; const last = this.byEnd[end]; const oldLeft = first.previous; const oldRight = last.next; const newRight = this.byStart[index]; if (!newRight && last === this.lastChunk) return this; const newLeft = newRight ? newRight.previous : this.lastChunk; if (oldLeft) oldLeft.next = oldRight; if (oldRight) oldRight.previous = oldLeft; if (newLeft) newLeft.next = first; if (newRight) newRight.previous = last; if (!first.previous) this.firstChunk = last.next; if (!last.next) { this.lastChunk = first.previous; this.lastChunk.next = null; } first.previous = newLeft; last.next = newRight || null; if (!newLeft) this.firstChunk = first; if (!newRight) this.lastChunk = last; return this; } overwrite(start, end, content, options) { options = options || {}; return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); } update(start, end, content, options) { if (typeof content !== 'string') throw new TypeError('replacement content must be a string'); while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; if (end > this.original.length) throw new Error('end is out of bounds'); if (start === end) throw new Error( 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead', ); this._split(start); this._split(end); if (options === true) { if (!warned.storeName) { console.warn( 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string', ); // eslint-disable-line no-console warned.storeName = true; } options = { storeName: true }; } const storeName = options !== undefined ? options.storeName : false; const overwrite = options !== undefined ? options.overwrite : false; if (storeName) { const original = this.original.slice(start, end); Object.defineProperty(this.storedNames, original, { writable: true, value: true, enumerable: true, }); } const first = this.byStart[start]; const last = this.byEnd[end]; if (first) { let chunk = first; while (chunk !== last) { if (chunk.next !== this.byStart[chunk.end]) { throw new Error('Cannot overwrite across a split point'); } chunk = chunk.next; chunk.edit('', false); } first.edit(content, storeName, !overwrite); } else { // must be inserting at the end const newChunk = new Chunk(start, end, '').edit(content, storeName); // TODO last chunk in the array may not be the last chunk, if it's moved... last.next = newChunk; newChunk.previous = last; } return this; } prepend(content) { if (typeof content !== 'string') throw new TypeError('outro content must be a string'); this.intro = content + this.intro; return this; } prependLeft(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byEnd[index]; if (chunk) { chunk.prependLeft(content); } else { this.intro = content + this.intro; } return this; } prependRight(index, content) { if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); this._split(index); const chunk = this.byStart[index]; if (chunk) { chunk.prependRight(content); } else { this.outro = content + this.outro; } return this; } remove(start, end) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; if (start === end) return this; if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); if (start > end) throw new Error('end must be greater than start'); this._split(start); this._split(end); let chunk = this.byStart[start]; while (chunk) { chunk.intro = ''; chunk.outro = ''; chunk.edit(''); chunk = end > chunk.end ? this.byStart[chunk.end] : null; } return this; } lastChar() { if (this.outro.length) return this.outro[this.outro.length - 1]; let chunk = this.lastChunk; do { if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; if (chunk.content.length) return chunk.content[chunk.content.length - 1]; if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; } while ((chunk = chunk.previous)); if (this.intro.length) return this.intro[this.intro.length - 1]; return ''; } lastLine() { let lineIndex = this.outro.lastIndexOf(n); if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); let lineStr = this.outro; let chunk = this.lastChunk; do { if (chunk.outro.length > 0) { lineIndex = chunk.outro.lastIndexOf(n); if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; lineStr = chunk.outro + lineStr; } if (chunk.content.length > 0) { lineIndex = chunk.content.lastIndexOf(n); if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; lineStr = chunk.content + lineStr; } if (chunk.intro.length > 0) { lineIndex = chunk.intro.lastIndexOf(n); if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; lineStr = chunk.intro + lineStr; } } while ((chunk = chunk.previous)); lineIndex = this.intro.lastIndexOf(n); if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; return this.intro + lineStr; } slice(start = 0, end = this.original.length) { while (start < 0) start += this.original.length; while (end < 0) end += this.original.length; let result = ''; // find start chunk let chunk = this.firstChunk; while (chunk && (chunk.start > start || chunk.end <= start)) { // found end chunk before start if (chunk.start < end && chunk.end >= end) { return result; } chunk = chunk.next; } if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); const startChunk = chunk; while (chunk) { if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { result += chunk.intro; } const containsEnd = chunk.start < end && chunk.end >= end; if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); const sliceStart = startChunk === chunk ? start - chunk.start : 0; const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; result += chunk.content.slice(sliceStart, sliceEnd); if (chunk.outro && (!containsEnd || chunk.end === end)) { result += chunk.outro; } if (containsEnd) { break; } chunk = chunk.next; } return result; } // TODO deprecate this? not really very useful snip(start, end) { const clone = this.clone(); clone.remove(0, start); clone.remove(end, clone.original.length); return clone; } _split(index) { if (this.byStart[index] || this.byEnd[index]) return; let chunk = this.lastSearchedChunk; const searchForward = index > chunk.end; while (chunk) { if (chunk.contains(index)) return this._splitChunk(chunk, index); chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; } } _splitChunk(chunk, index) { if (chunk.edited && chunk.content.length) { // zero-length edited chunks are a special case (overlapping replacements) const loc = getLocator(this.original)(index); throw new Error( `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`, ); } const newChunk = chunk.split(index); this.byEnd[index] = chunk; this.byStart[index] = newChunk; this.byEnd[newChunk.end] = newChunk; if (chunk === this.lastChunk) this.lastChunk = newChunk; this.lastSearchedChunk = chunk; return true; } toString() { let str = this.intro; let chunk = this.firstChunk; while (chunk) { str += chunk.toString(); chunk = chunk.next; } return str + this.outro; } isEmpty() { let chunk = this.firstChunk; do { if ( (chunk.intro.length && chunk.intro.trim()) || (chunk.content.length && chunk.content.trim()) || (chunk.outro.length && chunk.outro.trim()) ) return false; } while ((chunk = chunk.next)); return true; } length() { let chunk = this.firstChunk; let length = 0; do { length += chunk.intro.length + chunk.content.length + chunk.outro.length; } while ((chunk = chunk.next)); return length; } trimLines() { return this.trim('[\\r\\n]'); } trim(charType) { return this.trimStart(charType).trimEnd(charType); } trimEndAborted(charType) { const rx = new RegExp((charType || '\\s') + '+$'); this.outro = this.outro.replace(rx, ''); if (this.outro.length) return true; let chunk = this.lastChunk; do { const end = chunk.end; const aborted = chunk.trimEnd(rx); // if chunk was trimmed, we have a new lastChunk if (chunk.end !== end) { if (this.lastChunk === chunk) { this.lastChunk = chunk.next; } this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) return true; chunk = chunk.previous; } while (chunk); return false; } trimEnd(charType) { this.trimEndAborted(charType); return this; } trimStartAborted(charType) { const rx = new RegExp('^' + (charType || '\\s') + '+'); this.intro = this.intro.replace(rx, ''); if (this.intro.length) return true; let chunk = this.firstChunk; do { const end = chunk.end; const aborted = chunk.trimStart(rx); if (chunk.end !== end) { // special case... if (chunk === this.lastChunk) this.lastChunk = chunk.next; this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) return true; chunk = chunk.next; } while (chunk); return false; } trimStart(charType) { this.trimStartAborted(charType); return this; } hasChanged() { return this.original !== this.toString(); } _replaceRegexp(searchValue, replacement) { function getReplacement(match, str) { if (typeof replacement === 'string') { return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter if (i === '$') return '$'; if (i === '&') return match[0]; const num = +i; if (num < match.length) return match[+i]; return `$${i}`; }); } else { return replacement(...match, match.index, str, match.groups); } } function matchAll(re, str) { let match; const matches = []; while ((match = re.exec(str))) { matches.push(match); } return matches; } if (searchValue.global) { const matches = matchAll(searchValue, this.original); matches.forEach((match) => { if (match.index != null) this.overwrite( match.index, match.index + match[0].length, getReplacement(match, this.original), ); }); } else { const match = this.original.match(searchValue); if (match && match.index != null) this.overwrite( match.index, match.index + match[0].length, getReplacement(match, this.original), ); } return this; } _replaceString(string, replacement) { const { original } = this; const index = original.indexOf(string); if (index !== -1) { this.overwrite(index, index + string.length, replacement); } return this; } replace(searchValue, replacement) { if (typeof searchValue === 'string') { return this._replaceString(searchValue, replacement); } return this._replaceRegexp(searchValue, replacement); } _replaceAllString(string, replacement) { const { original } = this; const stringLength = string.length; for ( let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength) ) { this.overwrite(index, index + stringLength, replacement); } return this; } replaceAll(searchValue, replacement) { if (typeof searchValue === 'string') { return this._replaceAllString(searchValue, replacement); } if (!searchValue.global) { throw new TypeError( 'MagicString.prototype.replaceAll called with a non-global RegExp argument', ); } return this._replaceRegexp(searchValue, replacement); } } /** * this appends a *{} rule to component styles to force the svelte compiler to add style classes to all nodes * That means adding/removing class rules from