lib/condenser/processors/node_modules/rollup/dist/rollup.es.js in condenser-0.0.8 vs lib/condenser/processors/node_modules/rollup/dist/rollup.es.js in condenser-0.0.9

- old
+ new

@@ -1,20 +1,21 @@ /* @license - Rollup.js v1.20.2 - Sun, 25 Aug 2019 05:31:46 GMT - commit b1747e49d9659799a8c128d3052e5e5703362c37 + Rollup.js v1.28.0 + Sat, 04 Jan 2020 20:12:15 GMT - commit b99758b3a4617769f2371540e530536d5c246692 https://github.com/rollup/rollup Released under the MIT License. */ import util from 'util'; import path, { relative as relative$1, extname, basename, dirname, resolve, sep } from 'path'; -import { writeFile as writeFile$1, readdirSync, mkdirSync, readFile as readFile$1, lstatSync, realpathSync, statSync, watch as watch$1 } from 'fs'; +import { readFile as readFile$1, writeFile as writeFile$1, readdirSync, mkdirSync, lstatSync, realpathSync, statSync, watch as watch$1 } from 'fs'; import * as acorn__default from 'acorn'; import { Parser } from 'acorn'; +import { createHash as createHash$2 } from 'crypto'; import { EventEmitter } from 'events'; import module from 'module'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. @@ -47,559 +48,12 @@ function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } -var version = "1.20.2"; +var version = "1.28.0"; -var minimalisticAssert = assert; -function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -} -assert.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); -}; - -function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; -} - -var inherits_browser = createCommonjsModule(function (module) { - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } - else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () { }; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; - } -}); - -var inherits = createCommonjsModule(function (module) { - try { - var util$1 = util; - if (typeof util$1.inherits !== 'function') - throw ''; - module.exports = util$1.inherits; - } - catch (e) { - module.exports = inherits_browser; - } -}); - -var inherits_1 = inherits; -function isSurrogatePair(msg, i) { - if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { - return false; - } - if (i < 0 || i + 1 >= msg.length) { - return false; - } - return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00; -} -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg === 'string') { - if (!enc) { - // Inspired by stringToUtf8ByteArray() in closure-library by Google - // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143 - // Apache License 2.0 - // https://github.com/google/closure-library/blob/master/LICENSE - var p = 0; - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - if (c < 128) { - res[p++] = c; - } - else if (c < 2048) { - res[p++] = (c >> 6) | 192; - res[p++] = (c & 63) | 128; - } - else if (isSurrogatePair(msg, i)) { - c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF); - res[p++] = (c >> 18) | 240; - res[p++] = ((c >> 12) & 63) | 128; - res[p++] = ((c >> 6) & 63) | 128; - res[p++] = (c & 63) | 128; - } - else { - res[p++] = (c >> 12) | 224; - res[p++] = ((c >> 6) & 63) | 128; - res[p++] = (c & 63) | 128; - } - } - } - else if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } - } - else { - for (i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - } - return res; -} -var toArray_1 = toArray; -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -var toHex_1 = toHex; -function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; -} -var htonl_1 = htonl; -function toHex32(msg, endian) { - var res = ''; - for (var i = 0; i < msg.length; i++) { - var w = msg[i]; - if (endian === 'little') - w = htonl(w); - res += zero8(w.toString(16)); - } - return res; -} -var toHex32_1 = toHex32; -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -var zero2_1 = zero2; -function zero8(word) { - if (word.length === 7) - return '0' + word; - else if (word.length === 6) - return '00' + word; - else if (word.length === 5) - return '000' + word; - else if (word.length === 4) - return '0000' + word; - else if (word.length === 3) - return '00000' + word; - else if (word.length === 2) - return '000000' + word; - else if (word.length === 1) - return '0000000' + word; - else - return word; -} -var zero8_1 = zero8; -function join32(msg, start, end, endian) { - var len = end - start; - minimalisticAssert(len % 4 === 0); - var res = new Array(len / 4); - for (var i = 0, k = start; i < res.length; i++, k += 4) { - var w; - if (endian === 'big') - w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; - else - w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; - res[i] = w >>> 0; - } - return res; -} -var join32_1 = join32; -function split32(msg, endian) { - var res = new Array(msg.length * 4); - for (var i = 0, k = 0; i < msg.length; i++, k += 4) { - var m = msg[i]; - if (endian === 'big') { - res[k] = m >>> 24; - res[k + 1] = (m >>> 16) & 0xff; - res[k + 2] = (m >>> 8) & 0xff; - res[k + 3] = m & 0xff; - } - else { - res[k + 3] = m >>> 24; - res[k + 2] = (m >>> 16) & 0xff; - res[k + 1] = (m >>> 8) & 0xff; - res[k] = m & 0xff; - } - } - return res; -} -var split32_1 = split32; -function rotr32(w, b) { - return (w >>> b) | (w << (32 - b)); -} -var rotr32_1 = rotr32; -function rotl32(w, b) { - return (w << b) | (w >>> (32 - b)); -} -var rotl32_1 = rotl32; -function sum32(a, b) { - return (a + b) >>> 0; -} -var sum32_1 = sum32; -function sum32_3(a, b, c) { - return (a + b + c) >>> 0; -} -var sum32_3_1 = sum32_3; -function sum32_4(a, b, c, d) { - return (a + b + c + d) >>> 0; -} -var sum32_4_1 = sum32_4; -function sum32_5(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; -} -var sum32_5_1 = sum32_5; -function sum64(buf, pos, ah, al) { - var bh = buf[pos]; - var bl = buf[pos + 1]; - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - buf[pos] = hi >>> 0; - buf[pos + 1] = lo; -} -var sum64_1 = sum64; -function sum64_hi(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; -} -var sum64_hi_1 = sum64_hi; -function sum64_lo(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; -} -var sum64_lo_1 = sum64_lo; -function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - var hi = ah + bh + ch + dh + carry; - return hi >>> 0; -} -var sum64_4_hi_1 = sum64_4_hi; -function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; -} -var sum64_4_lo_1 = sum64_4_lo; -function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - lo = (lo + el) >>> 0; - carry += lo < el ? 1 : 0; - var hi = ah + bh + ch + dh + eh + carry; - return hi >>> 0; -} -var sum64_5_hi_1 = sum64_5_hi; -function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; - return lo >>> 0; -} -var sum64_5_lo_1 = sum64_5_lo; -function rotr64_hi(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; -} -var rotr64_hi_1 = rotr64_hi; -function rotr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -var rotr64_lo_1 = rotr64_lo; -function shr64_hi(ah, al, num) { - return ah >>> num; -} -var shr64_hi_1 = shr64_hi; -function shr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -var shr64_lo_1 = shr64_lo; -var utils = { - inherits: inherits_1, - toArray: toArray_1, - toHex: toHex_1, - htonl: htonl_1, - toHex32: toHex32_1, - zero2: zero2_1, - zero8: zero8_1, - join32: join32_1, - split32: split32_1, - rotr32: rotr32_1, - rotl32: rotl32_1, - sum32: sum32_1, - sum32_3: sum32_3_1, - sum32_4: sum32_4_1, - sum32_5: sum32_5_1, - sum64: sum64_1, - sum64_hi: sum64_hi_1, - sum64_lo: sum64_lo_1, - sum64_4_hi: sum64_4_hi_1, - sum64_4_lo: sum64_4_lo_1, - sum64_5_hi: sum64_5_hi_1, - sum64_5_lo: sum64_5_lo_1, - rotr64_hi: rotr64_hi_1, - rotr64_lo: rotr64_lo_1, - shr64_hi: shr64_hi_1, - shr64_lo: shr64_lo_1 -}; - -function BlockHash() { - this.pending = null; - this.pendingTotal = 0; - this.blockSize = this.constructor.blockSize; - this.outSize = this.constructor.outSize; - this.hmacStrength = this.constructor.hmacStrength; - this.padLength = this.constructor.padLength / 8; - this.endian = 'big'; - this._delta8 = this.blockSize / 8; - this._delta32 = this.blockSize / 32; -} -var BlockHash_1 = BlockHash; -BlockHash.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils.toArray(msg, enc); - if (!this.pending) - this.pending = msg; - else - this.pending = this.pending.concat(msg); - this.pendingTotal += msg.length; - // Enough data, try updating - if (this.pending.length >= this._delta8) { - msg = this.pending; - // Process pending data in blocks - var r = msg.length % this._delta8; - this.pending = msg.slice(msg.length - r, msg.length); - if (this.pending.length === 0) - this.pending = null; - msg = utils.join32(msg, 0, msg.length - r, this.endian); - for (var i = 0; i < msg.length; i += this._delta32) - this._update(msg, i, i + this._delta32); - } - return this; -}; -BlockHash.prototype.digest = function digest(enc) { - this.update(this._pad()); - minimalisticAssert(this.pending === null); - return this._digest(enc); -}; -BlockHash.prototype._pad = function pad() { - var len = this.pendingTotal; - var bytes = this._delta8; - var k = bytes - ((len + this.padLength) % bytes); - var res = new Array(k + this.padLength); - res[0] = 0x80; - for (var i = 1; i < k; i++) - res[i] = 0; - // Append length - len <<= 3; - if (this.endian === 'big') { - for (var t = 8; t < this.padLength; t++) - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = (len >>> 24) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = len & 0xff; - } - else { - res[i++] = len & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 24) & 0xff; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - for (t = 8; t < this.padLength; t++) - res[i++] = 0; - } - return res; -}; -var common = { - BlockHash: BlockHash_1 -}; - -var rotr32$1 = utils.rotr32; -function ft_1(s, x, y, z) { - if (s === 0) - return ch32(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32(x, y, z); -} -var ft_1_1 = ft_1; -function ch32(x, y, z) { - return (x & y) ^ ((~x) & z); -} -var ch32_1 = ch32; -function maj32(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); -} -var maj32_1 = maj32; -function p32(x, y, z) { - return x ^ y ^ z; -} -var p32_1 = p32; -function s0_256(x) { - return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22); -} -var s0_256_1 = s0_256; -function s1_256(x) { - return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25); -} -var s1_256_1 = s1_256; -function g0_256(x) { - return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3); -} -var g0_256_1 = g0_256; -function g1_256(x) { - return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10); -} -var g1_256_1 = g1_256; -var common$1 = { - ft_1: ft_1_1, - ch32: ch32_1, - maj32: maj32_1, - p32: p32_1, - s0_256: s0_256_1, - s1_256: s1_256_1, - g0_256: g0_256_1, - g1_256: g1_256_1 -}; - -var sum32$1 = utils.sum32; -var sum32_4$1 = utils.sum32_4; -var sum32_5$1 = utils.sum32_5; -var ch32$1 = common$1.ch32; -var maj32$1 = common$1.maj32; -var s0_256$1 = common$1.s0_256; -var s1_256$1 = common$1.s1_256; -var g0_256$1 = common$1.g0_256; -var g1_256$1 = common$1.g1_256; -var BlockHash$1 = common.BlockHash; -var sha256_K = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]; -function SHA256() { - if (!(this instanceof SHA256)) - return new SHA256(); - BlockHash$1.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); -} -utils.inherits(SHA256, BlockHash$1); -var _256 = SHA256; -SHA256.blockSize = 512; -SHA256.outSize = 256; -SHA256.hmacStrength = 192; -SHA256.padLength = 64; -SHA256.prototype._update = function _update(msg, start) { - var W = this.W; - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - for (; i < W.length; i++) - W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]); - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - var f = this.h[5]; - var g = this.h[6]; - var h = this.h[7]; - minimalisticAssert(this.k.length === W.length); - for (i = 0; i < W.length; i++) { - var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]); - var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c)); - h = g; - g = f; - f = e; - e = sum32$1(d, T1); - d = c; - c = b; - b = a; - a = sum32$1(T1, T2); - } - this.h[0] = sum32$1(this.h[0], a); - this.h[1] = sum32$1(this.h[1], b); - this.h[2] = sum32$1(this.h[2], c); - this.h[3] = sum32$1(this.h[3], d); - this.h[4] = sum32$1(this.h[4], e); - this.h[5] = sum32$1(this.h[5], f); - this.h[6] = sum32$1(this.h[6], g); - this.h[7] = sum32$1(this.h[7], h); -}; -SHA256.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - var charToInteger = {}; var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; for (var i = 0; i < chars.length; i++) { charToInteger[chars.charCodeAt(i)] = i; } @@ -727,10 +181,20 @@ result += chars[clamped]; } while (num > 0); return result; } +var BitSet = function BitSet(arg) { + this.bits = arg instanceof BitSet ? arg.bits.slice() : []; +}; +BitSet.prototype.add = function add(n) { + this.bits[Math.floor(n / BITS)] |= 1 << n % BITS; +}; +BitSet.prototype.has = function has(n) { + return !!(this.bits[Math.floor(n / BITS)] & (1 << n % BITS)); +}; +var BITS = 32; var Chunk = function Chunk(start, end, content) { this.start = start; this.end = end; this.original = content; this.intro = ''; @@ -972,28 +436,31 @@ }; Mappings.prototype.addUneditedChunk = function addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { var originalCharIndex = chunk.start; var first = true; while (originalCharIndex < chunk.end) { - if (this.hires || first || sourcemapLocations[originalCharIndex]) { + 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; - first = false; } - this.pending = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + this.pending = sourceIndex > 0 + ? [this.generatedCodeColumn, sourceIndex, loc.line, loc.column] + : null; }; Mappings.prototype.advance = function advance(str) { if (!str) { return; } @@ -1026,19 +493,19 @@ 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: {} }, + sourcemapLocations: { writable: true, value: new BitSet() }, storedNames: { writable: true, value: {} }, indentStr: { writable: true, value: guessIndent(string) } }); this.byStart[0] = chunk; this.byEnd[string.length] = chunk; }; MagicString.prototype.addSourcemapLocation = function addSourcemapLocation(char) { - this.sourcemapLocations[char] = true; + this.sourcemapLocations.add(char); }; MagicString.prototype.append = function append(content) { if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); } @@ -1091,13 +558,13 @@ } cloned.lastChunk = clonedChunk; if (this.indentExclusionRanges) { cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); } - Object.keys(this.sourcemapLocations).forEach(function (loc) { - cloned.sourcemapLocations[loc] = true; - }); + cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); + cloned.intro = this.intro; + cloned.outro = this.outro; return cloned; }; MagicString.prototype.generateDecodedMap = function generateDecodedMap(options) { var this$1 = this; options = options || {}; @@ -1855,10 +1322,559 @@ } } while (!source.content.trimEndAborted(charType)); return this; }; +var minimalisticAssert = assert; +function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +} +assert.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); +}; + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var inherits_browser = createCommonjsModule(function (module) { + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } + else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () { }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } +}); + +var inherits = createCommonjsModule(function (module) { + try { + var util$1 = util; + if (typeof util$1.inherits !== 'function') + throw ''; + module.exports = util$1.inherits; + } + catch (e) { + module.exports = inherits_browser; + } +}); + +var inherits_1 = inherits; +function isSurrogatePair(msg, i) { + if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { + return false; + } + if (i < 0 || i + 1 >= msg.length) { + return false; + } + return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00; +} +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg === 'string') { + if (!enc) { + // Inspired by stringToUtf8ByteArray() in closure-library by Google + // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143 + // Apache License 2.0 + // https://github.com/google/closure-library/blob/master/LICENSE + var p = 0; + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + if (c < 128) { + res[p++] = c; + } + else if (c < 2048) { + res[p++] = (c >> 6) | 192; + res[p++] = (c & 63) | 128; + } + else if (isSurrogatePair(msg, i)) { + c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF); + res[p++] = (c >> 18) | 240; + res[p++] = ((c >> 12) & 63) | 128; + res[p++] = ((c >> 6) & 63) | 128; + res[p++] = (c & 63) | 128; + } + else { + res[p++] = (c >> 12) | 224; + res[p++] = ((c >> 6) & 63) | 128; + res[p++] = (c & 63) | 128; + } + } + } + else if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + } + else { + for (i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + } + return res; +} +var toArray_1 = toArray; +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +var toHex_1 = toHex; +function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; +} +var htonl_1 = htonl; +function toHex32(msg, endian) { + var res = ''; + for (var i = 0; i < msg.length; i++) { + var w = msg[i]; + if (endian === 'little') + w = htonl(w); + res += zero8(w.toString(16)); + } + return res; +} +var toHex32_1 = toHex32; +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +var zero2_1 = zero2; +function zero8(word) { + if (word.length === 7) + return '0' + word; + else if (word.length === 6) + return '00' + word; + else if (word.length === 5) + return '000' + word; + else if (word.length === 4) + return '0000' + word; + else if (word.length === 3) + return '00000' + word; + else if (word.length === 2) + return '000000' + word; + else if (word.length === 1) + return '0000000' + word; + else + return word; +} +var zero8_1 = zero8; +function join32(msg, start, end, endian) { + var len = end - start; + minimalisticAssert(len % 4 === 0); + var res = new Array(len / 4); + for (var i = 0, k = start; i < res.length; i++, k += 4) { + var w; + if (endian === 'big') + w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; + else + w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; + res[i] = w >>> 0; + } + return res; +} +var join32_1 = join32; +function split32(msg, endian) { + var res = new Array(msg.length * 4); + for (var i = 0, k = 0; i < msg.length; i++, k += 4) { + var m = msg[i]; + if (endian === 'big') { + res[k] = m >>> 24; + res[k + 1] = (m >>> 16) & 0xff; + res[k + 2] = (m >>> 8) & 0xff; + res[k + 3] = m & 0xff; + } + else { + res[k + 3] = m >>> 24; + res[k + 2] = (m >>> 16) & 0xff; + res[k + 1] = (m >>> 8) & 0xff; + res[k] = m & 0xff; + } + } + return res; +} +var split32_1 = split32; +function rotr32(w, b) { + return (w >>> b) | (w << (32 - b)); +} +var rotr32_1 = rotr32; +function rotl32(w, b) { + return (w << b) | (w >>> (32 - b)); +} +var rotl32_1 = rotl32; +function sum32(a, b) { + return (a + b) >>> 0; +} +var sum32_1 = sum32; +function sum32_3(a, b, c) { + return (a + b + c) >>> 0; +} +var sum32_3_1 = sum32_3; +function sum32_4(a, b, c, d) { + return (a + b + c + d) >>> 0; +} +var sum32_4_1 = sum32_4; +function sum32_5(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; +} +var sum32_5_1 = sum32_5; +function sum64(buf, pos, ah, al) { + var bh = buf[pos]; + var bl = buf[pos + 1]; + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + buf[pos] = hi >>> 0; + buf[pos + 1] = lo; +} +var sum64_1 = sum64; +function sum64_hi(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; +} +var sum64_hi_1 = sum64_hi; +function sum64_lo(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; +} +var sum64_lo_1 = sum64_lo; +function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + var hi = ah + bh + ch + dh + carry; + return hi >>> 0; +} +var sum64_4_hi_1 = sum64_4_hi; +function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; +} +var sum64_4_lo_1 = sum64_4_lo; +function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + lo = (lo + el) >>> 0; + carry += lo < el ? 1 : 0; + var hi = ah + bh + ch + dh + eh + carry; + return hi >>> 0; +} +var sum64_5_hi_1 = sum64_5_hi; +function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + return lo >>> 0; +} +var sum64_5_lo_1 = sum64_5_lo; +function rotr64_hi(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; +} +var rotr64_hi_1 = rotr64_hi; +function rotr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +} +var rotr64_lo_1 = rotr64_lo; +function shr64_hi(ah, al, num) { + return ah >>> num; +} +var shr64_hi_1 = shr64_hi; +function shr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +} +var shr64_lo_1 = shr64_lo; +var utils = { + inherits: inherits_1, + toArray: toArray_1, + toHex: toHex_1, + htonl: htonl_1, + toHex32: toHex32_1, + zero2: zero2_1, + zero8: zero8_1, + join32: join32_1, + split32: split32_1, + rotr32: rotr32_1, + rotl32: rotl32_1, + sum32: sum32_1, + sum32_3: sum32_3_1, + sum32_4: sum32_4_1, + sum32_5: sum32_5_1, + sum64: sum64_1, + sum64_hi: sum64_hi_1, + sum64_lo: sum64_lo_1, + sum64_4_hi: sum64_4_hi_1, + sum64_4_lo: sum64_4_lo_1, + sum64_5_hi: sum64_5_hi_1, + sum64_5_lo: sum64_5_lo_1, + rotr64_hi: rotr64_hi_1, + rotr64_lo: rotr64_lo_1, + shr64_hi: shr64_hi_1, + shr64_lo: shr64_lo_1 +}; + +function BlockHash() { + this.pending = null; + this.pendingTotal = 0; + this.blockSize = this.constructor.blockSize; + this.outSize = this.constructor.outSize; + this.hmacStrength = this.constructor.hmacStrength; + this.padLength = this.constructor.padLength / 8; + this.endian = 'big'; + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; +} +var BlockHash_1 = BlockHash; +BlockHash.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; + // Enough data, try updating + if (this.pending.length >= this._delta8) { + msg = this.pending; + // Process pending data in blocks + var r = msg.length % this._delta8; + this.pending = msg.slice(msg.length - r, msg.length); + if (this.pending.length === 0) + this.pending = null; + msg = utils.join32(msg, 0, msg.length - r, this.endian); + for (var i = 0; i < msg.length; i += this._delta32) + this._update(msg, i, i + this._delta32); + } + return this; +}; +BlockHash.prototype.digest = function digest(enc) { + this.update(this._pad()); + minimalisticAssert(this.pending === null); + return this._digest(enc); +}; +BlockHash.prototype._pad = function pad() { + var len = this.pendingTotal; + var bytes = this._delta8; + var k = bytes - ((len + this.padLength) % bytes); + var res = new Array(k + this.padLength); + res[0] = 0x80; + for (var i = 1; i < k; i++) + res[i] = 0; + // Append length + len <<= 3; + if (this.endian === 'big') { + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = (len >>> 24) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = len & 0xff; + } + else { + res[i++] = len & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 24) & 0xff; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + for (t = 8; t < this.padLength; t++) + res[i++] = 0; + } + return res; +}; +var common = { + BlockHash: BlockHash_1 +}; + +var rotr32$1 = utils.rotr32; +function ft_1(s, x, y, z) { + if (s === 0) + return ch32(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32(x, y, z); +} +var ft_1_1 = ft_1; +function ch32(x, y, z) { + return (x & y) ^ ((~x) & z); +} +var ch32_1 = ch32; +function maj32(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); +} +var maj32_1 = maj32; +function p32(x, y, z) { + return x ^ y ^ z; +} +var p32_1 = p32; +function s0_256(x) { + return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22); +} +var s0_256_1 = s0_256; +function s1_256(x) { + return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25); +} +var s1_256_1 = s1_256; +function g0_256(x) { + return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3); +} +var g0_256_1 = g0_256; +function g1_256(x) { + return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10); +} +var g1_256_1 = g1_256; +var common$1 = { + ft_1: ft_1_1, + ch32: ch32_1, + maj32: maj32_1, + p32: p32_1, + s0_256: s0_256_1, + s1_256: s1_256_1, + g0_256: g0_256_1, + g1_256: g1_256_1 +}; + +var sum32$1 = utils.sum32; +var sum32_4$1 = utils.sum32_4; +var sum32_5$1 = utils.sum32_5; +var ch32$1 = common$1.ch32; +var maj32$1 = common$1.maj32; +var s0_256$1 = common$1.s0_256; +var s1_256$1 = common$1.s1_256; +var g0_256$1 = common$1.g0_256; +var g1_256$1 = common$1.g1_256; +var BlockHash$1 = common.BlockHash; +var sha256_K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]; +function SHA256() { + if (!(this instanceof SHA256)) + return new SHA256(); + BlockHash$1.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); +} +utils.inherits(SHA256, BlockHash$1); +var _256 = SHA256; +SHA256.blockSize = 512; +SHA256.outSize = 256; +SHA256.hmacStrength = 192; +SHA256.padLength = 64; +SHA256.prototype._update = function _update(msg, start) { + var W = this.W; + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]); + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + var f = this.h[5]; + var g = this.h[6]; + var h = this.h[7]; + minimalisticAssert(this.k.length === W.length); + for (i = 0; i < W.length; i++) { + var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]); + var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c)); + h = g; + g = f; + f = e; + e = sum32$1(d, T1); + d = c; + c = b; + b = a; + a = sum32$1(T1, T2); + } + this.h[0] = sum32$1(this.h[0], a); + this.h[1] = sum32$1(this.h[1], b); + this.h[2] = sum32$1(this.h[2], c); + this.h[3] = sum32$1(this.h[3], d); + this.h[4] = sum32$1(this.h[4], e); + this.h[5] = sum32$1(this.h[5], f); + this.h[6] = sum32$1(this.h[6], g); + this.h[7] = sum32$1(this.h[7], h); +}; +SHA256.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +const createHash = () => _256(); + function relative(from, to) { const fromParts = from.split(/[/\\]/).filter(Boolean); const toParts = to.split(/[/\\]/).filter(Boolean); if (fromParts[0] === '.') fromParts.shift(); @@ -1876,24 +1892,68 @@ toParts.unshift('..'); } return toParts.join('/'); } -const BLANK = Object.create(null); +const UnknownKey = Symbol('Unknown Key'); +const EMPTY_PATH = []; +const UNKNOWN_PATH = [UnknownKey]; +const EntitiesKey = Symbol('Entities'); +class PathTracker { + constructor() { + this.entityPaths = Object.create(null, { [EntitiesKey]: { value: new Set() } }); + } + 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(); +const BROKEN_FLOW_NONE = 0; +const BROKEN_FLOW_BREAK_CONTINUE = 1; +const BROKEN_FLOW_ERROR_RETURN_LABEL = 2; +function createInclusionContext() { + return { + brokenFlow: BROKEN_FLOW_NONE, + includedLabels: new Set() + }; +} +function createHasEffectsContext() { + return { + accessed: new PathTracker(), + assigned: new PathTracker(), + brokenFlow: BROKEN_FLOW_NONE, + called: new PathTracker(), + ignore: { + breaks: false, + continues: false, + labels: new Set(), + returnAwaitYield: false + }, + includedLabels: new Set(), + instantiated: new PathTracker(), + replacedVariableInits: new Map() + }; +} + const BlockStatement = 'BlockStatement'; const CallExpression = 'CallExpression'; -const ExportAllDeclaration = 'ExportAllDeclaration'; +const ExportNamespaceSpecifier = 'ExportNamespaceSpecifier'; const ExpressionStatement = 'ExpressionStatement'; const FunctionExpression = 'FunctionExpression'; const Identifier = 'Identifier'; const ImportDefaultSpecifier = 'ImportDefaultSpecifier'; const ImportNamespaceSpecifier = 'ImportNamespaceSpecifier'; const Program = 'Program'; const Property = 'Property'; const ReturnStatement = 'ReturnStatement'; -const VariableDeclaration = 'VariableDeclaration'; function treeshakeNode(node, code, start, end) { code.remove(start, end); if (node.annotations) { for (const annotation of node.annotations) { @@ -1922,11 +1982,11 @@ 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) + if (start === -1 || start >= searchPos) return searchPos; charCodeAfterSlash = code.charCodeAt(++start); ++start; // With our assumption, '/' always starts a comment. Determine comment type: start = @@ -2121,42 +2181,27 @@ } usedNames.add(safeName); return safeName; } -class CallOptions { - static create(callOptions) { - return new this(callOptions); - } - constructor({ withNew = false, args = [], callIdentifier = undefined } = {}) { - this.withNew = withNew; - this.args = args; - this.callIdentifier = callIdentifier; - } - equals(callOptions) { - return callOptions && this.callIdentifier === callOptions.callIdentifier; - } -} +const NO_ARGS = []; -const UNKNOWN_KEY = { UNKNOWN_KEY: true }; -const EMPTY_PATH = []; -const UNKNOWN_PATH = [UNKNOWN_KEY]; function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) { return Object.create(inheritedDescriptions, memberDescriptions); } -const UNKNOWN_VALUE = { UNKNOWN_VALUE: true }; +const UnknownValue = Symbol('Unknown Value'); const UNKNOWN_EXPRESSION = { deoptimizePath: () => { }, - getLiteralValueAtPath: () => UNKNOWN_VALUE, + getLiteralValueAtPath: () => UnknownValue, getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION, hasEffectsWhenAccessedAtPath: path => path.length > 0, hasEffectsWhenAssignedAtPath: path => path.length > 0, hasEffectsWhenCalledAtPath: () => true, include: () => { }, - includeCallArguments(args) { + includeCallArguments(context, args) { for (const arg of args) { - arg.include(false); + arg.include(context, false); } }, included: true, toString: () => '[[UNKNOWN]]' }; @@ -2190,11 +2235,11 @@ constructor() { this.included = false; } deoptimizePath() { } getLiteralValueAtPath() { - return UNKNOWN_VALUE; + return UnknownValue; } getReturnExpressionWhenCalledAtPath(path) { if (path.length === 1) { return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]); } @@ -2204,22 +2249,22 @@ return path.length > 1; } hasEffectsWhenAssignedAtPath(path) { return path.length > 1; } - hasEffectsWhenCalledAtPath(path, callOptions, options) { + hasEffectsWhenCalledAtPath(path, callOptions, context) { if (path.length === 1) { - return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, options); + return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context); } return true; } include() { this.included = true; } - includeCallArguments(args) { + includeCallArguments(context, args) { for (const arg of args) { - arg.include(false); + arg.include(context, false); } } toString() { return '[[UNKNOWN ARRAY]]'; } @@ -2256,11 +2301,11 @@ returnsPrimitive: null } }; const UNKNOWN_LITERAL_BOOLEAN = { deoptimizePath: () => { }, - getLiteralValueAtPath: () => UNKNOWN_VALUE, + getLiteralValueAtPath: () => UnknownValue, getReturnExpressionWhenCalledAtPath: path => { if (path.length === 1) { return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]); } return UNKNOWN_EXPRESSION; @@ -2273,13 +2318,13 @@ return typeof subPath !== 'string' || !literalBooleanMembers[subPath]; } return true; }, include: () => { }, - includeCallArguments(args) { + includeCallArguments(context, args) { for (const arg of args) { - arg.include(false); + arg.include(context, false); } }, included: true, toString: () => '[[UNKNOWN BOOLEAN]]' }; @@ -2299,11 +2344,11 @@ returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN } }; const UNKNOWN_LITERAL_NUMBER = { deoptimizePath: () => { }, - getLiteralValueAtPath: () => UNKNOWN_VALUE, + getLiteralValueAtPath: () => UnknownValue, getReturnExpressionWhenCalledAtPath: path => { if (path.length === 1) { return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]); } return UNKNOWN_EXPRESSION; @@ -2316,13 +2361,13 @@ return typeof subPath !== 'string' || !literalNumberMembers[subPath]; } return true; }, include: () => { }, - includeCallArguments(args) { + includeCallArguments(context, args) { for (const arg of args) { - arg.include(false); + arg.include(context, false); } }, included: true, toString: () => '[[UNKNOWN NUMBER]]' }; @@ -2350,29 +2395,29 @@ returnsPrimitive: UNKNOWN_LITERAL_NUMBER } }; const UNKNOWN_LITERAL_STRING = { deoptimizePath: () => { }, - getLiteralValueAtPath: () => UNKNOWN_VALUE, + getLiteralValueAtPath: () => UnknownValue, getReturnExpressionWhenCalledAtPath: path => { if (path.length === 1) { return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]); } return UNKNOWN_EXPRESSION; }, hasEffectsWhenAccessedAtPath: path => path.length > 1, hasEffectsWhenAssignedAtPath: path => path.length > 0, - hasEffectsWhenCalledAtPath: (path, callOptions, options) => { + hasEffectsWhenCalledAtPath: (path, callOptions, context) => { if (path.length === 1) { - return hasMemberEffectWhenCalled(literalStringMembers, path[0], true, callOptions, options); + return hasMemberEffectWhenCalled(literalStringMembers, path[0], true, callOptions, context); } return true; }, include: () => { }, - includeCallArguments(args) { + includeCallArguments(context, args) { for (const arg of args) { - arg.include(false); + arg.include(context, false); } }, included: true, toString: () => '[[UNKNOWN STRING]]' }; @@ -2388,11 +2433,11 @@ constructor() { this.included = false; } deoptimizePath() { } getLiteralValueAtPath() { - return UNKNOWN_VALUE; + return UnknownValue; } getReturnExpressionWhenCalledAtPath(path) { if (path.length === 1) { return getMemberReturnExpressionWhenCalled(objectMembers, path[0]); } @@ -2402,22 +2447,22 @@ return path.length > 1; } hasEffectsWhenAssignedAtPath(path) { return path.length > 1; } - hasEffectsWhenCalledAtPath(path, callOptions, options) { + hasEffectsWhenCalledAtPath(path, callOptions, context) { if (path.length === 1) { - return hasMemberEffectWhenCalled(objectMembers, path[0], this.included, callOptions, options); + return hasMemberEffectWhenCalled(objectMembers, path[0], this.included, callOptions, context); } return true; } include() { this.included = true; } - includeCallArguments(args) { + includeCallArguments(context, args) { for (const arg of args) { - arg.include(false); + arg.include(context, false); } } toString() { return '[[UNKNOWN OBJECT]]'; } @@ -2512,24 +2557,23 @@ return literalStringMembers; default: return Object.create(null); } } -function hasMemberEffectWhenCalled(members, memberName, parentIncluded, callOptions, options) { - if (typeof memberName !== 'string' || !members[memberName]) +function hasMemberEffectWhenCalled(members, memberName, parentIncluded, callOptions, context) { + if (typeof memberName !== 'string' || + !members[memberName] || + (members[memberName].mutatesSelf && parentIncluded)) return true; - if (members[memberName].mutatesSelf && parentIncluded) - return true; if (!members[memberName].callsArgs) return false; for (const argIndex of members[memberName].callsArgs) { if (callOptions.args[argIndex] && - callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, CallOptions.create({ - args: [], - callIdentifier: {}, + callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, { + args: NO_ARGS, withNew: false - }), options.getHasEffectsWhenCalledOptions())) + }, context)) return true; } return false; } function getMemberReturnExpressionWhenCalled(members, memberName) { @@ -2560,40 +2604,40 @@ deoptimizePath(_path) { } getBaseVariableName() { return this.renderBaseName || this.renderName || this.name; } getLiteralValueAtPath(_path, _recursionTracker, _origin) { - return UNKNOWN_VALUE; + return UnknownValue; } getName() { const name = this.renderName || this.name; - return this.renderBaseName ? `${this.renderBaseName}.${name}` : name; + return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name; } getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) { return UNKNOWN_EXPRESSION; } - hasEffectsWhenAccessedAtPath(path, _options) { + hasEffectsWhenAccessedAtPath(path, _context) { return path.length > 0; } - hasEffectsWhenAssignedAtPath(_path, _options) { + hasEffectsWhenAssignedAtPath(_path, _context) { return true; } - hasEffectsWhenCalledAtPath(_path, _callOptions, _options) { + hasEffectsWhenCalledAtPath(_path, _callOptions, _context) { return true; } /** * 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() { + include(_context) { this.included = true; } - includeCallArguments(args) { + includeCallArguments(context, args) { for (const arg of args) { - arg.include(false); + arg.include(context, false); } } markCalledFromTryStatement() { } setRenderNames(baseName, name) { this.renderBaseName = baseName; @@ -2604,10 +2648,13 @@ } toString() { return this.name; } } +const getPropertyAccess = (name) => { + return /^(?!\d)[\w$]+$/.test(name) ? `.${name}` : `[${JSON.stringify(name)}]`; +}; class ExternalVariable extends Variable { constructor(module, name) { super(name); this.module = module; @@ -2628,23 +2675,22 @@ } } const reservedWords = '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'.split(' '); const builtins = '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'.split(' '); -const blacklisted = Object.create(null); -reservedWords.concat(builtins).forEach(word => (blacklisted[word] = true)); +const blacklisted = new Set(reservedWords.concat(builtins)); const illegalCharacters = /[^$_a-zA-Z0-9]/g; const startsWithDigit = (str) => /\d/.test(str[0]); function isLegal(str) { - if (startsWithDigit(str) || blacklisted[str]) { + if (startsWithDigit(str) || blacklisted.has(str)) { return false; } return !illegalCharacters.test(str); } function makeLegal(str) { str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_'); - if (startsWithDigit(str) || blacklisted[str]) + if (startsWithDigit(str) || blacklisted.has(str)) str = `_${str}`; return str || '_'; } const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/; @@ -2678,11 +2724,11 @@ this.variableName = makeLegal(parts.pop()); this.nameSuggestions = Object.create(null); this.declarations = Object.create(null); this.exportedVariables = new Map(); } - getVariableForExportName(name, _isExportAllSearch) { + getVariableForExportName(name) { if (name === '*') { this.exportsNamespace = true; } else if (name !== 'default') { this.exportsNames = true; @@ -2793,86 +2839,106 @@ } this.additionalInitializers = null; } } deoptimizePath(path) { - if (path.length > MAX_PATH_DEPTH) + if (path.length > MAX_PATH_DEPTH || this.isReassigned) return; - if (!(this.isReassigned || this.deoptimizationTracker.track(this, path))) { - if (path.length === 0) { - if (!this.isReassigned) { - this.isReassigned = true; - for (const expression of this.expressionsToBeDeoptimized) { - expression.deoptimizeCache(); - } - if (this.init) { - this.init.deoptimizePath(UNKNOWN_PATH); - } + const trackedEntities = this.deoptimizationTracker.getEntities(path); + if (trackedEntities.has(this)) + return; + trackedEntities.add(this); + if (path.length === 0) { + if (!this.isReassigned) { + this.isReassigned = true; + const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized; + this.expressionsToBeDeoptimized = []; + for (const expression of expressionsToBeDeoptimized) { + expression.deoptimizeCache(); } + if (this.init) { + this.init.deoptimizePath(UNKNOWN_PATH); + } } - else if (this.init) { - this.init.deoptimizePath(path); - } } + else if (this.init) { + this.init.deoptimizePath(path); + } } getLiteralValueAtPath(path, recursionTracker, origin) { - if (this.isReassigned || - !this.init || - path.length > MAX_PATH_DEPTH || - recursionTracker.isTracked(this.init, path)) { - return UNKNOWN_VALUE; + if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) { + return UnknownValue; } + const trackedEntities = recursionTracker.getEntities(path); + if (trackedEntities.has(this.init)) { + return UnknownValue; + } this.expressionsToBeDeoptimized.push(origin); - return this.init.getLiteralValueAtPath(path, recursionTracker.track(this.init, path), origin); + trackedEntities.add(this.init); + const value = this.init.getLiteralValueAtPath(path, recursionTracker, origin); + trackedEntities.delete(this.init); + return value; } getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) { - if (this.isReassigned || - !this.init || - path.length > MAX_PATH_DEPTH || - recursionTracker.isTracked(this.init, path)) { + if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) { return UNKNOWN_EXPRESSION; } + const trackedEntities = recursionTracker.getEntities(path); + if (trackedEntities.has(this.init)) { + return UNKNOWN_EXPRESSION; + } this.expressionsToBeDeoptimized.push(origin); - return this.init.getReturnExpressionWhenCalledAtPath(path, recursionTracker.track(this.init, path), origin); + trackedEntities.add(this.init); + const value = this.init.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin); + trackedEntities.delete(this.init); + return value; } - hasEffectsWhenAccessedAtPath(path, options) { + hasEffectsWhenAccessedAtPath(path, context) { if (path.length === 0) return false; - return (this.isReassigned || - path.length > MAX_PATH_DEPTH || - (this.init && - !options.hasNodeBeenAccessedAtPath(path, this.init) && - this.init.hasEffectsWhenAccessedAtPath(path, options.addAccessedNodeAtPath(path, this.init)))); + if (this.isReassigned || path.length > MAX_PATH_DEPTH) + return true; + const trackedExpressions = context.accessed.getEntities(path); + if (trackedExpressions.has(this)) + return false; + trackedExpressions.add(this); + return (this.init && this.init.hasEffectsWhenAccessedAtPath(path, context)); } - hasEffectsWhenAssignedAtPath(path, options) { + hasEffectsWhenAssignedAtPath(path, context) { if (this.included || path.length > MAX_PATH_DEPTH) return true; if (path.length === 0) return false; - return (this.isReassigned || - (this.init && - !options.hasNodeBeenAssignedAtPath(path, this.init) && - this.init.hasEffectsWhenAssignedAtPath(path, options.addAssignedNodeAtPath(path, this.init)))); + if (this.isReassigned) + return true; + const trackedExpressions = context.assigned.getEntities(path); + if (trackedExpressions.has(this)) + return false; + trackedExpressions.add(this); + return (this.init && this.init.hasEffectsWhenAssignedAtPath(path, context)); } - hasEffectsWhenCalledAtPath(path, callOptions, options) { - if (path.length > MAX_PATH_DEPTH) + hasEffectsWhenCalledAtPath(path, callOptions, context) { + if (path.length > MAX_PATH_DEPTH || this.isReassigned) return true; - return (this.isReassigned || - (this.init && - !options.hasNodeBeenCalledAtPathWithOptions(path, this.init, callOptions) && - this.init.hasEffectsWhenCalledAtPath(path, callOptions, options.addCalledNodeAtPathWithOptions(path, this.init, callOptions)))); + const trackedExpressions = (callOptions.withNew + ? context.instantiated + : context.called).getEntities(path); + if (trackedExpressions.has(this)) + return false; + trackedExpressions.add(this); + return (this.init && this.init.hasEffectsWhenCalledAtPath(path, callOptions, context)); } - include() { + include(context) { if (!this.included) { this.included = true; if (!this.module.isExecuted) { markModuleAndImpureDependenciesAsExecuted(this.module); } 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(false); + declaration.include(context, 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; @@ -2881,18 +2947,18 @@ node = node.parent; } } } } - includeCallArguments(args) { + includeCallArguments(context, args) { if (this.isReassigned) { for (const arg of args) { - arg.include(false); + arg.include(context, false); } } else if (this.init) { - this.init.includeCallArguments(args); + this.init.includeCallArguments(context, args); } } markCalledFromTryStatement() { this.calledFromTryStatement = true; } @@ -2928,15 +2994,18 @@ super(); this.accessedOutsideVariables = new Map(); this.parent = parent; parent.children.push(this); } - addAccessedGlobalsByFormat(globalsByFormat) { - let accessedGlobalVariablesByFormat = this.accessedGlobalVariablesByFormat; - if (!accessedGlobalVariablesByFormat) { - accessedGlobalVariablesByFormat = this.accessedGlobalVariablesByFormat = new Map(); + addAccessedDynamicImport(importExpression) { + (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression); + if (this.parent instanceof ChildScope) { + this.parent.addAccessedDynamicImport(importExpression); } + } + addAccessedGlobalsByFormat(globalsByFormat) { + const accessedGlobalVariablesByFormat = this.accessedGlobalVariablesByFormat || (this.accessedGlobalVariablesByFormat = new Map()); for (const format of Object.keys(globalsByFormat)) { let accessedGlobalVariables = accessedGlobalVariablesByFormat.get(format); if (!accessedGlobalVariables) { accessedGlobalVariables = new Set(); accessedGlobalVariablesByFormat.set(format, accessedGlobalVariables); @@ -2949,22 +3018,16 @@ this.parent.addAccessedGlobalsByFormat(globalsByFormat); } } addNamespaceMemberAccess(name, variable) { this.accessedOutsideVariables.set(name, variable); - if (this.parent instanceof ChildScope) { - this.parent.addNamespaceMemberAccess(name, variable); - } + this.parent.addNamespaceMemberAccess(name, variable); } addReturnExpression(expression) { this.parent instanceof ChildScope && this.parent.addReturnExpression(expression); } - contains(name) { - return this.variables.has(name) || this.parent.contains(name); - } - deconflict(format) { - const usedNames = new Set(); + addUsedOutsideNames(usedNames, format) { for (const variable of this.accessedOutsideVariables.values()) { if (variable.included) { usedNames.add(variable.getBaseVariableName()); if (variable.exportName && format === 'system') { usedNames.add('exports'); @@ -2975,21 +3038,35 @@ if (accessedGlobalVariables) { for (const name of accessedGlobalVariables) { usedNames.add(name); } } + } + contains(name) { + return this.variables.has(name) || this.parent.contains(name); + } + deconflict(format) { + const usedNames = new Set(); + this.addUsedOutsideNames(usedNames, format); + 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.setSafeName(getSafeName(name, usedNames)); } } for (const scope of this.children) { scope.deconflict(format); } } findLexicalBoundary() { - return this.parent instanceof ChildScope ? this.parent.findLexicalBoundary() : this; + return this.parent.findLexicalBoundary(); } findVariable(name) { const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name); if (knownVariable) { return knownVariable; @@ -3041,4921 +3118,20 @@ throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument'); } return getLocator$1(source, options)(search, options && options.startIndex); } -/** - * Copyright (c) 2014-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ -// Used for setting prototype methods that IE8 chokes on. -var DELETE = 'delete'; -// Constants describing the size of trie nodes. -var SHIFT = 5; // Resulted in best performance after ______? -var SIZE = 1 << SHIFT; -var MASK = SIZE - 1; -// A consistent shared value representing "not set" which equals nothing other -// than itself, and nothing that could be provided externally. -var NOT_SET = {}; -// Boolean references, Rough equivalent of `bool &`. -function MakeRef() { - return { value: false }; -} -function SetRef(ref) { - if (ref) { - ref.value = true; - } -} -// A function which returns a value representing an "owner" for transient writes -// to tries. The return value will only ever equal itself, and will not equal -// the return of any subsequent call of this function. -function OwnerID() { } -function ensureSize(iter) { - if (iter.size === undefined) { - iter.size = iter.__iterate(returnTrue); - } - return iter.size; -} -function wrapIndex(iter, index) { - // This implements "is array index" which the ECMAString spec defines as: - // - // A String property name P is an array index if and only if - // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal - // to 2^32−1. - // - // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects - if (typeof index !== 'number') { - var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32 - if ('' + uint32Index !== index || uint32Index === 4294967295) { - return NaN; - } - index = uint32Index; - } - return index < 0 ? ensureSize(iter) + index : index; -} -function returnTrue() { - return true; -} -function wholeSlice(begin, end, size) { - return (((begin === 0 && !isNeg(begin)) || - (size !== undefined && begin <= -size)) && - (end === undefined || (size !== undefined && end >= size))); -} -function resolveBegin(begin, size) { - return resolveIndex(begin, size, 0); -} -function resolveEnd(end, size) { - return resolveIndex(end, size, size); -} -function resolveIndex(index, size, defaultIndex) { - // Sanitize indices using this shorthand for ToInt32(argument) - // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 - return index === undefined - ? defaultIndex - : isNeg(index) - ? size === Infinity - ? size - : Math.max(0, size + index) | 0 - : size === undefined || size === index - ? index - : Math.min(size, index) | 0; -} -function isNeg(value) { - // Account for -0 which is negative, but not less than 0. - return value < 0 || (value === 0 && 1 / value === -Infinity); -} -// Note: value is unchanged to not break immutable-devtools. -var IS_COLLECTION_SYMBOL = '@@__IMMUTABLE_ITERABLE__@@'; -function isCollection(maybeCollection) { - return Boolean(maybeCollection && maybeCollection[IS_COLLECTION_SYMBOL]); -} -var IS_KEYED_SYMBOL = '@@__IMMUTABLE_KEYED__@@'; -function isKeyed(maybeKeyed) { - return Boolean(maybeKeyed && maybeKeyed[IS_KEYED_SYMBOL]); -} -var IS_INDEXED_SYMBOL = '@@__IMMUTABLE_INDEXED__@@'; -function isIndexed(maybeIndexed) { - return Boolean(maybeIndexed && maybeIndexed[IS_INDEXED_SYMBOL]); -} -function isAssociative(maybeAssociative) { - return isKeyed(maybeAssociative) || isIndexed(maybeAssociative); -} -var Collection = function Collection(value) { - return isCollection(value) ? value : Seq(value); -}; -var KeyedCollection = /*@__PURE__*/ (function (Collection) { - function KeyedCollection(value) { - return isKeyed(value) ? value : KeyedSeq(value); - } - if (Collection) - KeyedCollection.__proto__ = Collection; - KeyedCollection.prototype = Object.create(Collection && Collection.prototype); - KeyedCollection.prototype.constructor = KeyedCollection; - return KeyedCollection; -}(Collection)); -var IndexedCollection = /*@__PURE__*/ (function (Collection) { - function IndexedCollection(value) { - return isIndexed(value) ? value : IndexedSeq(value); - } - if (Collection) - IndexedCollection.__proto__ = Collection; - IndexedCollection.prototype = Object.create(Collection && Collection.prototype); - IndexedCollection.prototype.constructor = IndexedCollection; - return IndexedCollection; -}(Collection)); -var SetCollection = /*@__PURE__*/ (function (Collection) { - function SetCollection(value) { - return isCollection(value) && !isAssociative(value) ? value : SetSeq(value); - } - if (Collection) - SetCollection.__proto__ = Collection; - SetCollection.prototype = Object.create(Collection && Collection.prototype); - SetCollection.prototype.constructor = SetCollection; - return SetCollection; -}(Collection)); -Collection.Keyed = KeyedCollection; -Collection.Indexed = IndexedCollection; -Collection.Set = SetCollection; -var IS_SEQ_SYMBOL = '@@__IMMUTABLE_SEQ__@@'; -function isSeq(maybeSeq) { - return Boolean(maybeSeq && maybeSeq[IS_SEQ_SYMBOL]); -} -var IS_RECORD_SYMBOL = '@@__IMMUTABLE_RECORD__@@'; -function isRecord(maybeRecord) { - return Boolean(maybeRecord && maybeRecord[IS_RECORD_SYMBOL]); -} -function isImmutable(maybeImmutable) { - return isCollection(maybeImmutable) || isRecord(maybeImmutable); -} -var IS_ORDERED_SYMBOL = '@@__IMMUTABLE_ORDERED__@@'; -function isOrdered(maybeOrdered) { - return Boolean(maybeOrdered && maybeOrdered[IS_ORDERED_SYMBOL]); -} -var ITERATE_KEYS = 0; -var ITERATE_VALUES = 1; -var ITERATE_ENTRIES = 2; -var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; -var FAUX_ITERATOR_SYMBOL = '@@iterator'; -var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL; -var Iterator = function Iterator(next) { - this.next = next; -}; -Iterator.prototype.toString = function toString() { - return '[Iterator]'; -}; -Iterator.KEYS = ITERATE_KEYS; -Iterator.VALUES = ITERATE_VALUES; -Iterator.ENTRIES = ITERATE_ENTRIES; -Iterator.prototype.inspect = Iterator.prototype.toSource = function () { - return this.toString(); -}; -Iterator.prototype[ITERATOR_SYMBOL] = function () { - return this; -}; -function iteratorValue(type, k, v, iteratorResult) { - var value = type === 0 ? k : type === 1 ? v : [k, v]; - iteratorResult - ? (iteratorResult.value = value) - : (iteratorResult = { - value: value, - done: false, - }); - return iteratorResult; -} -function iteratorDone() { - return { value: undefined, done: true }; -} -function hasIterator(maybeIterable) { - return !!getIteratorFn(maybeIterable); -} -function isIterator(maybeIterator) { - return maybeIterator && typeof maybeIterator.next === 'function'; -} -function getIterator(iterable) { - var iteratorFn = getIteratorFn(iterable); - return iteratorFn && iteratorFn.call(iterable); -} -function getIteratorFn(iterable) { - var iteratorFn = iterable && - ((REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) || - iterable[FAUX_ITERATOR_SYMBOL]); - if (typeof iteratorFn === 'function') { - return iteratorFn; - } -} -var hasOwnProperty = Object.prototype.hasOwnProperty; -function isArrayLike(value) { - if (Array.isArray(value) || typeof value === 'string') { - return true; - } - return (value && - typeof value === 'object' && - Number.isInteger(value.length) && - value.length >= 0 && - (value.length === 0 - ? // Only {length: 0} is considered Array-like. - Object.keys(value).length === 1 - : // An object is only Array-like if it has a property where the last value - // in the array-like may be found (which could be undefined). - value.hasOwnProperty(value.length - 1))); -} -var Seq = /*@__PURE__*/ (function (Collection$$1) { - function Seq(value) { - return value === null || value === undefined - ? emptySequence() - : isImmutable(value) - ? value.toSeq() - : seqFromValue(value); - } - if (Collection$$1) - Seq.__proto__ = Collection$$1; - Seq.prototype = Object.create(Collection$$1 && Collection$$1.prototype); - Seq.prototype.constructor = Seq; - Seq.prototype.toSeq = function toSeq() { - return this; - }; - Seq.prototype.toString = function toString() { - return this.__toString('Seq {', '}'); - }; - Seq.prototype.cacheResult = function cacheResult() { - if (!this._cache && this.__iterateUncached) { - this._cache = this.entrySeq().toArray(); - this.size = this._cache.length; - } - return this; - }; - // abstract __iterateUncached(fn, reverse) - Seq.prototype.__iterate = function __iterate(fn, reverse) { - var cache = this._cache; - if (cache) { - var size = cache.length; - var i = 0; - while (i !== size) { - var entry = cache[reverse ? size - ++i : i++]; - if (fn(entry[1], entry[0], this) === false) { - break; - } - } - return i; - } - return this.__iterateUncached(fn, reverse); - }; - // abstract __iteratorUncached(type, reverse) - Seq.prototype.__iterator = function __iterator(type, reverse) { - var cache = this._cache; - if (cache) { - var size = cache.length; - var i = 0; - return new Iterator(function () { - if (i === size) { - return iteratorDone(); - } - var entry = cache[reverse ? size - ++i : i++]; - return iteratorValue(type, entry[0], entry[1]); - }); - } - return this.__iteratorUncached(type, reverse); - }; - return Seq; -}(Collection)); -var KeyedSeq = /*@__PURE__*/ (function (Seq) { - function KeyedSeq(value) { - return value === null || value === undefined - ? emptySequence().toKeyedSeq() - : isCollection(value) - ? isKeyed(value) - ? value.toSeq() - : value.fromEntrySeq() - : isRecord(value) - ? value.toSeq() - : keyedSeqFromValue(value); - } - if (Seq) - KeyedSeq.__proto__ = Seq; - KeyedSeq.prototype = Object.create(Seq && Seq.prototype); - KeyedSeq.prototype.constructor = KeyedSeq; - KeyedSeq.prototype.toKeyedSeq = function toKeyedSeq() { - return this; - }; - return KeyedSeq; -}(Seq)); -var IndexedSeq = /*@__PURE__*/ (function (Seq) { - function IndexedSeq(value) { - return value === null || value === undefined - ? emptySequence() - : isCollection(value) - ? isKeyed(value) - ? value.entrySeq() - : value.toIndexedSeq() - : isRecord(value) - ? value.toSeq().entrySeq() - : indexedSeqFromValue(value); - } - if (Seq) - IndexedSeq.__proto__ = Seq; - IndexedSeq.prototype = Object.create(Seq && Seq.prototype); - IndexedSeq.prototype.constructor = IndexedSeq; - IndexedSeq.of = function of( /*...values*/) { - return IndexedSeq(arguments); - }; - IndexedSeq.prototype.toIndexedSeq = function toIndexedSeq() { - return this; - }; - IndexedSeq.prototype.toString = function toString() { - return this.__toString('Seq [', ']'); - }; - return IndexedSeq; -}(Seq)); -var SetSeq = /*@__PURE__*/ (function (Seq) { - function SetSeq(value) { - return (isCollection(value) && !isAssociative(value) - ? value - : IndexedSeq(value)).toSetSeq(); - } - if (Seq) - SetSeq.__proto__ = Seq; - SetSeq.prototype = Object.create(Seq && Seq.prototype); - SetSeq.prototype.constructor = SetSeq; - SetSeq.of = function of( /*...values*/) { - return SetSeq(arguments); - }; - SetSeq.prototype.toSetSeq = function toSetSeq() { - return this; - }; - return SetSeq; -}(Seq)); -Seq.isSeq = isSeq; -Seq.Keyed = KeyedSeq; -Seq.Set = SetSeq; -Seq.Indexed = IndexedSeq; -Seq.prototype[IS_SEQ_SYMBOL] = true; -// #pragma Root Sequences -var ArraySeq = /*@__PURE__*/ (function (IndexedSeq) { - function ArraySeq(array) { - this._array = array; - this.size = array.length; - } - if (IndexedSeq) - ArraySeq.__proto__ = IndexedSeq; - ArraySeq.prototype = Object.create(IndexedSeq && IndexedSeq.prototype); - ArraySeq.prototype.constructor = ArraySeq; - ArraySeq.prototype.get = function get(index, notSetValue) { - return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue; - }; - ArraySeq.prototype.__iterate = function __iterate(fn, reverse) { - var array = this._array; - var size = array.length; - var i = 0; - while (i !== size) { - var ii = reverse ? size - ++i : i++; - if (fn(array[ii], ii, this) === false) { - break; - } - } - return i; - }; - ArraySeq.prototype.__iterator = function __iterator(type, reverse) { - var array = this._array; - var size = array.length; - var i = 0; - return new Iterator(function () { - if (i === size) { - return iteratorDone(); - } - var ii = reverse ? size - ++i : i++; - return iteratorValue(type, ii, array[ii]); - }); - }; - return ArraySeq; -}(IndexedSeq)); -var ObjectSeq = /*@__PURE__*/ (function (KeyedSeq) { - function ObjectSeq(object) { - var keys = Object.keys(object); - this._object = object; - this._keys = keys; - this.size = keys.length; - } - if (KeyedSeq) - ObjectSeq.__proto__ = KeyedSeq; - ObjectSeq.prototype = Object.create(KeyedSeq && KeyedSeq.prototype); - ObjectSeq.prototype.constructor = ObjectSeq; - ObjectSeq.prototype.get = function get(key, notSetValue) { - if (notSetValue !== undefined && !this.has(key)) { - return notSetValue; - } - return this._object[key]; - }; - ObjectSeq.prototype.has = function has(key) { - return hasOwnProperty.call(this._object, key); - }; - ObjectSeq.prototype.__iterate = function __iterate(fn, reverse) { - var object = this._object; - var keys = this._keys; - var size = keys.length; - var i = 0; - while (i !== size) { - var key = keys[reverse ? size - ++i : i++]; - if (fn(object[key], key, this) === false) { - break; - } - } - return i; - }; - ObjectSeq.prototype.__iterator = function __iterator(type, reverse) { - var object = this._object; - var keys = this._keys; - var size = keys.length; - var i = 0; - return new Iterator(function () { - if (i === size) { - return iteratorDone(); - } - var key = keys[reverse ? size - ++i : i++]; - return iteratorValue(type, key, object[key]); - }); - }; - return ObjectSeq; -}(KeyedSeq)); -ObjectSeq.prototype[IS_ORDERED_SYMBOL] = true; -var CollectionSeq = /*@__PURE__*/ (function (IndexedSeq) { - function CollectionSeq(collection) { - this._collection = collection; - this.size = collection.length || collection.size; - } - if (IndexedSeq) - CollectionSeq.__proto__ = IndexedSeq; - CollectionSeq.prototype = Object.create(IndexedSeq && IndexedSeq.prototype); - CollectionSeq.prototype.constructor = CollectionSeq; - CollectionSeq.prototype.__iterateUncached = function __iterateUncached(fn, reverse) { - if (reverse) { - return this.cacheResult().__iterate(fn, reverse); - } - var collection = this._collection; - var iterator = getIterator(collection); - var iterations = 0; - if (isIterator(iterator)) { - var step; - while (!(step = iterator.next()).done) { - if (fn(step.value, iterations++, this) === false) { - break; - } - } - } - return iterations; - }; - CollectionSeq.prototype.__iteratorUncached = function __iteratorUncached(type, reverse) { - if (reverse) { - return this.cacheResult().__iterator(type, reverse); - } - var collection = this._collection; - var iterator = getIterator(collection); - if (!isIterator(iterator)) { - return new Iterator(iteratorDone); - } - var iterations = 0; - return new Iterator(function () { - var step = iterator.next(); - return step.done ? step : iteratorValue(type, iterations++, step.value); - }); - }; - return CollectionSeq; -}(IndexedSeq)); -// # pragma Helper functions -var EMPTY_SEQ; -function emptySequence() { - return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([])); -} -function keyedSeqFromValue(value) { - var seq = Array.isArray(value) - ? new ArraySeq(value) - : hasIterator(value) - ? new CollectionSeq(value) - : undefined; - if (seq) { - return seq.fromEntrySeq(); - } - if (typeof value === 'object') { - return new ObjectSeq(value); - } - throw new TypeError('Expected Array or collection object of [k, v] entries, or keyed object: ' + - value); -} -function indexedSeqFromValue(value) { - var seq = maybeIndexedSeqFromValue(value); - if (seq) { - return seq; - } - throw new TypeError('Expected Array or collection object of values: ' + value); -} -function seqFromValue(value) { - var seq = maybeIndexedSeqFromValue(value); - if (seq) { - return seq; - } - if (typeof value === 'object') { - return new ObjectSeq(value); - } - throw new TypeError('Expected Array or collection object of values, or keyed object: ' + value); -} -function maybeIndexedSeqFromValue(value) { - return isArrayLike(value) - ? new ArraySeq(value) - : hasIterator(value) - ? new CollectionSeq(value) - : undefined; -} -var IS_MAP_SYMBOL = '@@__IMMUTABLE_MAP__@@'; -function isMap(maybeMap) { - return Boolean(maybeMap && maybeMap[IS_MAP_SYMBOL]); -} -function isOrderedMap(maybeOrderedMap) { - return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap); -} -function isValueObject(maybeValue) { - return Boolean(maybeValue && - typeof maybeValue.equals === 'function' && - typeof maybeValue.hashCode === 'function'); -} -/** - * An extension of the "same-value" algorithm as [described for use by ES6 Map - * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality) - * - * NaN is considered the same as NaN, however -0 and 0 are considered the same - * value, which is different from the algorithm described by - * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). - * - * This is extended further to allow Objects to describe the values they - * represent, by way of `valueOf` or `equals` (and `hashCode`). - * - * Note: because of this extension, the key equality of Immutable.Map and the - * value equality of Immutable.Set will differ from ES6 Map and Set. - * - * ### Defining custom values - * - * The easiest way to describe the value an object represents is by implementing - * `valueOf`. For example, `Date` represents a value by returning a unix - * timestamp for `valueOf`: - * - * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ... - * var date2 = new Date(1234567890000); - * date1.valueOf(); // 1234567890000 - * assert( date1 !== date2 ); - * assert( Immutable.is( date1, date2 ) ); - * - * Note: overriding `valueOf` may have other implications if you use this object - * where JavaScript expects a primitive, such as implicit string coercion. - * - * For more complex types, especially collections, implementing `valueOf` may - * not be performant. An alternative is to implement `equals` and `hashCode`. - * - * `equals` takes another object, presumably of similar type, and returns true - * if it is equal. Equality is symmetrical, so the same result should be - * returned if this and the argument are flipped. - * - * assert( a.equals(b) === b.equals(a) ); - * - * `hashCode` returns a 32bit integer number representing the object which will - * be used to determine how to store the value object in a Map or Set. You must - * provide both or neither methods, one must not exist without the other. - * - * Also, an important relationship between these methods must be upheld: if two - * values are equal, they *must* return the same hashCode. If the values are not - * equal, they might have the same hashCode; this is called a hash collision, - * and while undesirable for performance reasons, it is acceptable. - * - * if (a.equals(b)) { - * assert( a.hashCode() === b.hashCode() ); - * } - * - * All Immutable collections are Value Objects: they implement `equals()` - * and `hashCode()`. - */ -function is(valueA, valueB) { - if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { - return true; - } - if (!valueA || !valueB) { - return false; - } - if (typeof valueA.valueOf === 'function' && - typeof valueB.valueOf === 'function') { - valueA = valueA.valueOf(); - valueB = valueB.valueOf(); - if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { - return true; - } - if (!valueA || !valueB) { - return false; - } - } - return !!(isValueObject(valueA) && - isValueObject(valueB) && - valueA.equals(valueB)); -} -var imul = typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 - ? Math.imul - : function imul(a, b) { - a |= 0; // int - b |= 0; // int - var c = a & 0xffff; - var d = b & 0xffff; - // Shift by 0 fixes the sign on the high part. - return (c * d + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0)) | 0; // int - }; -// v8 has an optimization for storing 31-bit signed numbers. -// Values which have either 00 or 11 as the high order bits qualify. -// This function drops the highest order bit in a signed number, maintaining -// the sign bit. -function smi(i32) { - return ((i32 >>> 1) & 0x40000000) | (i32 & 0xbfffffff); -} -var defaultValueOf = Object.prototype.valueOf; -function hash(o) { - switch (typeof o) { - case 'boolean': - // The hash values for built-in constants are a 1 value for each 5-byte - // shift region expect for the first, which encodes the value. This - // reduces the odds of a hash collision for these common values. - return o ? 0x42108421 : 0x42108420; - case 'number': - return hashNumber(o); - case 'string': - return o.length > STRING_HASH_CACHE_MIN_STRLEN - ? cachedHashString(o) - : hashString(o); - case 'object': - case 'function': - if (o === null) { - return 0x42108422; - } - if (typeof o.hashCode === 'function') { - // Drop any high bits from accidentally long hash codes. - return smi(o.hashCode(o)); - } - if (o.valueOf !== defaultValueOf && typeof o.valueOf === 'function') { - o = o.valueOf(o); - } - return hashJSObj(o); - case 'undefined': - return 0x42108423; - default: - if (typeof o.toString === 'function') { - return hashString(o.toString()); - } - throw new Error('Value type ' + typeof o + ' cannot be hashed.'); - } -} -// Compress arbitrarily large numbers into smi hashes. -function hashNumber(n) { - if (n !== n || n === Infinity) { - return 0; - } - var hash = n | 0; - if (hash !== n) { - hash ^= n * 0xffffffff; - } - while (n > 0xffffffff) { - n /= 0xffffffff; - hash ^= n; - } - return smi(hash); -} -function cachedHashString(string) { - var hashed = stringHashCache[string]; - if (hashed === undefined) { - hashed = hashString(string); - if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) { - STRING_HASH_CACHE_SIZE = 0; - stringHashCache = {}; - } - STRING_HASH_CACHE_SIZE++; - stringHashCache[string] = hashed; - } - return hashed; -} -// http://jsperf.com/hashing-strings -function hashString(string) { - // This is the hash from JVM - // The hash code for a string is computed as - // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], - // where s[i] is the ith character of the string and n is the length of - // the string. We "mod" the result to make it between 0 (inclusive) and 2^31 - // (exclusive) by dropping high bits. - var hashed = 0; - for (var ii = 0; ii < string.length; ii++) { - hashed = (31 * hashed + string.charCodeAt(ii)) | 0; - } - return smi(hashed); -} -function hashJSObj(obj) { - var hashed; - if (usingWeakMap) { - hashed = weakMap.get(obj); - if (hashed !== undefined) { - return hashed; - } - } - hashed = obj[UID_HASH_KEY]; - if (hashed !== undefined) { - return hashed; - } - if (!canDefineProperty) { - hashed = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY]; - if (hashed !== undefined) { - return hashed; - } - hashed = getIENodeHash(obj); - if (hashed !== undefined) { - return hashed; - } - } - hashed = ++objHashUID; - if (objHashUID & 0x40000000) { - objHashUID = 0; - } - if (usingWeakMap) { - weakMap.set(obj, hashed); - } - else if (isExtensible !== undefined && isExtensible(obj) === false) { - throw new Error('Non-extensible objects are not allowed as keys.'); - } - else if (canDefineProperty) { - Object.defineProperty(obj, UID_HASH_KEY, { - enumerable: false, - configurable: false, - writable: false, - value: hashed, - }); - } - else if (obj.propertyIsEnumerable !== undefined && - obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) { - // Since we can't define a non-enumerable property on the object - // we'll hijack one of the less-used non-enumerable properties to - // save our hash on it. Since this is a function it will not show up in - // `JSON.stringify` which is what we want. - obj.propertyIsEnumerable = function () { - return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments); - }; - obj.propertyIsEnumerable[UID_HASH_KEY] = hashed; - } - else if (obj.nodeType !== undefined) { - // At this point we couldn't get the IE `uniqueID` to use as a hash - // and we couldn't use a non-enumerable property to exploit the - // dontEnum bug so we simply add the `UID_HASH_KEY` on the node - // itself. - obj[UID_HASH_KEY] = hashed; - } - else { - throw new Error('Unable to set a non-enumerable property on object.'); - } - return hashed; -} -// Get references to ES5 object methods. -var isExtensible = Object.isExtensible; -// True if Object.defineProperty works as expected. IE8 fails this test. -var canDefineProperty = (function () { - try { - Object.defineProperty({}, '@', {}); - return true; - } - catch (e) { - return false; - } -})(); -// IE has a `uniqueID` property on DOM nodes. We can construct the hash from it -// and avoid memory leaks from the IE cloneNode bug. -function getIENodeHash(node) { - if (node && node.nodeType > 0) { - switch (node.nodeType) { - case 1: // Element - return node.uniqueID; - case 9: // Document - return node.documentElement && node.documentElement.uniqueID; - } - } -} -// If possible, use a WeakMap. -var usingWeakMap = typeof WeakMap === 'function'; -var weakMap; -if (usingWeakMap) { - weakMap = new WeakMap(); -} -var objHashUID = 0; -var UID_HASH_KEY = '__immutablehash__'; -if (typeof Symbol === 'function') { - UID_HASH_KEY = Symbol(UID_HASH_KEY); -} -var STRING_HASH_CACHE_MIN_STRLEN = 16; -var STRING_HASH_CACHE_MAX_SIZE = 255; -var STRING_HASH_CACHE_SIZE = 0; -var stringHashCache = {}; -var ToKeyedSequence = /*@__PURE__*/ (function (KeyedSeq$$1) { - function ToKeyedSequence(indexed, useKeys) { - this._iter = indexed; - this._useKeys = useKeys; - this.size = indexed.size; - } - if (KeyedSeq$$1) - ToKeyedSequence.__proto__ = KeyedSeq$$1; - ToKeyedSequence.prototype = Object.create(KeyedSeq$$1 && KeyedSeq$$1.prototype); - ToKeyedSequence.prototype.constructor = ToKeyedSequence; - ToKeyedSequence.prototype.get = function get(key, notSetValue) { - return this._iter.get(key, notSetValue); - }; - ToKeyedSequence.prototype.has = function has(key) { - return this._iter.has(key); - }; - ToKeyedSequence.prototype.valueSeq = function valueSeq() { - return this._iter.valueSeq(); - }; - ToKeyedSequence.prototype.reverse = function reverse() { - var this$1 = this; - var reversedSequence = reverseFactory(this, true); - if (!this._useKeys) { - reversedSequence.valueSeq = function () { return this$1._iter.toSeq().reverse(); }; - } - return reversedSequence; - }; - ToKeyedSequence.prototype.map = function map(mapper, context) { - var this$1 = this; - var mappedSequence = mapFactory(this, mapper, context); - if (!this._useKeys) { - mappedSequence.valueSeq = function () { return this$1._iter.toSeq().map(mapper, context); }; - } - return mappedSequence; - }; - ToKeyedSequence.prototype.__iterate = function __iterate(fn, reverse) { - var this$1 = this; - return this._iter.__iterate(function (v, k) { return fn(v, k, this$1); }, reverse); - }; - ToKeyedSequence.prototype.__iterator = function __iterator(type, reverse) { - return this._iter.__iterator(type, reverse); - }; - return ToKeyedSequence; -}(KeyedSeq)); -ToKeyedSequence.prototype[IS_ORDERED_SYMBOL] = true; -var ToIndexedSequence = /*@__PURE__*/ (function (IndexedSeq$$1) { - function ToIndexedSequence(iter) { - this._iter = iter; - this.size = iter.size; - } - if (IndexedSeq$$1) - ToIndexedSequence.__proto__ = IndexedSeq$$1; - ToIndexedSequence.prototype = Object.create(IndexedSeq$$1 && IndexedSeq$$1.prototype); - ToIndexedSequence.prototype.constructor = ToIndexedSequence; - ToIndexedSequence.prototype.includes = function includes(value) { - return this._iter.includes(value); - }; - ToIndexedSequence.prototype.__iterate = function __iterate(fn, reverse) { - var this$1 = this; - var i = 0; - reverse && ensureSize(this); - return this._iter.__iterate(function (v) { return fn(v, reverse ? this$1.size - ++i : i++, this$1); }, reverse); - }; - ToIndexedSequence.prototype.__iterator = function __iterator(type, reverse) { - var this$1 = this; - var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); - var i = 0; - reverse && ensureSize(this); - return new Iterator(function () { - var step = iterator.next(); - return step.done - ? step - : iteratorValue(type, reverse ? this$1.size - ++i : i++, step.value, step); - }); - }; - return ToIndexedSequence; -}(IndexedSeq)); -var ToSetSequence = /*@__PURE__*/ (function (SetSeq$$1) { - function ToSetSequence(iter) { - this._iter = iter; - this.size = iter.size; - } - if (SetSeq$$1) - ToSetSequence.__proto__ = SetSeq$$1; - ToSetSequence.prototype = Object.create(SetSeq$$1 && SetSeq$$1.prototype); - ToSetSequence.prototype.constructor = ToSetSequence; - ToSetSequence.prototype.has = function has(key) { - return this._iter.includes(key); - }; - ToSetSequence.prototype.__iterate = function __iterate(fn, reverse) { - var this$1 = this; - return this._iter.__iterate(function (v) { return fn(v, v, this$1); }, reverse); - }; - ToSetSequence.prototype.__iterator = function __iterator(type, reverse) { - var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); - return new Iterator(function () { - var step = iterator.next(); - return step.done - ? step - : iteratorValue(type, step.value, step.value, step); - }); - }; - return ToSetSequence; -}(SetSeq)); -var FromEntriesSequence = /*@__PURE__*/ (function (KeyedSeq$$1) { - function FromEntriesSequence(entries) { - this._iter = entries; - this.size = entries.size; - } - if (KeyedSeq$$1) - FromEntriesSequence.__proto__ = KeyedSeq$$1; - FromEntriesSequence.prototype = Object.create(KeyedSeq$$1 && KeyedSeq$$1.prototype); - FromEntriesSequence.prototype.constructor = FromEntriesSequence; - FromEntriesSequence.prototype.entrySeq = function entrySeq() { - return this._iter.toSeq(); - }; - FromEntriesSequence.prototype.__iterate = function __iterate(fn, reverse) { - var this$1 = this; - return this._iter.__iterate(function (entry) { - // Check if entry exists first so array access doesn't throw for holes - // in the parent iteration. - if (entry) { - validateEntry(entry); - var indexedCollection = isCollection(entry); - return fn(indexedCollection ? entry.get(1) : entry[1], indexedCollection ? entry.get(0) : entry[0], this$1); - } - }, reverse); - }; - FromEntriesSequence.prototype.__iterator = function __iterator(type, reverse) { - var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); - return new Iterator(function () { - while (true) { - var step = iterator.next(); - if (step.done) { - return step; - } - var entry = step.value; - // Check if entry exists first so array access doesn't throw for holes - // in the parent iteration. - if (entry) { - validateEntry(entry); - var indexedCollection = isCollection(entry); - return iteratorValue(type, indexedCollection ? entry.get(0) : entry[0], indexedCollection ? entry.get(1) : entry[1], step); - } - } - }); - }; - return FromEntriesSequence; -}(KeyedSeq)); -ToIndexedSequence.prototype.cacheResult = ToKeyedSequence.prototype.cacheResult = ToSetSequence.prototype.cacheResult = FromEntriesSequence.prototype.cacheResult = cacheResultThrough; -function flipFactory(collection) { - var flipSequence = makeSequence(collection); - flipSequence._iter = collection; - flipSequence.size = collection.size; - flipSequence.flip = function () { return collection; }; - flipSequence.reverse = function () { - var reversedSequence = collection.reverse.apply(this); // super.reverse() - reversedSequence.flip = function () { return collection.reverse(); }; - return reversedSequence; - }; - flipSequence.has = function (key) { return collection.includes(key); }; - flipSequence.includes = function (key) { return collection.has(key); }; - flipSequence.cacheResult = cacheResultThrough; - flipSequence.__iterateUncached = function (fn, reverse) { - var this$1 = this; - return collection.__iterate(function (v, k) { return fn(k, v, this$1) !== false; }, reverse); - }; - flipSequence.__iteratorUncached = function (type, reverse) { - if (type === ITERATE_ENTRIES) { - var iterator = collection.__iterator(type, reverse); - return new Iterator(function () { - var step = iterator.next(); - if (!step.done) { - var k = step.value[0]; - step.value[0] = step.value[1]; - step.value[1] = k; - } - return step; - }); - } - return collection.__iterator(type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES, reverse); - }; - return flipSequence; -} -function mapFactory(collection, mapper, context) { - var mappedSequence = makeSequence(collection); - mappedSequence.size = collection.size; - mappedSequence.has = function (key) { return collection.has(key); }; - mappedSequence.get = function (key, notSetValue) { - var v = collection.get(key, NOT_SET); - return v === NOT_SET - ? notSetValue - : mapper.call(context, v, key, collection); - }; - mappedSequence.__iterateUncached = function (fn, reverse) { - var this$1 = this; - return collection.__iterate(function (v, k, c) { return fn(mapper.call(context, v, k, c), k, this$1) !== false; }, reverse); - }; - mappedSequence.__iteratorUncached = function (type, reverse) { - var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); - return new Iterator(function () { - var step = iterator.next(); - if (step.done) { - return step; - } - var entry = step.value; - var key = entry[0]; - return iteratorValue(type, key, mapper.call(context, entry[1], key, collection), step); - }); - }; - return mappedSequence; -} -function reverseFactory(collection, useKeys) { - var this$1 = this; - var reversedSequence = makeSequence(collection); - reversedSequence._iter = collection; - reversedSequence.size = collection.size; - reversedSequence.reverse = function () { return collection; }; - if (collection.flip) { - reversedSequence.flip = function () { - var flipSequence = flipFactory(collection); - flipSequence.reverse = function () { return collection.flip(); }; - return flipSequence; - }; - } - reversedSequence.get = function (key, notSetValue) { return collection.get(useKeys ? key : -1 - key, notSetValue); }; - reversedSequence.has = function (key) { return collection.has(useKeys ? key : -1 - key); }; - reversedSequence.includes = function (value) { return collection.includes(value); }; - reversedSequence.cacheResult = cacheResultThrough; - reversedSequence.__iterate = function (fn, reverse) { - var this$1 = this; - var i = 0; - reverse && ensureSize(collection); - return collection.__iterate(function (v, k) { return fn(v, useKeys ? k : reverse ? this$1.size - ++i : i++, this$1); }, !reverse); - }; - reversedSequence.__iterator = function (type, reverse) { - var i = 0; - reverse && ensureSize(collection); - var iterator = collection.__iterator(ITERATE_ENTRIES, !reverse); - return new Iterator(function () { - var step = iterator.next(); - if (step.done) { - return step; - } - var entry = step.value; - return iteratorValue(type, useKeys ? entry[0] : reverse ? this$1.size - ++i : i++, entry[1], step); - }); - }; - return reversedSequence; -} -function filterFactory(collection, predicate, context, useKeys) { - var filterSequence = makeSequence(collection); - if (useKeys) { - filterSequence.has = function (key) { - var v = collection.get(key, NOT_SET); - return v !== NOT_SET && !!predicate.call(context, v, key, collection); - }; - filterSequence.get = function (key, notSetValue) { - var v = collection.get(key, NOT_SET); - return v !== NOT_SET && predicate.call(context, v, key, collection) - ? v - : notSetValue; - }; - } - filterSequence.__iterateUncached = function (fn, reverse) { - var this$1 = this; - var iterations = 0; - collection.__iterate(function (v, k, c) { - if (predicate.call(context, v, k, c)) { - iterations++; - return fn(v, useKeys ? k : iterations - 1, this$1); - } - }, reverse); - return iterations; - }; - filterSequence.__iteratorUncached = function (type, reverse) { - var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); - var iterations = 0; - return new Iterator(function () { - while (true) { - var step = iterator.next(); - if (step.done) { - return step; - } - var entry = step.value; - var key = entry[0]; - var value = entry[1]; - if (predicate.call(context, value, key, collection)) { - return iteratorValue(type, useKeys ? key : iterations++, value, step); - } - } - }); - }; - return filterSequence; -} -function countByFactory(collection, grouper, context) { - var groups = Map$1().asMutable(); - collection.__iterate(function (v, k) { - groups.update(grouper.call(context, v, k, collection), 0, function (a) { return a + 1; }); - }); - return groups.asImmutable(); -} -function groupByFactory(collection, grouper, context) { - var isKeyedIter = isKeyed(collection); - var groups = (isOrdered(collection) ? OrderedMap() : Map$1()).asMutable(); - collection.__iterate(function (v, k) { - groups.update(grouper.call(context, v, k, collection), function (a) { return ((a = a || []), a.push(isKeyedIter ? [k, v] : v), a); }); - }); - var coerce = collectionClass(collection); - return groups.map(function (arr) { return reify(collection, coerce(arr)); }).asImmutable(); -} -function sliceFactory(collection, begin, end, useKeys) { - var originalSize = collection.size; - if (wholeSlice(begin, end, originalSize)) { - return collection; - } - var resolvedBegin = resolveBegin(begin, originalSize); - var resolvedEnd = resolveEnd(end, originalSize); - // begin or end will be NaN if they were provided as negative numbers and - // this collection's size is unknown. In that case, cache first so there is - // a known size and these do not resolve to NaN. - if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) { - return sliceFactory(collection.toSeq().cacheResult(), begin, end, useKeys); - } - // Note: resolvedEnd is undefined when the original sequence's length is - // unknown and this slice did not supply an end and should contain all - // elements after resolvedBegin. - // In that case, resolvedSize will be NaN and sliceSize will remain undefined. - var resolvedSize = resolvedEnd - resolvedBegin; - var sliceSize; - if (resolvedSize === resolvedSize) { - sliceSize = resolvedSize < 0 ? 0 : resolvedSize; - } - var sliceSeq = makeSequence(collection); - // If collection.size is undefined, the size of the realized sliceSeq is - // unknown at this point unless the number of items to slice is 0 - sliceSeq.size = - sliceSize === 0 ? sliceSize : (collection.size && sliceSize) || undefined; - if (!useKeys && isSeq(collection) && sliceSize >= 0) { - sliceSeq.get = function (index, notSetValue) { - index = wrapIndex(this, index); - return index >= 0 && index < sliceSize - ? collection.get(index + resolvedBegin, notSetValue) - : notSetValue; - }; - } - sliceSeq.__iterateUncached = function (fn, reverse) { - var this$1 = this; - if (sliceSize === 0) { - return 0; - } - if (reverse) { - return this.cacheResult().__iterate(fn, reverse); - } - var skipped = 0; - var isSkipping = true; - var iterations = 0; - collection.__iterate(function (v, k) { - if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) { - iterations++; - return (fn(v, useKeys ? k : iterations - 1, this$1) !== false && - iterations !== sliceSize); - } - }); - return iterations; - }; - sliceSeq.__iteratorUncached = function (type, reverse) { - if (sliceSize !== 0 && reverse) { - return this.cacheResult().__iterator(type, reverse); - } - // Don't bother instantiating parent iterator if taking 0. - if (sliceSize === 0) { - return new Iterator(iteratorDone); - } - var iterator = collection.__iterator(type, reverse); - var skipped = 0; - var iterations = 0; - return new Iterator(function () { - while (skipped++ < resolvedBegin) { - iterator.next(); - } - if (++iterations > sliceSize) { - return iteratorDone(); - } - var step = iterator.next(); - if (useKeys || type === ITERATE_VALUES || step.done) { - return step; - } - if (type === ITERATE_KEYS) { - return iteratorValue(type, iterations - 1, undefined, step); - } - return iteratorValue(type, iterations - 1, step.value[1], step); - }); - }; - return sliceSeq; -} -function takeWhileFactory(collection, predicate, context) { - var takeSequence = makeSequence(collection); - takeSequence.__iterateUncached = function (fn, reverse) { - var this$1 = this; - if (reverse) { - return this.cacheResult().__iterate(fn, reverse); - } - var iterations = 0; - collection.__iterate(function (v, k, c) { return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$1); }); - return iterations; - }; - takeSequence.__iteratorUncached = function (type, reverse) { - var this$1 = this; - if (reverse) { - return this.cacheResult().__iterator(type, reverse); - } - var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); - var iterating = true; - return new Iterator(function () { - if (!iterating) { - return iteratorDone(); - } - var step = iterator.next(); - if (step.done) { - return step; - } - var entry = step.value; - var k = entry[0]; - var v = entry[1]; - if (!predicate.call(context, v, k, this$1)) { - iterating = false; - return iteratorDone(); - } - return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); - }); - }; - return takeSequence; -} -function skipWhileFactory(collection, predicate, context, useKeys) { - var skipSequence = makeSequence(collection); - skipSequence.__iterateUncached = function (fn, reverse) { - var this$1 = this; - if (reverse) { - return this.cacheResult().__iterate(fn, reverse); - } - var isSkipping = true; - var iterations = 0; - collection.__iterate(function (v, k, c) { - if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) { - iterations++; - return fn(v, useKeys ? k : iterations - 1, this$1); - } - }); - return iterations; - }; - skipSequence.__iteratorUncached = function (type, reverse) { - var this$1 = this; - if (reverse) { - return this.cacheResult().__iterator(type, reverse); - } - var iterator = collection.__iterator(ITERATE_ENTRIES, reverse); - var skipping = true; - var iterations = 0; - return new Iterator(function () { - var step; - var k; - var v; - do { - step = iterator.next(); - if (step.done) { - if (useKeys || type === ITERATE_VALUES) { - return step; - } - if (type === ITERATE_KEYS) { - return iteratorValue(type, iterations++, undefined, step); - } - return iteratorValue(type, iterations++, step.value[1], step); - } - var entry = step.value; - k = entry[0]; - v = entry[1]; - skipping && (skipping = predicate.call(context, v, k, this$1)); - } while (skipping); - return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); - }); - }; - return skipSequence; -} -function concatFactory(collection, values) { - var isKeyedCollection = isKeyed(collection); - var iters = [collection] - .concat(values) - .map(function (v) { - if (!isCollection(v)) { - v = isKeyedCollection - ? keyedSeqFromValue(v) - : indexedSeqFromValue(Array.isArray(v) ? v : [v]); - } - else if (isKeyedCollection) { - v = KeyedCollection(v); - } - return v; - }) - .filter(function (v) { return v.size !== 0; }); - if (iters.length === 0) { - return collection; - } - if (iters.length === 1) { - var singleton = iters[0]; - if (singleton === collection || - (isKeyedCollection && isKeyed(singleton)) || - (isIndexed(collection) && isIndexed(singleton))) { - return singleton; - } - } - var concatSeq = new ArraySeq(iters); - if (isKeyedCollection) { - concatSeq = concatSeq.toKeyedSeq(); - } - else if (!isIndexed(collection)) { - concatSeq = concatSeq.toSetSeq(); - } - concatSeq = concatSeq.flatten(true); - concatSeq.size = iters.reduce(function (sum, seq) { - if (sum !== undefined) { - var size = seq.size; - if (size !== undefined) { - return sum + size; - } - } - }, 0); - return concatSeq; -} -function flattenFactory(collection, depth, useKeys) { - var flatSequence = makeSequence(collection); - flatSequence.__iterateUncached = function (fn, reverse) { - if (reverse) { - return this.cacheResult().__iterate(fn, reverse); - } - var iterations = 0; - var stopped = false; - function flatDeep(iter, currentDepth) { - iter.__iterate(function (v, k) { - if ((!depth || currentDepth < depth) && isCollection(v)) { - flatDeep(v, currentDepth + 1); - } - else { - iterations++; - if (fn(v, useKeys ? k : iterations - 1, flatSequence) === false) { - stopped = true; - } - } - return !stopped; - }, reverse); - } - flatDeep(collection, 0); - return iterations; - }; - flatSequence.__iteratorUncached = function (type, reverse) { - if (reverse) { - return this.cacheResult().__iterator(type, reverse); - } - var iterator = collection.__iterator(type, reverse); - var stack = []; - var iterations = 0; - return new Iterator(function () { - while (iterator) { - var step = iterator.next(); - if (step.done !== false) { - iterator = stack.pop(); - continue; - } - var v = step.value; - if (type === ITERATE_ENTRIES) { - v = v[1]; - } - if ((!depth || stack.length < depth) && isCollection(v)) { - stack.push(iterator); - iterator = v.__iterator(type, reverse); - } - else { - return useKeys ? step : iteratorValue(type, iterations++, v, step); - } - } - return iteratorDone(); - }); - }; - return flatSequence; -} -function flatMapFactory(collection, mapper, context) { - var coerce = collectionClass(collection); - return collection - .toSeq() - .map(function (v, k) { return coerce(mapper.call(context, v, k, collection)); }) - .flatten(true); -} -function interposeFactory(collection, separator) { - var interposedSequence = makeSequence(collection); - interposedSequence.size = collection.size && collection.size * 2 - 1; - interposedSequence.__iterateUncached = function (fn, reverse) { - var this$1 = this; - var iterations = 0; - collection.__iterate(function (v) { - return (!iterations || fn(separator, iterations++, this$1) !== false) && - fn(v, iterations++, this$1) !== false; - }, reverse); - return iterations; - }; - interposedSequence.__iteratorUncached = function (type, reverse) { - var iterator = collection.__iterator(ITERATE_VALUES, reverse); - var iterations = 0; - var step; - return new Iterator(function () { - if (!step || iterations % 2) { - step = iterator.next(); - if (step.done) { - return step; - } - } - return iterations % 2 - ? iteratorValue(type, iterations++, separator) - : iteratorValue(type, iterations++, step.value, step); - }); - }; - return interposedSequence; -} -function sortFactory(collection, comparator, mapper) { - if (!comparator) { - comparator = defaultComparator; - } - var isKeyedCollection = isKeyed(collection); - var index = 0; - var entries = collection - .toSeq() - .map(function (v, k) { return [k, v, index++, mapper ? mapper(v, k, collection) : v]; }) - .valueSeq() - .toArray(); - entries.sort(function (a, b) { return comparator(a[3], b[3]) || a[2] - b[2]; }).forEach(isKeyedCollection - ? function (v, i) { - entries[i].length = 2; - } - : function (v, i) { - entries[i] = v[1]; - }); - return isKeyedCollection - ? KeyedSeq(entries) - : isIndexed(collection) - ? IndexedSeq(entries) - : SetSeq(entries); -} -function maxFactory(collection, comparator, mapper) { - if (!comparator) { - comparator = defaultComparator; - } - if (mapper) { - var entry = collection - .toSeq() - .map(function (v, k) { return [v, mapper(v, k, collection)]; }) - .reduce(function (a, b) { return (maxCompare(comparator, a[1], b[1]) ? b : a); }); - return entry && entry[0]; - } - return collection.reduce(function (a, b) { return (maxCompare(comparator, a, b) ? b : a); }); -} -function maxCompare(comparator, a, b) { - var comp = comparator(b, a); - // b is considered the new max if the comparator declares them equal, but - // they are not equal and b is in fact a nullish value. - return ((comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || - comp > 0); -} -function zipWithFactory(keyIter, zipper, iters, zipAll) { - var zipSequence = makeSequence(keyIter); - var sizes = new ArraySeq(iters).map(function (i) { return i.size; }); - zipSequence.size = zipAll ? sizes.max() : sizes.min(); - // Note: this a generic base implementation of __iterate in terms of - // __iterator which may be more generically useful in the future. - zipSequence.__iterate = function (fn, reverse) { - /* generic: - var iterator = this.__iterator(ITERATE_ENTRIES, reverse); - var step; - var iterations = 0; - while (!(step = iterator.next()).done) { - iterations++; - if (fn(step.value[1], step.value[0], this) === false) { - break; - } - } - return iterations; - */ - // indexed: - var iterator = this.__iterator(ITERATE_VALUES, reverse); - var step; - var iterations = 0; - while (!(step = iterator.next()).done) { - if (fn(step.value, iterations++, this) === false) { - break; - } - } - return iterations; - }; - zipSequence.__iteratorUncached = function (type, reverse) { - var iterators = iters.map(function (i) { return ((i = Collection(i)), getIterator(reverse ? i.reverse() : i)); }); - var iterations = 0; - var isDone = false; - return new Iterator(function () { - var steps; - if (!isDone) { - steps = iterators.map(function (i) { return i.next(); }); - isDone = zipAll ? steps.every(function (s) { return s.done; }) : steps.some(function (s) { return s.done; }); - } - if (isDone) { - return iteratorDone(); - } - return iteratorValue(type, iterations++, zipper.apply(null, steps.map(function (s) { return s.value; }))); - }); - }; - return zipSequence; -} -// #pragma Helper Functions -function reify(iter, seq) { - return iter === seq ? iter : isSeq(iter) ? seq : iter.constructor(seq); -} -function validateEntry(entry) { - if (entry !== Object(entry)) { - throw new TypeError('Expected [K, V] tuple: ' + entry); - } -} -function collectionClass(collection) { - return isKeyed(collection) - ? KeyedCollection - : isIndexed(collection) - ? IndexedCollection - : SetCollection; -} -function makeSequence(collection) { - return Object.create((isKeyed(collection) - ? KeyedSeq - : isIndexed(collection) - ? IndexedSeq - : SetSeq).prototype); -} -function cacheResultThrough() { - if (this._iter.cacheResult) { - this._iter.cacheResult(); - this.size = this._iter.size; - return this; - } - return Seq.prototype.cacheResult.call(this); -} -function defaultComparator(a, b) { - if (a === undefined && b === undefined) { - return 0; - } - if (a === undefined) { - return 1; - } - if (b === undefined) { - return -1; - } - return a > b ? 1 : a < b ? -1 : 0; -} -// http://jsperf.com/copy-array-inline -function arrCopy(arr, offset) { - offset = offset || 0; - var len = Math.max(0, arr.length - offset); - var newArr = new Array(len); - for (var ii = 0; ii < len; ii++) { - newArr[ii] = arr[ii + offset]; - } - return newArr; -} -function invariant(condition, error) { - if (!condition) { - throw new Error(error); - } -} -function assertNotInfinite(size) { - invariant(size !== Infinity, 'Cannot perform this action with an infinite size.'); -} -function coerceKeyPath(keyPath) { - if (isArrayLike(keyPath) && typeof keyPath !== 'string') { - return keyPath; - } - if (isOrdered(keyPath)) { - return keyPath.toArray(); - } - throw new TypeError('Invalid keyPath: expected Ordered Collection or Array: ' + keyPath); -} -function isPlainObj(value) { - return (value && - (typeof value.constructor !== 'function' || - value.constructor.name === 'Object')); -} -/** - * Returns true if the value is a potentially-persistent data structure, either - * provided by Immutable.js or a plain Array or Object. - */ -function isDataStructure(value) { - return (typeof value === 'object' && - (isImmutable(value) || Array.isArray(value) || isPlainObj(value))); -} -/** - * Converts a value to a string, adding quotes if a string was provided. - */ -function quoteString(value) { - try { - return typeof value === 'string' ? JSON.stringify(value) : String(value); - } - catch (_ignoreError) { - return JSON.stringify(value); - } -} -function has(collection, key) { - return isImmutable(collection) - ? collection.has(key) - : isDataStructure(collection) && hasOwnProperty.call(collection, key); -} -function get(collection, key, notSetValue) { - return isImmutable(collection) - ? collection.get(key, notSetValue) - : !has(collection, key) - ? notSetValue - : typeof collection.get === 'function' - ? collection.get(key) - : collection[key]; -} -function shallowCopy(from) { - if (Array.isArray(from)) { - return arrCopy(from); - } - var to = {}; - for (var key in from) { - if (hasOwnProperty.call(from, key)) { - to[key] = from[key]; - } - } - return to; -} -function remove(collection, key) { - if (!isDataStructure(collection)) { - throw new TypeError('Cannot update non-data-structure value: ' + collection); - } - if (isImmutable(collection)) { - if (!collection.remove) { - throw new TypeError('Cannot update immutable value without .remove() method: ' + collection); - } - return collection.remove(key); - } - if (!hasOwnProperty.call(collection, key)) { - return collection; - } - var collectionCopy = shallowCopy(collection); - if (Array.isArray(collectionCopy)) { - collectionCopy.splice(key, 1); - } - else { - delete collectionCopy[key]; - } - return collectionCopy; -} -function set(collection, key, value) { - if (!isDataStructure(collection)) { - throw new TypeError('Cannot update non-data-structure value: ' + collection); - } - if (isImmutable(collection)) { - if (!collection.set) { - throw new TypeError('Cannot update immutable value without .set() method: ' + collection); - } - return collection.set(key, value); - } - if (hasOwnProperty.call(collection, key) && value === collection[key]) { - return collection; - } - var collectionCopy = shallowCopy(collection); - collectionCopy[key] = value; - return collectionCopy; -} -function updateIn(collection, keyPath, notSetValue, updater) { - if (!updater) { - updater = notSetValue; - notSetValue = undefined; - } - var updatedValue = updateInDeeply(isImmutable(collection), collection, coerceKeyPath(keyPath), 0, notSetValue, updater); - return updatedValue === NOT_SET ? notSetValue : updatedValue; -} -function updateInDeeply(inImmutable, existing, keyPath, i, notSetValue, updater) { - var wasNotSet = existing === NOT_SET; - if (i === keyPath.length) { - var existingValue = wasNotSet ? notSetValue : existing; - var newValue = updater(existingValue); - return newValue === existingValue ? existing : newValue; - } - if (!wasNotSet && !isDataStructure(existing)) { - throw new TypeError('Cannot update within non-data-structure value in path [' + - keyPath.slice(0, i).map(quoteString) + - ']: ' + - existing); - } - var key = keyPath[i]; - var nextExisting = wasNotSet ? NOT_SET : get(existing, key, NOT_SET); - var nextUpdated = updateInDeeply(nextExisting === NOT_SET ? inImmutable : isImmutable(nextExisting), nextExisting, keyPath, i + 1, notSetValue, updater); - return nextUpdated === nextExisting - ? existing - : nextUpdated === NOT_SET - ? remove(existing, key) - : set(wasNotSet ? (inImmutable ? emptyMap() : {}) : existing, key, nextUpdated); -} -function setIn(collection, keyPath, value) { - return updateIn(collection, keyPath, NOT_SET, function () { return value; }); -} -function setIn$1(keyPath, v) { - return setIn(this, keyPath, v); -} -function removeIn(collection, keyPath) { - return updateIn(collection, keyPath, function () { return NOT_SET; }); -} -function deleteIn(keyPath) { - return removeIn(this, keyPath); -} -function update(collection, key, notSetValue, updater) { - return updateIn(collection, [key], notSetValue, updater); -} -function update$1(key, notSetValue, updater) { - return arguments.length === 1 - ? key(this) - : update(this, key, notSetValue, updater); -} -function updateIn$1(keyPath, notSetValue, updater) { - return updateIn(this, keyPath, notSetValue, updater); -} -function merge() { - var iters = [], len = arguments.length; - while (len--) - iters[len] = arguments[len]; - return mergeIntoKeyedWith(this, iters); -} -function mergeWith(merger) { - var iters = [], len = arguments.length - 1; - while (len-- > 0) - iters[len] = arguments[len + 1]; - if (typeof merger !== 'function') { - throw new TypeError('Invalid merger function: ' + merger); - } - return mergeIntoKeyedWith(this, iters, merger); -} -function mergeIntoKeyedWith(collection, collections, merger) { - var iters = []; - for (var ii = 0; ii < collections.length; ii++) { - var collection$1 = KeyedCollection(collections[ii]); - if (collection$1.size !== 0) { - iters.push(collection$1); - } - } - if (iters.length === 0) { - return collection; - } - if (collection.toSeq().size === 0 && - !collection.__ownerID && - iters.length === 1) { - return collection.constructor(iters[0]); - } - return collection.withMutations(function (collection) { - var mergeIntoCollection = merger - ? function (value, key) { - update(collection, key, NOT_SET, function (oldVal) { return (oldVal === NOT_SET ? value : merger(oldVal, value, key)); }); - } - : function (value, key) { - collection.set(key, value); - }; - for (var ii = 0; ii < iters.length; ii++) { - iters[ii].forEach(mergeIntoCollection); - } - }); -} -function merge$1(collection) { - var sources = [], len = arguments.length - 1; - while (len-- > 0) - sources[len] = arguments[len + 1]; - return mergeWithSources(collection, sources); -} -function mergeWith$1(merger, collection) { - var sources = [], len = arguments.length - 2; - while (len-- > 0) - sources[len] = arguments[len + 2]; - return mergeWithSources(collection, sources, merger); -} -function mergeDeep(collection) { - var sources = [], len = arguments.length - 1; - while (len-- > 0) - sources[len] = arguments[len + 1]; - return mergeDeepWithSources(collection, sources); -} -function mergeDeepWith(merger, collection) { - var sources = [], len = arguments.length - 2; - while (len-- > 0) - sources[len] = arguments[len + 2]; - return mergeDeepWithSources(collection, sources, merger); -} -function mergeDeepWithSources(collection, sources, merger) { - return mergeWithSources(collection, sources, deepMergerWith(merger)); -} -function mergeWithSources(collection, sources, merger) { - if (!isDataStructure(collection)) { - throw new TypeError('Cannot merge into non-data-structure value: ' + collection); - } - if (isImmutable(collection)) { - return typeof merger === 'function' && collection.mergeWith - ? collection.mergeWith.apply(collection, [merger].concat(sources)) - : collection.merge - ? collection.merge.apply(collection, sources) - : collection.concat.apply(collection, sources); - } - var isArray = Array.isArray(collection); - var merged = collection; - var Collection$$1 = isArray ? IndexedCollection : KeyedCollection; - var mergeItem = isArray - ? function (value) { - // Copy on write - if (merged === collection) { - merged = shallowCopy(merged); - } - merged.push(value); - } - : function (value, key) { - var hasVal = hasOwnProperty.call(merged, key); - var nextVal = hasVal && merger ? merger(merged[key], value, key) : value; - if (!hasVal || nextVal !== merged[key]) { - // Copy on write - if (merged === collection) { - merged = shallowCopy(merged); - } - merged[key] = nextVal; - } - }; - for (var i = 0; i < sources.length; i++) { - Collection$$1(sources[i]).forEach(mergeItem); - } - return merged; -} -function deepMergerWith(merger) { - function deepMerger(oldValue, newValue, key) { - return isDataStructure(oldValue) && isDataStructure(newValue) - ? mergeWithSources(oldValue, [newValue], deepMerger) - : merger - ? merger(oldValue, newValue, key) - : newValue; - } - return deepMerger; -} -function mergeDeep$1() { - var iters = [], len = arguments.length; - while (len--) - iters[len] = arguments[len]; - return mergeDeepWithSources(this, iters); -} -function mergeDeepWith$1(merger) { - var iters = [], len = arguments.length - 1; - while (len-- > 0) - iters[len] = arguments[len + 1]; - return mergeDeepWithSources(this, iters, merger); -} -function mergeIn(keyPath) { - var iters = [], len = arguments.length - 1; - while (len-- > 0) - iters[len] = arguments[len + 1]; - return updateIn(this, keyPath, emptyMap(), function (m) { return mergeWithSources(m, iters); }); -} -function mergeDeepIn(keyPath) { - var iters = [], len = arguments.length - 1; - while (len-- > 0) - iters[len] = arguments[len + 1]; - return updateIn(this, keyPath, emptyMap(), function (m) { return mergeDeepWithSources(m, iters); }); -} -function withMutations(fn) { - var mutable = this.asMutable(); - fn(mutable); - return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this; -} -function asMutable() { - return this.__ownerID ? this : this.__ensureOwner(new OwnerID()); -} -function asImmutable() { - return this.__ensureOwner(); -} -function wasAltered() { - return this.__altered; -} -var Map$1 = /*@__PURE__*/ (function (KeyedCollection$$1) { - function Map(value) { - return value === null || value === undefined - ? emptyMap() - : isMap(value) && !isOrdered(value) - ? value - : emptyMap().withMutations(function (map) { - var iter = KeyedCollection$$1(value); - assertNotInfinite(iter.size); - iter.forEach(function (v, k) { return map.set(k, v); }); - }); - } - if (KeyedCollection$$1) - Map.__proto__ = KeyedCollection$$1; - Map.prototype = Object.create(KeyedCollection$$1 && KeyedCollection$$1.prototype); - Map.prototype.constructor = Map; - Map.of = function of() { - var keyValues = [], len = arguments.length; - while (len--) - keyValues[len] = arguments[len]; - return emptyMap().withMutations(function (map) { - for (var i = 0; i < keyValues.length; i += 2) { - if (i + 1 >= keyValues.length) { - throw new Error('Missing value for key: ' + keyValues[i]); - } - map.set(keyValues[i], keyValues[i + 1]); - } - }); - }; - Map.prototype.toString = function toString() { - return this.__toString('Map {', '}'); - }; - // @pragma Access - Map.prototype.get = function get(k, notSetValue) { - return this._root - ? this._root.get(0, undefined, k, notSetValue) - : notSetValue; - }; - // @pragma Modification - Map.prototype.set = function set(k, v) { - return updateMap(this, k, v); - }; - Map.prototype.remove = function remove(k) { - return updateMap(this, k, NOT_SET); - }; - Map.prototype.deleteAll = function deleteAll(keys) { - var collection = Collection(keys); - if (collection.size === 0) { - return this; - } - return this.withMutations(function (map) { - collection.forEach(function (key) { return map.remove(key); }); - }); - }; - Map.prototype.clear = function clear() { - if (this.size === 0) { - return this; - } - if (this.__ownerID) { - this.size = 0; - this._root = null; - this.__hash = undefined; - this.__altered = true; - return this; - } - return emptyMap(); - }; - // @pragma Composition - Map.prototype.sort = function sort(comparator) { - // Late binding - return OrderedMap(sortFactory(this, comparator)); - }; - Map.prototype.sortBy = function sortBy(mapper, comparator) { - // Late binding - return OrderedMap(sortFactory(this, comparator, mapper)); - }; - Map.prototype.map = function map(mapper, context) { - return this.withMutations(function (map) { - map.forEach(function (value, key) { - map.set(key, mapper.call(context, value, key, map)); - }); - }); - }; - // @pragma Mutability - Map.prototype.__iterator = function __iterator(type, reverse) { - return new MapIterator(this, type, reverse); - }; - Map.prototype.__iterate = function __iterate(fn, reverse) { - var this$1 = this; - var iterations = 0; - this._root && - this._root.iterate(function (entry) { - iterations++; - return fn(entry[1], entry[0], this$1); - }, reverse); - return iterations; - }; - Map.prototype.__ensureOwner = function __ensureOwner(ownerID) { - if (ownerID === this.__ownerID) { - return this; - } - if (!ownerID) { - if (this.size === 0) { - return emptyMap(); - } - this.__ownerID = ownerID; - this.__altered = false; - return this; - } - return makeMap(this.size, this._root, ownerID, this.__hash); - }; - return Map; -}(KeyedCollection)); -Map$1.isMap = isMap; -var MapPrototype = Map$1.prototype; -MapPrototype[IS_MAP_SYMBOL] = true; -MapPrototype[DELETE] = MapPrototype.remove; -MapPrototype.removeAll = MapPrototype.deleteAll; -MapPrototype.setIn = setIn$1; -MapPrototype.removeIn = MapPrototype.deleteIn = deleteIn; -MapPrototype.update = update$1; -MapPrototype.updateIn = updateIn$1; -MapPrototype.merge = MapPrototype.concat = merge; -MapPrototype.mergeWith = mergeWith; -MapPrototype.mergeDeep = mergeDeep$1; -MapPrototype.mergeDeepWith = mergeDeepWith$1; -MapPrototype.mergeIn = mergeIn; -MapPrototype.mergeDeepIn = mergeDeepIn; -MapPrototype.withMutations = withMutations; -MapPrototype.wasAltered = wasAltered; -MapPrototype.asImmutable = asImmutable; -MapPrototype['@@transducer/init'] = MapPrototype.asMutable = asMutable; -MapPrototype['@@transducer/step'] = function (result, arr) { - return result.set(arr[0], arr[1]); -}; -MapPrototype['@@transducer/result'] = function (obj) { - return obj.asImmutable(); -}; -// #pragma Trie Nodes -var ArrayMapNode = function ArrayMapNode(ownerID, entries) { - this.ownerID = ownerID; - this.entries = entries; -}; -ArrayMapNode.prototype.get = function get(shift, keyHash, key, notSetValue) { - var entries = this.entries; - for (var ii = 0, len = entries.length; ii < len; ii++) { - if (is(key, entries[ii][0])) { - return entries[ii][1]; - } - } - return notSetValue; -}; -ArrayMapNode.prototype.update = function update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { - var removed = value === NOT_SET; - var entries = this.entries; - var idx = 0; - var len = entries.length; - for (; idx < len; idx++) { - if (is(key, entries[idx][0])) { - break; - } - } - var exists = idx < len; - if (exists ? entries[idx][1] === value : removed) { - return this; - } - SetRef(didAlter); - (removed || !exists) && SetRef(didChangeSize); - if (removed && entries.length === 1) { - return; // undefined - } - if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) { - return createNodes(ownerID, entries, key, value); - } - var isEditable = ownerID && ownerID === this.ownerID; - var newEntries = isEditable ? entries : arrCopy(entries); - if (exists) { - if (removed) { - idx === len - 1 - ? newEntries.pop() - : (newEntries[idx] = newEntries.pop()); - } - else { - newEntries[idx] = [key, value]; - } - } - else { - newEntries.push([key, value]); - } - if (isEditable) { - this.entries = newEntries; - return this; - } - return new ArrayMapNode(ownerID, newEntries); -}; -var BitmapIndexedNode = function BitmapIndexedNode(ownerID, bitmap, nodes) { - this.ownerID = ownerID; - this.bitmap = bitmap; - this.nodes = nodes; -}; -BitmapIndexedNode.prototype.get = function get(shift, keyHash, key, notSetValue) { - if (keyHash === undefined) { - keyHash = hash(key); - } - var bit = 1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK); - var bitmap = this.bitmap; - return (bitmap & bit) === 0 - ? notSetValue - : this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue); -}; -BitmapIndexedNode.prototype.update = function update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { - if (keyHash === undefined) { - keyHash = hash(key); - } - var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; - var bit = 1 << keyHashFrag; - var bitmap = this.bitmap; - var exists = (bitmap & bit) !== 0; - if (!exists && value === NOT_SET) { - return this; - } - var idx = popCount(bitmap & (bit - 1)); - var nodes = this.nodes; - var node = exists ? nodes[idx] : undefined; - var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); - if (newNode === node) { - return this; - } - if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) { - return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode); - } - if (exists && - !newNode && - nodes.length === 2 && - isLeafNode(nodes[idx ^ 1])) { - return nodes[idx ^ 1]; - } - if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) { - return newNode; - } - var isEditable = ownerID && ownerID === this.ownerID; - var newBitmap = exists ? (newNode ? bitmap : bitmap ^ bit) : bitmap | bit; - var newNodes = exists - ? newNode - ? setAt(nodes, idx, newNode, isEditable) - : spliceOut(nodes, idx, isEditable) - : spliceIn(nodes, idx, newNode, isEditable); - if (isEditable) { - this.bitmap = newBitmap; - this.nodes = newNodes; - return this; - } - return new BitmapIndexedNode(ownerID, newBitmap, newNodes); -}; -var HashArrayMapNode = function HashArrayMapNode(ownerID, count, nodes) { - this.ownerID = ownerID; - this.count = count; - this.nodes = nodes; -}; -HashArrayMapNode.prototype.get = function get(shift, keyHash, key, notSetValue) { - if (keyHash === undefined) { - keyHash = hash(key); - } - var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; - var node = this.nodes[idx]; - return node - ? node.get(shift + SHIFT, keyHash, key, notSetValue) - : notSetValue; -}; -HashArrayMapNode.prototype.update = function update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { - if (keyHash === undefined) { - keyHash = hash(key); - } - var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; - var removed = value === NOT_SET; - var nodes = this.nodes; - var node = nodes[idx]; - if (removed && !node) { - return this; - } - var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); - if (newNode === node) { - return this; - } - var newCount = this.count; - if (!node) { - newCount++; - } - else if (!newNode) { - newCount--; - if (newCount < MIN_HASH_ARRAY_MAP_SIZE) { - return packNodes(ownerID, nodes, newCount, idx); - } - } - var isEditable = ownerID && ownerID === this.ownerID; - var newNodes = setAt(nodes, idx, newNode, isEditable); - if (isEditable) { - this.count = newCount; - this.nodes = newNodes; - return this; - } - return new HashArrayMapNode(ownerID, newCount, newNodes); -}; -var HashCollisionNode = function HashCollisionNode(ownerID, keyHash, entries) { - this.ownerID = ownerID; - this.keyHash = keyHash; - this.entries = entries; -}; -HashCollisionNode.prototype.get = function get(shift, keyHash, key, notSetValue) { - var entries = this.entries; - for (var ii = 0, len = entries.length; ii < len; ii++) { - if (is(key, entries[ii][0])) { - return entries[ii][1]; - } - } - return notSetValue; -}; -HashCollisionNode.prototype.update = function update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { - if (keyHash === undefined) { - keyHash = hash(key); - } - var removed = value === NOT_SET; - if (keyHash !== this.keyHash) { - if (removed) { - return this; - } - SetRef(didAlter); - SetRef(didChangeSize); - return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]); - } - var entries = this.entries; - var idx = 0; - var len = entries.length; - for (; idx < len; idx++) { - if (is(key, entries[idx][0])) { - break; - } - } - var exists = idx < len; - if (exists ? entries[idx][1] === value : removed) { - return this; - } - SetRef(didAlter); - (removed || !exists) && SetRef(didChangeSize); - if (removed && len === 2) { - return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]); - } - var isEditable = ownerID && ownerID === this.ownerID; - var newEntries = isEditable ? entries : arrCopy(entries); - if (exists) { - if (removed) { - idx === len - 1 - ? newEntries.pop() - : (newEntries[idx] = newEntries.pop()); - } - else { - newEntries[idx] = [key, value]; - } - } - else { - newEntries.push([key, value]); - } - if (isEditable) { - this.entries = newEntries; - return this; - } - return new HashCollisionNode(ownerID, this.keyHash, newEntries); -}; -var ValueNode = function ValueNode(ownerID, keyHash, entry) { - this.ownerID = ownerID; - this.keyHash = keyHash; - this.entry = entry; -}; -ValueNode.prototype.get = function get(shift, keyHash, key, notSetValue) { - return is(key, this.entry[0]) ? this.entry[1] : notSetValue; -}; -ValueNode.prototype.update = function update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { - var removed = value === NOT_SET; - var keyMatch = is(key, this.entry[0]); - if (keyMatch ? value === this.entry[1] : removed) { - return this; - } - SetRef(didAlter); - if (removed) { - SetRef(didChangeSize); - return; // undefined - } - if (keyMatch) { - if (ownerID && ownerID === this.ownerID) { - this.entry[1] = value; - return this; - } - return new ValueNode(ownerID, this.keyHash, [key, value]); - } - SetRef(didChangeSize); - return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]); -}; -// #pragma Iterators -ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate = function (fn, reverse) { - var entries = this.entries; - for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) { - if (fn(entries[reverse ? maxIndex - ii : ii]) === false) { - return false; - } - } -}; -BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate = function (fn, reverse) { - var nodes = this.nodes; - for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) { - var node = nodes[reverse ? maxIndex - ii : ii]; - if (node && node.iterate(fn, reverse) === false) { - return false; - } - } -}; -// eslint-disable-next-line no-unused-vars -ValueNode.prototype.iterate = function (fn, reverse) { - return fn(this.entry); -}; -var MapIterator = /*@__PURE__*/ (function (Iterator$$1) { - function MapIterator(map, type, reverse) { - this._type = type; - this._reverse = reverse; - this._stack = map._root && mapIteratorFrame(map._root); - } - if (Iterator$$1) - MapIterator.__proto__ = Iterator$$1; - MapIterator.prototype = Object.create(Iterator$$1 && Iterator$$1.prototype); - MapIterator.prototype.constructor = MapIterator; - MapIterator.prototype.next = function next() { - var type = this._type; - var stack = this._stack; - while (stack) { - var node = stack.node; - var index = stack.index++; - var maxIndex = (void 0); - if (node.entry) { - if (index === 0) { - return mapIteratorValue(type, node.entry); - } - } - else if (node.entries) { - maxIndex = node.entries.length - 1; - if (index <= maxIndex) { - return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]); - } - } - else { - maxIndex = node.nodes.length - 1; - if (index <= maxIndex) { - var subNode = node.nodes[this._reverse ? maxIndex - index : index]; - if (subNode) { - if (subNode.entry) { - return mapIteratorValue(type, subNode.entry); - } - stack = this._stack = mapIteratorFrame(subNode, stack); - } - continue; - } - } - stack = this._stack = this._stack.__prev; - } - return iteratorDone(); - }; - return MapIterator; -}(Iterator)); -function mapIteratorValue(type, entry) { - return iteratorValue(type, entry[0], entry[1]); -} -function mapIteratorFrame(node, prev) { - return { - node: node, - index: 0, - __prev: prev, - }; -} -function makeMap(size, root, ownerID, hash$$1) { - var map = Object.create(MapPrototype); - map.size = size; - map._root = root; - map.__ownerID = ownerID; - map.__hash = hash$$1; - map.__altered = false; - return map; -} -var EMPTY_MAP; -function emptyMap() { - return EMPTY_MAP || (EMPTY_MAP = makeMap(0)); -} -function updateMap(map, k, v) { - var newRoot; - var newSize; - if (!map._root) { - if (v === NOT_SET) { - return map; - } - newSize = 1; - newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]); - } - else { - var didChangeSize = MakeRef(); - var didAlter = MakeRef(); - newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter); - if (!didAlter.value) { - return map; - } - newSize = map.size + (didChangeSize.value ? (v === NOT_SET ? -1 : 1) : 0); - } - if (map.__ownerID) { - map.size = newSize; - map._root = newRoot; - map.__hash = undefined; - map.__altered = true; - return map; - } - return newRoot ? makeMap(newSize, newRoot) : emptyMap(); -} -function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { - if (!node) { - if (value === NOT_SET) { - return node; - } - SetRef(didAlter); - SetRef(didChangeSize); - return new ValueNode(ownerID, keyHash, [key, value]); - } - return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter); -} -function isLeafNode(node) { - return (node.constructor === ValueNode || node.constructor === HashCollisionNode); -} -function mergeIntoNode(node, ownerID, shift, keyHash, entry) { - if (node.keyHash === keyHash) { - return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]); - } - var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK; - var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; - var newNode; - var nodes = idx1 === idx2 - ? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] - : ((newNode = new ValueNode(ownerID, keyHash, entry)), - idx1 < idx2 ? [node, newNode] : [newNode, node]); - return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes); -} -function createNodes(ownerID, entries, key, value) { - if (!ownerID) { - ownerID = new OwnerID(); - } - var node = new ValueNode(ownerID, hash(key), [key, value]); - for (var ii = 0; ii < entries.length; ii++) { - var entry = entries[ii]; - node = node.update(ownerID, 0, undefined, entry[0], entry[1]); - } - return node; -} -function packNodes(ownerID, nodes, count, excluding) { - var bitmap = 0; - var packedII = 0; - var packedNodes = new Array(count); - for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) { - var node = nodes[ii]; - if (node !== undefined && ii !== excluding) { - bitmap |= bit; - packedNodes[packedII++] = node; - } - } - return new BitmapIndexedNode(ownerID, bitmap, packedNodes); -} -function expandNodes(ownerID, nodes, bitmap, including, node) { - var count = 0; - var expandedNodes = new Array(SIZE); - for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) { - expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined; - } - expandedNodes[including] = node; - return new HashArrayMapNode(ownerID, count + 1, expandedNodes); -} -function popCount(x) { - x -= (x >> 1) & 0x55555555; - x = (x & 0x33333333) + ((x >> 2) & 0x33333333); - x = (x + (x >> 4)) & 0x0f0f0f0f; - x += x >> 8; - x += x >> 16; - return x & 0x7f; -} -function setAt(array, idx, val, canEdit) { - var newArray = canEdit ? array : arrCopy(array); - newArray[idx] = val; - return newArray; -} -function spliceIn(array, idx, val, canEdit) { - var newLen = array.length + 1; - if (canEdit && idx + 1 === newLen) { - array[idx] = val; - return array; - } - var newArray = new Array(newLen); - var after = 0; - for (var ii = 0; ii < newLen; ii++) { - if (ii === idx) { - newArray[ii] = val; - after = -1; - } - else { - newArray[ii] = array[ii + after]; - } - } - return newArray; -} -function spliceOut(array, idx, canEdit) { - var newLen = array.length - 1; - if (canEdit && idx === newLen) { - array.pop(); - return array; - } - var newArray = new Array(newLen); - var after = 0; - for (var ii = 0; ii < newLen; ii++) { - if (ii === idx) { - after = 1; - } - newArray[ii] = array[ii + after]; - } - return newArray; -} -var MAX_ARRAY_MAP_SIZE = SIZE / 4; -var MAX_BITMAP_INDEXED_SIZE = SIZE / 2; -var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4; -var IS_LIST_SYMBOL = '@@__IMMUTABLE_LIST__@@'; -function isList(maybeList) { - return Boolean(maybeList && maybeList[IS_LIST_SYMBOL]); -} -var List = /*@__PURE__*/ (function (IndexedCollection$$1) { - function List(value) { - var empty = emptyList(); - if (value === null || value === undefined) { - return empty; - } - if (isList(value)) { - return value; - } - var iter = IndexedCollection$$1(value); - var size = iter.size; - if (size === 0) { - return empty; - } - assertNotInfinite(size); - if (size > 0 && size < SIZE) { - return makeList(0, size, SHIFT, null, new VNode(iter.toArray())); - } - return empty.withMutations(function (list) { - list.setSize(size); - iter.forEach(function (v, i) { return list.set(i, v); }); - }); - } - if (IndexedCollection$$1) - List.__proto__ = IndexedCollection$$1; - List.prototype = Object.create(IndexedCollection$$1 && IndexedCollection$$1.prototype); - List.prototype.constructor = List; - List.of = function of( /*...values*/) { - return this(arguments); - }; - List.prototype.toString = function toString() { - return this.__toString('List [', ']'); - }; - // @pragma Access - List.prototype.get = function get(index, notSetValue) { - index = wrapIndex(this, index); - if (index >= 0 && index < this.size) { - index += this._origin; - var node = listNodeFor(this, index); - return node && node.array[index & MASK]; - } - return notSetValue; - }; - // @pragma Modification - List.prototype.set = function set(index, value) { - return updateList(this, index, value); - }; - List.prototype.remove = function remove(index) { - return !this.has(index) - ? this - : index === 0 - ? this.shift() - : index === this.size - 1 - ? this.pop() - : this.splice(index, 1); - }; - List.prototype.insert = function insert(index, value) { - return this.splice(index, 0, value); - }; - List.prototype.clear = function clear() { - if (this.size === 0) { - return this; - } - if (this.__ownerID) { - this.size = this._origin = this._capacity = 0; - this._level = SHIFT; - this._root = this._tail = null; - this.__hash = undefined; - this.__altered = true; - return this; - } - return emptyList(); - }; - List.prototype.push = function push( /*...values*/) { - var values = arguments; - var oldSize = this.size; - return this.withMutations(function (list) { - setListBounds(list, 0, oldSize + values.length); - for (var ii = 0; ii < values.length; ii++) { - list.set(oldSize + ii, values[ii]); - } - }); - }; - List.prototype.pop = function pop() { - return setListBounds(this, 0, -1); - }; - List.prototype.unshift = function unshift( /*...values*/) { - var values = arguments; - return this.withMutations(function (list) { - setListBounds(list, -values.length); - for (var ii = 0; ii < values.length; ii++) { - list.set(ii, values[ii]); - } - }); - }; - List.prototype.shift = function shift() { - return setListBounds(this, 1); - }; - // @pragma Composition - List.prototype.concat = function concat( /*...collections*/) { - var arguments$1 = arguments; - var seqs = []; - for (var i = 0; i < arguments.length; i++) { - var argument = arguments$1[i]; - var seq = IndexedCollection$$1(typeof argument !== 'string' && hasIterator(argument) - ? argument - : [argument]); - if (seq.size !== 0) { - seqs.push(seq); - } - } - if (seqs.length === 0) { - return this; - } - if (this.size === 0 && !this.__ownerID && seqs.length === 1) { - return this.constructor(seqs[0]); - } - return this.withMutations(function (list) { - seqs.forEach(function (seq) { return seq.forEach(function (value) { return list.push(value); }); }); - }); - }; - List.prototype.setSize = function setSize(size) { - return setListBounds(this, 0, size); - }; - List.prototype.map = function map(mapper, context) { - var this$1 = this; - return this.withMutations(function (list) { - for (var i = 0; i < this$1.size; i++) { - list.set(i, mapper.call(context, list.get(i), i, list)); - } - }); - }; - // @pragma Iteration - List.prototype.slice = function slice(begin, end) { - var size = this.size; - if (wholeSlice(begin, end, size)) { - return this; - } - return setListBounds(this, resolveBegin(begin, size), resolveEnd(end, size)); - }; - List.prototype.__iterator = function __iterator(type, reverse) { - var index = reverse ? this.size : 0; - var values = iterateList(this, reverse); - return new Iterator(function () { - var value = values(); - return value === DONE - ? iteratorDone() - : iteratorValue(type, reverse ? --index : index++, value); - }); - }; - List.prototype.__iterate = function __iterate(fn, reverse) { - var index = reverse ? this.size : 0; - var values = iterateList(this, reverse); - var value; - while ((value = values()) !== DONE) { - if (fn(value, reverse ? --index : index++, this) === false) { - break; - } - } - return index; - }; - List.prototype.__ensureOwner = function __ensureOwner(ownerID) { - if (ownerID === this.__ownerID) { - return this; - } - if (!ownerID) { - if (this.size === 0) { - return emptyList(); - } - this.__ownerID = ownerID; - this.__altered = false; - return this; - } - return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash); - }; - return List; -}(IndexedCollection)); -List.isList = isList; -var ListPrototype = List.prototype; -ListPrototype[IS_LIST_SYMBOL] = true; -ListPrototype[DELETE] = ListPrototype.remove; -ListPrototype.merge = ListPrototype.concat; -ListPrototype.setIn = setIn$1; -ListPrototype.deleteIn = ListPrototype.removeIn = deleteIn; -ListPrototype.update = update$1; -ListPrototype.updateIn = updateIn$1; -ListPrototype.mergeIn = mergeIn; -ListPrototype.mergeDeepIn = mergeDeepIn; -ListPrototype.withMutations = withMutations; -ListPrototype.wasAltered = wasAltered; -ListPrototype.asImmutable = asImmutable; -ListPrototype['@@transducer/init'] = ListPrototype.asMutable = asMutable; -ListPrototype['@@transducer/step'] = function (result, arr) { - return result.push(arr); -}; -ListPrototype['@@transducer/result'] = function (obj) { - return obj.asImmutable(); -}; -var VNode = function VNode(array, ownerID) { - this.array = array; - this.ownerID = ownerID; -}; -// TODO: seems like these methods are very similar -VNode.prototype.removeBefore = function removeBefore(ownerID, level, index) { - if (index === level ? 1 << level : this.array.length === 0) { - return this; - } - var originIndex = (index >>> level) & MASK; - if (originIndex >= this.array.length) { - return new VNode([], ownerID); - } - var removingFirst = originIndex === 0; - var newChild; - if (level > 0) { - var oldChild = this.array[originIndex]; - newChild = - oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index); - if (newChild === oldChild && removingFirst) { - return this; - } - } - if (removingFirst && !newChild) { - return this; - } - var editable = editableVNode(this, ownerID); - if (!removingFirst) { - for (var ii = 0; ii < originIndex; ii++) { - editable.array[ii] = undefined; - } - } - if (newChild) { - editable.array[originIndex] = newChild; - } - return editable; -}; -VNode.prototype.removeAfter = function removeAfter(ownerID, level, index) { - if (index === (level ? 1 << level : 0) || this.array.length === 0) { - return this; - } - var sizeIndex = ((index - 1) >>> level) & MASK; - if (sizeIndex >= this.array.length) { - return this; - } - var newChild; - if (level > 0) { - var oldChild = this.array[sizeIndex]; - newChild = - oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index); - if (newChild === oldChild && sizeIndex === this.array.length - 1) { - return this; - } - } - var editable = editableVNode(this, ownerID); - editable.array.splice(sizeIndex + 1); - if (newChild) { - editable.array[sizeIndex] = newChild; - } - return editable; -}; -var DONE = {}; -function iterateList(list, reverse) { - var left = list._origin; - var right = list._capacity; - var tailPos = getTailOffset(right); - var tail = list._tail; - return iterateNodeOrLeaf(list._root, list._level, 0); - function iterateNodeOrLeaf(node, level, offset) { - return level === 0 - ? iterateLeaf(node, offset) - : iterateNode(node, level, offset); - } - function iterateLeaf(node, offset) { - var array = offset === tailPos ? tail && tail.array : node && node.array; - var from = offset > left ? 0 : left - offset; - var to = right - offset; - if (to > SIZE) { - to = SIZE; - } - return function () { - if (from === to) { - return DONE; - } - var idx = reverse ? --to : from++; - return array && array[idx]; - }; - } - function iterateNode(node, level, offset) { - var values; - var array = node && node.array; - var from = offset > left ? 0 : (left - offset) >> level; - var to = ((right - offset) >> level) + 1; - if (to > SIZE) { - to = SIZE; - } - return function () { - while (true) { - if (values) { - var value = values(); - if (value !== DONE) { - return value; - } - values = null; - } - if (from === to) { - return DONE; - } - var idx = reverse ? --to : from++; - values = iterateNodeOrLeaf(array && array[idx], level - SHIFT, offset + (idx << level)); - } - }; - } -} -function makeList(origin, capacity, level, root, tail, ownerID, hash) { - var list = Object.create(ListPrototype); - list.size = capacity - origin; - list._origin = origin; - list._capacity = capacity; - list._level = level; - list._root = root; - list._tail = tail; - list.__ownerID = ownerID; - list.__hash = hash; - list.__altered = false; - return list; -} -var EMPTY_LIST; -function emptyList() { - return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT)); -} -function updateList(list, index, value) { - index = wrapIndex(list, index); - if (index !== index) { - return list; - } - if (index >= list.size || index < 0) { - return list.withMutations(function (list) { - index < 0 - ? setListBounds(list, index).set(0, value) - : setListBounds(list, 0, index + 1).set(index, value); - }); - } - index += list._origin; - var newTail = list._tail; - var newRoot = list._root; - var didAlter = MakeRef(); - if (index >= getTailOffset(list._capacity)) { - newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter); - } - else { - newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter); - } - if (!didAlter.value) { - return list; - } - if (list.__ownerID) { - list._root = newRoot; - list._tail = newTail; - list.__hash = undefined; - list.__altered = true; - return list; - } - return makeList(list._origin, list._capacity, list._level, newRoot, newTail); -} -function updateVNode(node, ownerID, level, index, value, didAlter) { - var idx = (index >>> level) & MASK; - var nodeHas = node && idx < node.array.length; - if (!nodeHas && value === undefined) { - return node; - } - var newNode; - if (level > 0) { - var lowerNode = node && node.array[idx]; - var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter); - if (newLowerNode === lowerNode) { - return node; - } - newNode = editableVNode(node, ownerID); - newNode.array[idx] = newLowerNode; - return newNode; - } - if (nodeHas && node.array[idx] === value) { - return node; - } - if (didAlter) { - SetRef(didAlter); - } - newNode = editableVNode(node, ownerID); - if (value === undefined && idx === newNode.array.length - 1) { - newNode.array.pop(); - } - else { - newNode.array[idx] = value; - } - return newNode; -} -function editableVNode(node, ownerID) { - if (ownerID && node && ownerID === node.ownerID) { - return node; - } - return new VNode(node ? node.array.slice() : [], ownerID); -} -function listNodeFor(list, rawIndex) { - if (rawIndex >= getTailOffset(list._capacity)) { - return list._tail; - } - if (rawIndex < 1 << (list._level + SHIFT)) { - var node = list._root; - var level = list._level; - while (node && level > 0) { - node = node.array[(rawIndex >>> level) & MASK]; - level -= SHIFT; - } - return node; - } -} -function setListBounds(list, begin, end) { - // Sanitize begin & end using this shorthand for ToInt32(argument) - // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 - if (begin !== undefined) { - begin |= 0; - } - if (end !== undefined) { - end |= 0; - } - var owner = list.__ownerID || new OwnerID(); - var oldOrigin = list._origin; - var oldCapacity = list._capacity; - var newOrigin = oldOrigin + begin; - var newCapacity = end === undefined - ? oldCapacity - : end < 0 - ? oldCapacity + end - : oldOrigin + end; - if (newOrigin === oldOrigin && newCapacity === oldCapacity) { - return list; - } - // If it's going to end after it starts, it's empty. - if (newOrigin >= newCapacity) { - return list.clear(); - } - var newLevel = list._level; - var newRoot = list._root; - // New origin might need creating a higher root. - var offsetShift = 0; - while (newOrigin + offsetShift < 0) { - newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner); - newLevel += SHIFT; - offsetShift += 1 << newLevel; - } - if (offsetShift) { - newOrigin += offsetShift; - oldOrigin += offsetShift; - newCapacity += offsetShift; - oldCapacity += offsetShift; - } - var oldTailOffset = getTailOffset(oldCapacity); - var newTailOffset = getTailOffset(newCapacity); - // New size might need creating a higher root. - while (newTailOffset >= 1 << (newLevel + SHIFT)) { - newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner); - newLevel += SHIFT; - } - // Locate or create the new tail. - var oldTail = list._tail; - var newTail = newTailOffset < oldTailOffset - ? listNodeFor(list, newCapacity - 1) - : newTailOffset > oldTailOffset - ? new VNode([], owner) - : oldTail; - // Merge Tail into tree. - if (oldTail && - newTailOffset > oldTailOffset && - newOrigin < oldCapacity && - oldTail.array.length) { - newRoot = editableVNode(newRoot, owner); - var node = newRoot; - for (var level = newLevel; level > SHIFT; level -= SHIFT) { - var idx = (oldTailOffset >>> level) & MASK; - node = node.array[idx] = editableVNode(node.array[idx], owner); - } - node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail; - } - // If the size has been reduced, there's a chance the tail needs to be trimmed. - if (newCapacity < oldCapacity) { - newTail = newTail && newTail.removeAfter(owner, 0, newCapacity); - } - // If the new origin is within the tail, then we do not need a root. - if (newOrigin >= newTailOffset) { - newOrigin -= newTailOffset; - newCapacity -= newTailOffset; - newLevel = SHIFT; - newRoot = null; - newTail = newTail && newTail.removeBefore(owner, 0, newOrigin); - // Otherwise, if the root has been trimmed, garbage collect. - } - else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) { - offsetShift = 0; - // Identify the new top root node of the subtree of the old root. - while (newRoot) { - var beginIndex = (newOrigin >>> newLevel) & MASK; - if ((beginIndex !== newTailOffset >>> newLevel) & MASK) { - break; - } - if (beginIndex) { - offsetShift += (1 << newLevel) * beginIndex; - } - newLevel -= SHIFT; - newRoot = newRoot.array[beginIndex]; - } - // Trim the new sides of the new root. - if (newRoot && newOrigin > oldOrigin) { - newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift); - } - if (newRoot && newTailOffset < oldTailOffset) { - newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift); - } - if (offsetShift) { - newOrigin -= offsetShift; - newCapacity -= offsetShift; - } - } - if (list.__ownerID) { - list.size = newCapacity - newOrigin; - list._origin = newOrigin; - list._capacity = newCapacity; - list._level = newLevel; - list._root = newRoot; - list._tail = newTail; - list.__hash = undefined; - list.__altered = true; - return list; - } - return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail); -} -function getTailOffset(size) { - return size < SIZE ? 0 : ((size - 1) >>> SHIFT) << SHIFT; -} -var OrderedMap = /*@__PURE__*/ (function (Map$$1) { - function OrderedMap(value) { - return value === null || value === undefined - ? emptyOrderedMap() - : isOrderedMap(value) - ? value - : emptyOrderedMap().withMutations(function (map) { - var iter = KeyedCollection(value); - assertNotInfinite(iter.size); - iter.forEach(function (v, k) { return map.set(k, v); }); - }); - } - if (Map$$1) - OrderedMap.__proto__ = Map$$1; - OrderedMap.prototype = Object.create(Map$$1 && Map$$1.prototype); - OrderedMap.prototype.constructor = OrderedMap; - OrderedMap.of = function of( /*...values*/) { - return this(arguments); - }; - OrderedMap.prototype.toString = function toString() { - return this.__toString('OrderedMap {', '}'); - }; - // @pragma Access - OrderedMap.prototype.get = function get(k, notSetValue) { - var index = this._map.get(k); - return index !== undefined ? this._list.get(index)[1] : notSetValue; - }; - // @pragma Modification - OrderedMap.prototype.clear = function clear() { - if (this.size === 0) { - return this; - } - if (this.__ownerID) { - this.size = 0; - this._map.clear(); - this._list.clear(); - return this; - } - return emptyOrderedMap(); - }; - OrderedMap.prototype.set = function set(k, v) { - return updateOrderedMap(this, k, v); - }; - OrderedMap.prototype.remove = function remove(k) { - return updateOrderedMap(this, k, NOT_SET); - }; - OrderedMap.prototype.wasAltered = function wasAltered() { - return this._map.wasAltered() || this._list.wasAltered(); - }; - OrderedMap.prototype.__iterate = function __iterate(fn, reverse) { - var this$1 = this; - return this._list.__iterate(function (entry) { return entry && fn(entry[1], entry[0], this$1); }, reverse); - }; - OrderedMap.prototype.__iterator = function __iterator(type, reverse) { - return this._list.fromEntrySeq().__iterator(type, reverse); - }; - OrderedMap.prototype.__ensureOwner = function __ensureOwner(ownerID) { - if (ownerID === this.__ownerID) { - return this; - } - var newMap = this._map.__ensureOwner(ownerID); - var newList = this._list.__ensureOwner(ownerID); - if (!ownerID) { - if (this.size === 0) { - return emptyOrderedMap(); - } - this.__ownerID = ownerID; - this._map = newMap; - this._list = newList; - return this; - } - return makeOrderedMap(newMap, newList, ownerID, this.__hash); - }; - return OrderedMap; -}(Map$1)); -OrderedMap.isOrderedMap = isOrderedMap; -OrderedMap.prototype[IS_ORDERED_SYMBOL] = true; -OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove; -function makeOrderedMap(map, list, ownerID, hash) { - var omap = Object.create(OrderedMap.prototype); - omap.size = map ? map.size : 0; - omap._map = map; - omap._list = list; - omap.__ownerID = ownerID; - omap.__hash = hash; - return omap; -} -var EMPTY_ORDERED_MAP; -function emptyOrderedMap() { - return (EMPTY_ORDERED_MAP || - (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList()))); -} -function updateOrderedMap(omap, k, v) { - var map = omap._map; - var list = omap._list; - var i = map.get(k); - var has = i !== undefined; - var newMap; - var newList; - if (v === NOT_SET) { - // removed - if (!has) { - return omap; - } - if (list.size >= SIZE && list.size >= map.size * 2) { - newList = list.filter(function (entry, idx) { return entry !== undefined && i !== idx; }); - newMap = newList - .toKeyedSeq() - .map(function (entry) { return entry[0]; }) - .flip() - .toMap(); - if (omap.__ownerID) { - newMap.__ownerID = newList.__ownerID = omap.__ownerID; - } - } - else { - newMap = map.remove(k); - newList = i === list.size - 1 ? list.pop() : list.set(i, undefined); - } - } - else if (has) { - if (v === list.get(i)[1]) { - return omap; - } - newMap = map; - newList = list.set(i, [k, v]); - } - else { - newMap = map.set(k, list.size); - newList = list.set(list.size, [k, v]); - } - if (omap.__ownerID) { - omap.size = newMap.size; - omap._map = newMap; - omap._list = newList; - omap.__hash = undefined; - return omap; - } - return makeOrderedMap(newMap, newList); -} -var IS_STACK_SYMBOL = '@@__IMMUTABLE_STACK__@@'; -function isStack(maybeStack) { - return Boolean(maybeStack && maybeStack[IS_STACK_SYMBOL]); -} -var Stack = /*@__PURE__*/ (function (IndexedCollection$$1) { - function Stack(value) { - return value === null || value === undefined - ? emptyStack() - : isStack(value) - ? value - : emptyStack().pushAll(value); - } - if (IndexedCollection$$1) - Stack.__proto__ = IndexedCollection$$1; - Stack.prototype = Object.create(IndexedCollection$$1 && IndexedCollection$$1.prototype); - Stack.prototype.constructor = Stack; - Stack.of = function of( /*...values*/) { - return this(arguments); - }; - Stack.prototype.toString = function toString() { - return this.__toString('Stack [', ']'); - }; - // @pragma Access - Stack.prototype.get = function get(index, notSetValue) { - var head = this._head; - index = wrapIndex(this, index); - while (head && index--) { - head = head.next; - } - return head ? head.value : notSetValue; - }; - Stack.prototype.peek = function peek() { - return this._head && this._head.value; - }; - // @pragma Modification - Stack.prototype.push = function push( /*...values*/) { - var arguments$1 = arguments; - if (arguments.length === 0) { - return this; - } - var newSize = this.size + arguments.length; - var head = this._head; - for (var ii = arguments.length - 1; ii >= 0; ii--) { - head = { - value: arguments$1[ii], - next: head, - }; - } - if (this.__ownerID) { - this.size = newSize; - this._head = head; - this.__hash = undefined; - this.__altered = true; - return this; - } - return makeStack(newSize, head); - }; - Stack.prototype.pushAll = function pushAll(iter) { - iter = IndexedCollection$$1(iter); - if (iter.size === 0) { - return this; - } - if (this.size === 0 && isStack(iter)) { - return iter; - } - assertNotInfinite(iter.size); - var newSize = this.size; - var head = this._head; - iter.__iterate(function (value) { - newSize++; - head = { - value: value, - next: head, - }; - }, /* reverse */ true); - if (this.__ownerID) { - this.size = newSize; - this._head = head; - this.__hash = undefined; - this.__altered = true; - return this; - } - return makeStack(newSize, head); - }; - Stack.prototype.pop = function pop() { - return this.slice(1); - }; - Stack.prototype.clear = function clear() { - if (this.size === 0) { - return this; - } - if (this.__ownerID) { - this.size = 0; - this._head = undefined; - this.__hash = undefined; - this.__altered = true; - return this; - } - return emptyStack(); - }; - Stack.prototype.slice = function slice(begin, end) { - if (wholeSlice(begin, end, this.size)) { - return this; - } - var resolvedBegin = resolveBegin(begin, this.size); - var resolvedEnd = resolveEnd(end, this.size); - if (resolvedEnd !== this.size) { - // super.slice(begin, end); - return IndexedCollection$$1.prototype.slice.call(this, begin, end); - } - var newSize = this.size - resolvedBegin; - var head = this._head; - while (resolvedBegin--) { - head = head.next; - } - if (this.__ownerID) { - this.size = newSize; - this._head = head; - this.__hash = undefined; - this.__altered = true; - return this; - } - return makeStack(newSize, head); - }; - // @pragma Mutability - Stack.prototype.__ensureOwner = function __ensureOwner(ownerID) { - if (ownerID === this.__ownerID) { - return this; - } - if (!ownerID) { - if (this.size === 0) { - return emptyStack(); - } - this.__ownerID = ownerID; - this.__altered = false; - return this; - } - return makeStack(this.size, this._head, ownerID, this.__hash); - }; - // @pragma Iteration - Stack.prototype.__iterate = function __iterate(fn, reverse) { - var this$1 = this; - if (reverse) { - return new ArraySeq(this.toArray()).__iterate(function (v, k) { return fn(v, k, this$1); }, reverse); - } - var iterations = 0; - var node = this._head; - while (node) { - if (fn(node.value, iterations++, this) === false) { - break; - } - node = node.next; - } - return iterations; - }; - Stack.prototype.__iterator = function __iterator(type, reverse) { - if (reverse) { - return new ArraySeq(this.toArray()).__iterator(type, reverse); - } - var iterations = 0; - var node = this._head; - return new Iterator(function () { - if (node) { - var value = node.value; - node = node.next; - return iteratorValue(type, iterations++, value); - } - return iteratorDone(); - }); - }; - return Stack; -}(IndexedCollection)); -Stack.isStack = isStack; -var StackPrototype = Stack.prototype; -StackPrototype[IS_STACK_SYMBOL] = true; -StackPrototype.shift = StackPrototype.pop; -StackPrototype.unshift = StackPrototype.push; -StackPrototype.unshiftAll = StackPrototype.pushAll; -StackPrototype.withMutations = withMutations; -StackPrototype.wasAltered = wasAltered; -StackPrototype.asImmutable = asImmutable; -StackPrototype['@@transducer/init'] = StackPrototype.asMutable = asMutable; -StackPrototype['@@transducer/step'] = function (result, arr) { - return result.unshift(arr); -}; -StackPrototype['@@transducer/result'] = function (obj) { - return obj.asImmutable(); -}; -function makeStack(size, head, ownerID, hash) { - var map = Object.create(StackPrototype); - map.size = size; - map._head = head; - map.__ownerID = ownerID; - map.__hash = hash; - map.__altered = false; - return map; -} -var EMPTY_STACK; -function emptyStack() { - return EMPTY_STACK || (EMPTY_STACK = makeStack(0)); -} -var IS_SET_SYMBOL = '@@__IMMUTABLE_SET__@@'; -function isSet(maybeSet) { - return Boolean(maybeSet && maybeSet[IS_SET_SYMBOL]); -} -function isOrderedSet(maybeOrderedSet) { - return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet); -} -function deepEqual(a, b) { - if (a === b) { - return true; - } - if (!isCollection(b) || - (a.size !== undefined && b.size !== undefined && a.size !== b.size) || - (a.__hash !== undefined && - b.__hash !== undefined && - a.__hash !== b.__hash) || - isKeyed(a) !== isKeyed(b) || - isIndexed(a) !== isIndexed(b) || - isOrdered(a) !== isOrdered(b)) { - return false; - } - if (a.size === 0 && b.size === 0) { - return true; - } - var notAssociative = !isAssociative(a); - if (isOrdered(a)) { - var entries = a.entries(); - return (b.every(function (v, k) { - var entry = entries.next().value; - return entry && is(entry[1], v) && (notAssociative || is(entry[0], k)); - }) && entries.next().done); - } - var flipped = false; - if (a.size === undefined) { - if (b.size === undefined) { - if (typeof a.cacheResult === 'function') { - a.cacheResult(); - } - } - else { - flipped = true; - var _ = a; - a = b; - b = _; - } - } - var allEqual = true; - var bSize = b.__iterate(function (v, k) { - if (notAssociative - ? !a.has(v) - : flipped - ? !is(v, a.get(k, NOT_SET)) - : !is(a.get(k, NOT_SET), v)) { - allEqual = false; - return false; - } - }); - return allEqual && a.size === bSize; -} -/** - * Contributes additional methods to a constructor - */ -function mixin(ctor, methods) { - var keyCopier = function (key) { - ctor.prototype[key] = methods[key]; - }; - Object.keys(methods).forEach(keyCopier); - Object.getOwnPropertySymbols && - Object.getOwnPropertySymbols(methods).forEach(keyCopier); - return ctor; -} -function toJS(value) { - if (!value || typeof value !== 'object') { - return value; - } - if (!isCollection(value)) { - if (!isDataStructure(value)) { - return value; - } - value = Seq(value); - } - if (isKeyed(value)) { - var result$1 = {}; - value.__iterate(function (v, k) { - result$1[k] = toJS(v); - }); - return result$1; - } - var result = []; - value.__iterate(function (v) { - result.push(toJS(v)); - }); - return result; -} -var Set$1 = /*@__PURE__*/ (function (SetCollection$$1) { - function Set(value) { - return value === null || value === undefined - ? emptySet() - : isSet(value) && !isOrdered(value) - ? value - : emptySet().withMutations(function (set) { - var iter = SetCollection$$1(value); - assertNotInfinite(iter.size); - iter.forEach(function (v) { return set.add(v); }); - }); - } - if (SetCollection$$1) - Set.__proto__ = SetCollection$$1; - Set.prototype = Object.create(SetCollection$$1 && SetCollection$$1.prototype); - Set.prototype.constructor = Set; - Set.of = function of( /*...values*/) { - return this(arguments); - }; - Set.fromKeys = function fromKeys(value) { - return this(KeyedCollection(value).keySeq()); - }; - Set.intersect = function intersect(sets) { - sets = Collection(sets).toArray(); - return sets.length - ? SetPrototype.intersect.apply(Set(sets.pop()), sets) - : emptySet(); - }; - Set.union = function union(sets) { - sets = Collection(sets).toArray(); - return sets.length - ? SetPrototype.union.apply(Set(sets.pop()), sets) - : emptySet(); - }; - Set.prototype.toString = function toString() { - return this.__toString('Set {', '}'); - }; - // @pragma Access - Set.prototype.has = function has(value) { - return this._map.has(value); - }; - // @pragma Modification - Set.prototype.add = function add(value) { - return updateSet(this, this._map.set(value, value)); - }; - Set.prototype.remove = function remove(value) { - return updateSet(this, this._map.remove(value)); - }; - Set.prototype.clear = function clear() { - return updateSet(this, this._map.clear()); - }; - // @pragma Composition - Set.prototype.map = function map(mapper, context) { - var this$1 = this; - var removes = []; - var adds = []; - this.forEach(function (value) { - var mapped = mapper.call(context, value, value, this$1); - if (mapped !== value) { - removes.push(value); - adds.push(mapped); - } - }); - return this.withMutations(function (set) { - removes.forEach(function (value) { return set.remove(value); }); - adds.forEach(function (value) { return set.add(value); }); - }); - }; - Set.prototype.union = function union() { - var iters = [], len = arguments.length; - while (len--) - iters[len] = arguments[len]; - iters = iters.filter(function (x) { return x.size !== 0; }); - if (iters.length === 0) { - return this; - } - if (this.size === 0 && !this.__ownerID && iters.length === 1) { - return this.constructor(iters[0]); - } - return this.withMutations(function (set) { - for (var ii = 0; ii < iters.length; ii++) { - SetCollection$$1(iters[ii]).forEach(function (value) { return set.add(value); }); - } - }); - }; - Set.prototype.intersect = function intersect() { - var iters = [], len = arguments.length; - while (len--) - iters[len] = arguments[len]; - if (iters.length === 0) { - return this; - } - iters = iters.map(function (iter) { return SetCollection$$1(iter); }); - var toRemove = []; - this.forEach(function (value) { - if (!iters.every(function (iter) { return iter.includes(value); })) { - toRemove.push(value); - } - }); - return this.withMutations(function (set) { - toRemove.forEach(function (value) { - set.remove(value); - }); - }); - }; - Set.prototype.subtract = function subtract() { - var iters = [], len = arguments.length; - while (len--) - iters[len] = arguments[len]; - if (iters.length === 0) { - return this; - } - iters = iters.map(function (iter) { return SetCollection$$1(iter); }); - var toRemove = []; - this.forEach(function (value) { - if (iters.some(function (iter) { return iter.includes(value); })) { - toRemove.push(value); - } - }); - return this.withMutations(function (set) { - toRemove.forEach(function (value) { - set.remove(value); - }); - }); - }; - Set.prototype.sort = function sort(comparator) { - // Late binding - return OrderedSet(sortFactory(this, comparator)); - }; - Set.prototype.sortBy = function sortBy(mapper, comparator) { - // Late binding - return OrderedSet(sortFactory(this, comparator, mapper)); - }; - Set.prototype.wasAltered = function wasAltered() { - return this._map.wasAltered(); - }; - Set.prototype.__iterate = function __iterate(fn, reverse) { - var this$1 = this; - return this._map.__iterate(function (k) { return fn(k, k, this$1); }, reverse); - }; - Set.prototype.__iterator = function __iterator(type, reverse) { - return this._map.__iterator(type, reverse); - }; - Set.prototype.__ensureOwner = function __ensureOwner(ownerID) { - if (ownerID === this.__ownerID) { - return this; - } - var newMap = this._map.__ensureOwner(ownerID); - if (!ownerID) { - if (this.size === 0) { - return this.__empty(); - } - this.__ownerID = ownerID; - this._map = newMap; - return this; - } - return this.__make(newMap, ownerID); - }; - return Set; -}(SetCollection)); -Set$1.isSet = isSet; -var SetPrototype = Set$1.prototype; -SetPrototype[IS_SET_SYMBOL] = true; -SetPrototype[DELETE] = SetPrototype.remove; -SetPrototype.merge = SetPrototype.concat = SetPrototype.union; -SetPrototype.withMutations = withMutations; -SetPrototype.asImmutable = asImmutable; -SetPrototype['@@transducer/init'] = SetPrototype.asMutable = asMutable; -SetPrototype['@@transducer/step'] = function (result, arr) { - return result.add(arr); -}; -SetPrototype['@@transducer/result'] = function (obj) { - return obj.asImmutable(); -}; -SetPrototype.__empty = emptySet; -SetPrototype.__make = makeSet; -function updateSet(set, newMap) { - if (set.__ownerID) { - set.size = newMap.size; - set._map = newMap; - return set; - } - return newMap === set._map - ? set - : newMap.size === 0 - ? set.__empty() - : set.__make(newMap); -} -function makeSet(map, ownerID) { - var set = Object.create(SetPrototype); - set.size = map ? map.size : 0; - set._map = map; - set.__ownerID = ownerID; - return set; -} -var EMPTY_SET; -function emptySet() { - return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap())); -} -/** - * Returns a lazy seq of nums from start (inclusive) to end - * (exclusive), by step, where start defaults to 0, step to 1, and end to - * infinity. When start is equal to end, returns empty list. - */ -var Range = /*@__PURE__*/ (function (IndexedSeq$$1) { - function Range(start, end, step) { - if (!(this instanceof Range)) { - return new Range(start, end, step); - } - invariant(step !== 0, 'Cannot step a Range by 0'); - start = start || 0; - if (end === undefined) { - end = Infinity; - } - step = step === undefined ? 1 : Math.abs(step); - if (end < start) { - step = -step; - } - this._start = start; - this._end = end; - this._step = step; - this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1); - if (this.size === 0) { - if (EMPTY_RANGE) { - return EMPTY_RANGE; - } - EMPTY_RANGE = this; - } - } - if (IndexedSeq$$1) - Range.__proto__ = IndexedSeq$$1; - Range.prototype = Object.create(IndexedSeq$$1 && IndexedSeq$$1.prototype); - Range.prototype.constructor = Range; - Range.prototype.toString = function toString() { - if (this.size === 0) { - return 'Range []'; - } - return ('Range [ ' + - this._start + - '...' + - this._end + - (this._step !== 1 ? ' by ' + this._step : '') + - ' ]'); - }; - Range.prototype.get = function get(index, notSetValue) { - return this.has(index) - ? this._start + wrapIndex(this, index) * this._step - : notSetValue; - }; - Range.prototype.includes = function includes(searchValue) { - var possibleIndex = (searchValue - this._start) / this._step; - return (possibleIndex >= 0 && - possibleIndex < this.size && - possibleIndex === Math.floor(possibleIndex)); - }; - Range.prototype.slice = function slice(begin, end) { - if (wholeSlice(begin, end, this.size)) { - return this; - } - begin = resolveBegin(begin, this.size); - end = resolveEnd(end, this.size); - if (end <= begin) { - return new Range(0, 0); - } - return new Range(this.get(begin, this._end), this.get(end, this._end), this._step); - }; - Range.prototype.indexOf = function indexOf(searchValue) { - var offsetValue = searchValue - this._start; - if (offsetValue % this._step === 0) { - var index = offsetValue / this._step; - if (index >= 0 && index < this.size) { - return index; - } - } - return -1; - }; - Range.prototype.lastIndexOf = function lastIndexOf(searchValue) { - return this.indexOf(searchValue); - }; - Range.prototype.__iterate = function __iterate(fn, reverse) { - var size = this.size; - var step = this._step; - var value = reverse ? this._start + (size - 1) * step : this._start; - var i = 0; - while (i !== size) { - if (fn(value, reverse ? size - ++i : i++, this) === false) { - break; - } - value += reverse ? -step : step; - } - return i; - }; - Range.prototype.__iterator = function __iterator(type, reverse) { - var size = this.size; - var step = this._step; - var value = reverse ? this._start + (size - 1) * step : this._start; - var i = 0; - return new Iterator(function () { - if (i === size) { - return iteratorDone(); - } - var v = value; - value += reverse ? -step : step; - return iteratorValue(type, reverse ? size - ++i : i++, v); - }); - }; - Range.prototype.equals = function equals(other) { - return other instanceof Range - ? this._start === other._start && - this._end === other._end && - this._step === other._step - : deepEqual(this, other); - }; - return Range; -}(IndexedSeq)); -var EMPTY_RANGE; -function getIn(collection, searchKeyPath, notSetValue) { - var keyPath = coerceKeyPath(searchKeyPath); - var i = 0; - while (i !== keyPath.length) { - collection = get(collection, keyPath[i++], NOT_SET); - if (collection === NOT_SET) { - return notSetValue; - } - } - return collection; -} -function getIn$1(searchKeyPath, notSetValue) { - return getIn(this, searchKeyPath, notSetValue); -} -function hasIn(collection, keyPath) { - return getIn(collection, keyPath, NOT_SET) !== NOT_SET; -} -function hasIn$1(searchKeyPath) { - return hasIn(this, searchKeyPath); -} -function toObject() { - assertNotInfinite(this.size); - var object = {}; - this.__iterate(function (v, k) { - object[k] = v; - }); - return object; -} -// Note: all of these methods are deprecated. -Collection.isIterable = isCollection; -Collection.isKeyed = isKeyed; -Collection.isIndexed = isIndexed; -Collection.isAssociative = isAssociative; -Collection.isOrdered = isOrdered; -Collection.Iterator = Iterator; -mixin(Collection, { - // ### Conversion to other types - toArray: function toArray() { - assertNotInfinite(this.size); - var array = new Array(this.size || 0); - var useTuples = isKeyed(this); - var i = 0; - this.__iterate(function (v, k) { - // Keyed collections produce an array of tuples. - array[i++] = useTuples ? [k, v] : v; - }); - return array; - }, - toIndexedSeq: function toIndexedSeq() { - return new ToIndexedSequence(this); - }, - toJS: function toJS$1() { - return toJS(this); - }, - toKeyedSeq: function toKeyedSeq() { - return new ToKeyedSequence(this, true); - }, - toMap: function toMap() { - // Use Late Binding here to solve the circular dependency. - return Map$1(this.toKeyedSeq()); - }, - toObject: toObject, - toOrderedMap: function toOrderedMap() { - // Use Late Binding here to solve the circular dependency. - return OrderedMap(this.toKeyedSeq()); - }, - toOrderedSet: function toOrderedSet() { - // Use Late Binding here to solve the circular dependency. - return OrderedSet(isKeyed(this) ? this.valueSeq() : this); - }, - toSet: function toSet() { - // Use Late Binding here to solve the circular dependency. - return Set$1(isKeyed(this) ? this.valueSeq() : this); - }, - toSetSeq: function toSetSeq() { - return new ToSetSequence(this); - }, - toSeq: function toSeq() { - return isIndexed(this) - ? this.toIndexedSeq() - : isKeyed(this) - ? this.toKeyedSeq() - : this.toSetSeq(); - }, - toStack: function toStack() { - // Use Late Binding here to solve the circular dependency. - return Stack(isKeyed(this) ? this.valueSeq() : this); - }, - toList: function toList() { - // Use Late Binding here to solve the circular dependency. - return List(isKeyed(this) ? this.valueSeq() : this); - }, - // ### Common JavaScript methods and properties - toString: function toString() { - return '[Collection]'; - }, - __toString: function __toString(head, tail) { - if (this.size === 0) { - return head + tail; - } - return (head + - ' ' + - this.toSeq() - .map(this.__toStringMapper) - .join(', ') + - ' ' + - tail); - }, - // ### ES6 Collection methods (ES6 Array and Map) - concat: function concat() { - var values = [], len = arguments.length; - while (len--) - values[len] = arguments[len]; - return reify(this, concatFactory(this, values)); - }, - includes: function includes(searchValue) { - return this.some(function (value) { return is(value, searchValue); }); - }, - entries: function entries() { - return this.__iterator(ITERATE_ENTRIES); - }, - every: function every(predicate, context) { - assertNotInfinite(this.size); - var returnValue = true; - this.__iterate(function (v, k, c) { - if (!predicate.call(context, v, k, c)) { - returnValue = false; - return false; - } - }); - return returnValue; - }, - filter: function filter(predicate, context) { - return reify(this, filterFactory(this, predicate, context, true)); - }, - find: function find(predicate, context, notSetValue) { - var entry = this.findEntry(predicate, context); - return entry ? entry[1] : notSetValue; - }, - forEach: function forEach(sideEffect, context) { - assertNotInfinite(this.size); - return this.__iterate(context ? sideEffect.bind(context) : sideEffect); - }, - join: function join(separator) { - assertNotInfinite(this.size); - separator = separator !== undefined ? '' + separator : ','; - var joined = ''; - var isFirst = true; - this.__iterate(function (v) { - isFirst ? (isFirst = false) : (joined += separator); - joined += v !== null && v !== undefined ? v.toString() : ''; - }); - return joined; - }, - keys: function keys() { - return this.__iterator(ITERATE_KEYS); - }, - map: function map(mapper, context) { - return reify(this, mapFactory(this, mapper, context)); - }, - reduce: function reduce$1(reducer, initialReduction, context) { - return reduce(this, reducer, initialReduction, context, arguments.length < 2, false); - }, - reduceRight: function reduceRight(reducer, initialReduction, context) { - return reduce(this, reducer, initialReduction, context, arguments.length < 2, true); - }, - reverse: function reverse() { - return reify(this, reverseFactory(this, true)); - }, - slice: function slice(begin, end) { - return reify(this, sliceFactory(this, begin, end, true)); - }, - some: function some(predicate, context) { - return !this.every(not(predicate), context); - }, - sort: function sort(comparator) { - return reify(this, sortFactory(this, comparator)); - }, - values: function values() { - return this.__iterator(ITERATE_VALUES); - }, - // ### More sequential methods - butLast: function butLast() { - return this.slice(0, -1); - }, - isEmpty: function isEmpty() { - return this.size !== undefined ? this.size === 0 : !this.some(function () { return true; }); - }, - count: function count(predicate, context) { - return ensureSize(predicate ? this.toSeq().filter(predicate, context) : this); - }, - countBy: function countBy(grouper, context) { - return countByFactory(this, grouper, context); - }, - equals: function equals(other) { - return deepEqual(this, other); - }, - entrySeq: function entrySeq() { - var collection = this; - if (collection._cache) { - // We cache as an entries array, so we can just return the cache! - return new ArraySeq(collection._cache); - } - var entriesSequence = collection - .toSeq() - .map(entryMapper) - .toIndexedSeq(); - entriesSequence.fromEntrySeq = function () { return collection.toSeq(); }; - return entriesSequence; - }, - filterNot: function filterNot(predicate, context) { - return this.filter(not(predicate), context); - }, - findEntry: function findEntry(predicate, context, notSetValue) { - var found = notSetValue; - this.__iterate(function (v, k, c) { - if (predicate.call(context, v, k, c)) { - found = [k, v]; - return false; - } - }); - return found; - }, - findKey: function findKey(predicate, context) { - var entry = this.findEntry(predicate, context); - return entry && entry[0]; - }, - findLast: function findLast(predicate, context, notSetValue) { - return this.toKeyedSeq() - .reverse() - .find(predicate, context, notSetValue); - }, - findLastEntry: function findLastEntry(predicate, context, notSetValue) { - return this.toKeyedSeq() - .reverse() - .findEntry(predicate, context, notSetValue); - }, - findLastKey: function findLastKey(predicate, context) { - return this.toKeyedSeq() - .reverse() - .findKey(predicate, context); - }, - first: function first(notSetValue) { - return this.find(returnTrue, null, notSetValue); - }, - flatMap: function flatMap(mapper, context) { - return reify(this, flatMapFactory(this, mapper, context)); - }, - flatten: function flatten(depth) { - return reify(this, flattenFactory(this, depth, true)); - }, - fromEntrySeq: function fromEntrySeq() { - return new FromEntriesSequence(this); - }, - get: function get(searchKey, notSetValue) { - return this.find(function (_, key) { return is(key, searchKey); }, undefined, notSetValue); - }, - getIn: getIn$1, - groupBy: function groupBy(grouper, context) { - return groupByFactory(this, grouper, context); - }, - has: function has(searchKey) { - return this.get(searchKey, NOT_SET) !== NOT_SET; - }, - hasIn: hasIn$1, - isSubset: function isSubset(iter) { - iter = typeof iter.includes === 'function' ? iter : Collection(iter); - return this.every(function (value) { return iter.includes(value); }); - }, - isSuperset: function isSuperset(iter) { - iter = typeof iter.isSubset === 'function' ? iter : Collection(iter); - return iter.isSubset(this); - }, - keyOf: function keyOf(searchValue) { - return this.findKey(function (value) { return is(value, searchValue); }); - }, - keySeq: function keySeq() { - return this.toSeq() - .map(keyMapper) - .toIndexedSeq(); - }, - last: function last(notSetValue) { - return this.toSeq() - .reverse() - .first(notSetValue); - }, - lastKeyOf: function lastKeyOf(searchValue) { - return this.toKeyedSeq() - .reverse() - .keyOf(searchValue); - }, - max: function max(comparator) { - return maxFactory(this, comparator); - }, - maxBy: function maxBy(mapper, comparator) { - return maxFactory(this, comparator, mapper); - }, - min: function min(comparator) { - return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator); - }, - minBy: function minBy(mapper, comparator) { - return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper); - }, - rest: function rest() { - return this.slice(1); - }, - skip: function skip(amount) { - return amount === 0 ? this : this.slice(Math.max(0, amount)); - }, - skipLast: function skipLast(amount) { - return amount === 0 ? this : this.slice(0, -Math.max(0, amount)); - }, - skipWhile: function skipWhile(predicate, context) { - return reify(this, skipWhileFactory(this, predicate, context, true)); - }, - skipUntil: function skipUntil(predicate, context) { - return this.skipWhile(not(predicate), context); - }, - sortBy: function sortBy(mapper, comparator) { - return reify(this, sortFactory(this, comparator, mapper)); - }, - take: function take(amount) { - return this.slice(0, Math.max(0, amount)); - }, - takeLast: function takeLast(amount) { - return this.slice(-Math.max(0, amount)); - }, - takeWhile: function takeWhile(predicate, context) { - return reify(this, takeWhileFactory(this, predicate, context)); - }, - takeUntil: function takeUntil(predicate, context) { - return this.takeWhile(not(predicate), context); - }, - update: function update(fn) { - return fn(this); - }, - valueSeq: function valueSeq() { - return this.toIndexedSeq(); - }, - // ### Hashable Object - hashCode: function hashCode() { - return this.__hash || (this.__hash = hashCollection(this)); - }, -}); -var CollectionPrototype = Collection.prototype; -CollectionPrototype[IS_COLLECTION_SYMBOL] = true; -CollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.values; -CollectionPrototype.toJSON = CollectionPrototype.toArray; -CollectionPrototype.__toStringMapper = quoteString; -CollectionPrototype.inspect = CollectionPrototype.toSource = function () { - return this.toString(); -}; -CollectionPrototype.chain = CollectionPrototype.flatMap; -CollectionPrototype.contains = CollectionPrototype.includes; -mixin(KeyedCollection, { - // ### More sequential methods - flip: function flip() { - return reify(this, flipFactory(this)); - }, - mapEntries: function mapEntries(mapper, context) { - var this$1 = this; - var iterations = 0; - return reify(this, this.toSeq() - .map(function (v, k) { return mapper.call(context, [k, v], iterations++, this$1); }) - .fromEntrySeq()); - }, - mapKeys: function mapKeys(mapper, context) { - var this$1 = this; - return reify(this, this.toSeq() - .flip() - .map(function (k, v) { return mapper.call(context, k, v, this$1); }) - .flip()); - }, -}); -var KeyedCollectionPrototype = KeyedCollection.prototype; -KeyedCollectionPrototype[IS_KEYED_SYMBOL] = true; -KeyedCollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.entries; -KeyedCollectionPrototype.toJSON = toObject; -KeyedCollectionPrototype.__toStringMapper = function (v, k) { return quoteString(k) + ': ' + quoteString(v); }; -mixin(IndexedCollection, { - // ### Conversion to other types - toKeyedSeq: function toKeyedSeq() { - return new ToKeyedSequence(this, false); - }, - // ### ES6 Collection methods (ES6 Array and Map) - filter: function filter(predicate, context) { - return reify(this, filterFactory(this, predicate, context, false)); - }, - findIndex: function findIndex(predicate, context) { - var entry = this.findEntry(predicate, context); - return entry ? entry[0] : -1; - }, - indexOf: function indexOf(searchValue) { - var key = this.keyOf(searchValue); - return key === undefined ? -1 : key; - }, - lastIndexOf: function lastIndexOf(searchValue) { - var key = this.lastKeyOf(searchValue); - return key === undefined ? -1 : key; - }, - reverse: function reverse() { - return reify(this, reverseFactory(this, false)); - }, - slice: function slice(begin, end) { - return reify(this, sliceFactory(this, begin, end, false)); - }, - splice: function splice(index, removeNum /*, ...values*/) { - var numArgs = arguments.length; - removeNum = Math.max(removeNum || 0, 0); - if (numArgs === 0 || (numArgs === 2 && !removeNum)) { - return this; - } - // If index is negative, it should resolve relative to the size of the - // collection. However size may be expensive to compute if not cached, so - // only call count() if the number is in fact negative. - index = resolveBegin(index, index < 0 ? this.count() : this.size); - var spliced = this.slice(0, index); - return reify(this, numArgs === 1 - ? spliced - : spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum))); - }, - // ### More collection methods - findLastIndex: function findLastIndex(predicate, context) { - var entry = this.findLastEntry(predicate, context); - return entry ? entry[0] : -1; - }, - first: function first(notSetValue) { - return this.get(0, notSetValue); - }, - flatten: function flatten(depth) { - return reify(this, flattenFactory(this, depth, false)); - }, - get: function get(index, notSetValue) { - index = wrapIndex(this, index); - return index < 0 || - (this.size === Infinity || (this.size !== undefined && index > this.size)) - ? notSetValue - : this.find(function (_, key) { return key === index; }, undefined, notSetValue); - }, - has: function has(index) { - index = wrapIndex(this, index); - return (index >= 0 && - (this.size !== undefined - ? this.size === Infinity || index < this.size - : this.indexOf(index) !== -1)); - }, - interpose: function interpose(separator) { - return reify(this, interposeFactory(this, separator)); - }, - interleave: function interleave( /*...collections*/) { - var collections = [this].concat(arrCopy(arguments)); - var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, collections); - var interleaved = zipped.flatten(true); - if (zipped.size) { - interleaved.size = zipped.size * collections.length; - } - return reify(this, interleaved); - }, - keySeq: function keySeq() { - return Range(0, this.size); - }, - last: function last(notSetValue) { - return this.get(-1, notSetValue); - }, - skipWhile: function skipWhile(predicate, context) { - return reify(this, skipWhileFactory(this, predicate, context, false)); - }, - zip: function zip( /*, ...collections */) { - var collections = [this].concat(arrCopy(arguments)); - return reify(this, zipWithFactory(this, defaultZipper, collections)); - }, - zipAll: function zipAll( /*, ...collections */) { - var collections = [this].concat(arrCopy(arguments)); - return reify(this, zipWithFactory(this, defaultZipper, collections, true)); - }, - zipWith: function zipWith(zipper /*, ...collections */) { - var collections = arrCopy(arguments); - collections[0] = this; - return reify(this, zipWithFactory(this, zipper, collections)); - }, -}); -var IndexedCollectionPrototype = IndexedCollection.prototype; -IndexedCollectionPrototype[IS_INDEXED_SYMBOL] = true; -IndexedCollectionPrototype[IS_ORDERED_SYMBOL] = true; -mixin(SetCollection, { - // ### ES6 Collection methods (ES6 Array and Map) - get: function get(value, notSetValue) { - return this.has(value) ? value : notSetValue; - }, - includes: function includes(value) { - return this.has(value); - }, - // ### More sequential methods - keySeq: function keySeq() { - return this.valueSeq(); - }, -}); -SetCollection.prototype.has = CollectionPrototype.includes; -SetCollection.prototype.contains = SetCollection.prototype.includes; -// Mixin subclasses -mixin(KeyedSeq, KeyedCollection.prototype); -mixin(IndexedSeq, IndexedCollection.prototype); -mixin(SetSeq, SetCollection.prototype); -// #pragma Helper functions -function reduce(collection, reducer, reduction, context, useFirst, reverse) { - assertNotInfinite(collection.size); - collection.__iterate(function (v, k, c) { - if (useFirst) { - useFirst = false; - reduction = v; - } - else { - reduction = reducer.call(context, reduction, v, k, c); - } - }, reverse); - return reduction; -} -function keyMapper(v, k) { - return k; -} -function entryMapper(v, k) { - return [k, v]; -} -function not(predicate) { - return function () { - return !predicate.apply(this, arguments); - }; -} -function neg(predicate) { - return function () { - return -predicate.apply(this, arguments); - }; -} -function defaultZipper() { - return arrCopy(arguments); -} -function defaultNegComparator(a, b) { - return a < b ? 1 : a > b ? -1 : 0; -} -function hashCollection(collection) { - if (collection.size === Infinity) { - return 0; - } - var ordered = isOrdered(collection); - var keyed = isKeyed(collection); - var h = ordered ? 1 : 0; - var size = collection.__iterate(keyed - ? ordered - ? function (v, k) { - h = (31 * h + hashMerge(hash(v), hash(k))) | 0; - } - : function (v, k) { - h = (h + hashMerge(hash(v), hash(k))) | 0; - } - : ordered - ? function (v) { - h = (31 * h + hash(v)) | 0; - } - : function (v) { - h = (h + hash(v)) | 0; - }); - return murmurHashOfSize(size, h); -} -function murmurHashOfSize(size, h) { - h = imul(h, 0xcc9e2d51); - h = imul((h << 15) | (h >>> -15), 0x1b873593); - h = imul((h << 13) | (h >>> -13), 5); - h = ((h + 0xe6546b64) | 0) ^ size; - h = imul(h ^ (h >>> 16), 0x85ebca6b); - h = imul(h ^ (h >>> 13), 0xc2b2ae35); - h = smi(h ^ (h >>> 16)); - return h; -} -function hashMerge(a, b) { - return (a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2))) | 0; // int -} -var OrderedSet = /*@__PURE__*/ (function (Set$$1) { - function OrderedSet(value) { - return value === null || value === undefined - ? emptyOrderedSet() - : isOrderedSet(value) - ? value - : emptyOrderedSet().withMutations(function (set) { - var iter = SetCollection(value); - assertNotInfinite(iter.size); - iter.forEach(function (v) { return set.add(v); }); - }); - } - if (Set$$1) - OrderedSet.__proto__ = Set$$1; - OrderedSet.prototype = Object.create(Set$$1 && Set$$1.prototype); - OrderedSet.prototype.constructor = OrderedSet; - OrderedSet.of = function of( /*...values*/) { - return this(arguments); - }; - OrderedSet.fromKeys = function fromKeys(value) { - return this(KeyedCollection(value).keySeq()); - }; - OrderedSet.prototype.toString = function toString() { - return this.__toString('OrderedSet {', '}'); - }; - return OrderedSet; -}(Set$1)); -OrderedSet.isOrderedSet = isOrderedSet; -var OrderedSetPrototype = OrderedSet.prototype; -OrderedSetPrototype[IS_ORDERED_SYMBOL] = true; -OrderedSetPrototype.zip = IndexedCollectionPrototype.zip; -OrderedSetPrototype.zipWith = IndexedCollectionPrototype.zipWith; -OrderedSetPrototype.__empty = emptyOrderedSet; -OrderedSetPrototype.__make = makeOrderedSet; -function makeOrderedSet(map, ownerID) { - var set = Object.create(OrderedSetPrototype); - set.size = map ? map.size : 0; - set._map = map; - set.__ownerID = ownerID; - return set; -} -var EMPTY_ORDERED_SET; -function emptyOrderedSet() { - return (EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap()))); -} -var Record = function Record(defaultValues, name) { - var hasInitialized; - var RecordType = function Record(values) { - var this$1 = this; - if (values instanceof RecordType) { - return values; - } - if (!(this instanceof RecordType)) { - return new RecordType(values); - } - if (!hasInitialized) { - hasInitialized = true; - var keys = Object.keys(defaultValues); - var indices = (RecordTypePrototype._indices = {}); - // Deprecated: left to attempt not to break any external code which - // relies on a ._name property existing on record instances. - // Use Record.getDescriptiveName() instead - RecordTypePrototype._name = name; - RecordTypePrototype._keys = keys; - RecordTypePrototype._defaultValues = defaultValues; - for (var i = 0; i < keys.length; i++) { - var propName = keys[i]; - indices[propName] = i; - if (RecordTypePrototype[propName]) { - /* eslint-disable no-console */ - typeof console === 'object' && - console.warn && - console.warn('Cannot define ' + - recordName(this) + - ' with property "' + - propName + - '" since that property name is part of the Record API.'); - /* eslint-enable no-console */ - } - else { - setProp(RecordTypePrototype, propName); - } - } - } - this.__ownerID = undefined; - this._values = List().withMutations(function (l) { - l.setSize(this$1._keys.length); - KeyedCollection(values).forEach(function (v, k) { - l.set(this$1._indices[k], v === this$1._defaultValues[k] ? undefined : v); - }); - }); - }; - var RecordTypePrototype = (RecordType.prototype = Object.create(RecordPrototype)); - RecordTypePrototype.constructor = RecordType; - if (name) { - RecordType.displayName = name; - } - return RecordType; -}; -Record.prototype.toString = function toString() { - var str = recordName(this) + ' { '; - var keys = this._keys; - var k; - for (var i = 0, l = keys.length; i !== l; i++) { - k = keys[i]; - str += (i ? ', ' : '') + k + ': ' + quoteString(this.get(k)); - } - return str + ' }'; -}; -Record.prototype.equals = function equals(other) { - return (this === other || - (other && - this._keys === other._keys && - recordSeq(this).equals(recordSeq(other)))); -}; -Record.prototype.hashCode = function hashCode() { - return recordSeq(this).hashCode(); -}; -// @pragma Access -Record.prototype.has = function has(k) { - return this._indices.hasOwnProperty(k); -}; -Record.prototype.get = function get(k, notSetValue) { - if (!this.has(k)) { - return notSetValue; - } - var index = this._indices[k]; - var value = this._values.get(index); - return value === undefined ? this._defaultValues[k] : value; -}; -// @pragma Modification -Record.prototype.set = function set(k, v) { - if (this.has(k)) { - var newValues = this._values.set(this._indices[k], v === this._defaultValues[k] ? undefined : v); - if (newValues !== this._values && !this.__ownerID) { - return makeRecord(this, newValues); - } - } - return this; -}; -Record.prototype.remove = function remove(k) { - return this.set(k); -}; -Record.prototype.clear = function clear() { - var newValues = this._values.clear().setSize(this._keys.length); - return this.__ownerID ? this : makeRecord(this, newValues); -}; -Record.prototype.wasAltered = function wasAltered() { - return this._values.wasAltered(); -}; -Record.prototype.toSeq = function toSeq() { - return recordSeq(this); -}; -Record.prototype.toJS = function toJS$1() { - return toJS(this); -}; -Record.prototype.entries = function entries() { - return this.__iterator(ITERATE_ENTRIES); -}; -Record.prototype.__iterator = function __iterator(type, reverse) { - return recordSeq(this).__iterator(type, reverse); -}; -Record.prototype.__iterate = function __iterate(fn, reverse) { - return recordSeq(this).__iterate(fn, reverse); -}; -Record.prototype.__ensureOwner = function __ensureOwner(ownerID) { - if (ownerID === this.__ownerID) { - return this; - } - var newValues = this._values.__ensureOwner(ownerID); - if (!ownerID) { - this.__ownerID = ownerID; - this._values = newValues; - return this; - } - return makeRecord(this, newValues, ownerID); -}; -Record.isRecord = isRecord; -Record.getDescriptiveName = recordName; -var RecordPrototype = Record.prototype; -RecordPrototype[IS_RECORD_SYMBOL] = true; -RecordPrototype[DELETE] = RecordPrototype.remove; -RecordPrototype.deleteIn = RecordPrototype.removeIn = deleteIn; -RecordPrototype.getIn = getIn$1; -RecordPrototype.hasIn = CollectionPrototype.hasIn; -RecordPrototype.merge = merge; -RecordPrototype.mergeWith = mergeWith; -RecordPrototype.mergeIn = mergeIn; -RecordPrototype.mergeDeep = mergeDeep$1; -RecordPrototype.mergeDeepWith = mergeDeepWith$1; -RecordPrototype.mergeDeepIn = mergeDeepIn; -RecordPrototype.setIn = setIn$1; -RecordPrototype.update = update$1; -RecordPrototype.updateIn = updateIn$1; -RecordPrototype.withMutations = withMutations; -RecordPrototype.asMutable = asMutable; -RecordPrototype.asImmutable = asImmutable; -RecordPrototype[ITERATOR_SYMBOL] = RecordPrototype.entries; -RecordPrototype.toJSON = RecordPrototype.toObject = - CollectionPrototype.toObject; -RecordPrototype.inspect = RecordPrototype.toSource = function () { - return this.toString(); -}; -function makeRecord(likeRecord, values, ownerID) { - var record = Object.create(Object.getPrototypeOf(likeRecord)); - record._values = values; - record.__ownerID = ownerID; - return record; -} -function recordName(record) { - return record.constructor.displayName || record.constructor.name || 'Record'; -} -function recordSeq(record) { - return keyedSeqFromValue(record._keys.map(function (k) { return [k, record.get(k)]; })); -} -function setProp(prototype, name) { - try { - Object.defineProperty(prototype, name, { - get: function () { - return this.get(name); - }, - set: function (value) { - invariant(this.__ownerID, 'Cannot set on an immutable record.'); - this.set(name, value); - }, - }); - } - catch (error) { - // Object.defineProperty failed. Probably IE8. - } -} -/** - * Returns a lazy Seq of `value` repeated `times` times. When `times` is - * undefined, returns an infinite sequence of `value`. - */ -var Repeat = /*@__PURE__*/ (function (IndexedSeq$$1) { - function Repeat(value, times) { - if (!(this instanceof Repeat)) { - return new Repeat(value, times); - } - this._value = value; - this.size = times === undefined ? Infinity : Math.max(0, times); - if (this.size === 0) { - if (EMPTY_REPEAT) { - return EMPTY_REPEAT; - } - EMPTY_REPEAT = this; - } - } - if (IndexedSeq$$1) - Repeat.__proto__ = IndexedSeq$$1; - Repeat.prototype = Object.create(IndexedSeq$$1 && IndexedSeq$$1.prototype); - Repeat.prototype.constructor = Repeat; - Repeat.prototype.toString = function toString() { - if (this.size === 0) { - return 'Repeat []'; - } - return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]'; - }; - Repeat.prototype.get = function get(index, notSetValue) { - return this.has(index) ? this._value : notSetValue; - }; - Repeat.prototype.includes = function includes(searchValue) { - return is(this._value, searchValue); - }; - Repeat.prototype.slice = function slice(begin, end) { - var size = this.size; - return wholeSlice(begin, end, size) - ? this - : new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size)); - }; - Repeat.prototype.reverse = function reverse() { - return this; - }; - Repeat.prototype.indexOf = function indexOf(searchValue) { - if (is(this._value, searchValue)) { - return 0; - } - return -1; - }; - Repeat.prototype.lastIndexOf = function lastIndexOf(searchValue) { - if (is(this._value, searchValue)) { - return this.size; - } - return -1; - }; - Repeat.prototype.__iterate = function __iterate(fn, reverse) { - var size = this.size; - var i = 0; - while (i !== size) { - if (fn(this._value, reverse ? size - ++i : i++, this) === false) { - break; - } - } - return i; - }; - Repeat.prototype.__iterator = function __iterator(type, reverse) { - var this$1 = this; - var size = this.size; - var i = 0; - return new Iterator(function () { - return i === size - ? iteratorDone() - : iteratorValue(type, reverse ? size - ++i : i++, this$1._value); - }); - }; - Repeat.prototype.equals = function equals(other) { - return other instanceof Repeat - ? is(this._value, other._value) - : deepEqual(other); - }; - return Repeat; -}(IndexedSeq)); -var EMPTY_REPEAT; -function fromJS(value, converter) { - return fromJSWith([], converter || defaultConverter, value, '', converter && converter.length > 2 ? [] : undefined, { '': value }); -} -function fromJSWith(stack, converter, value, key, keyPath, parentValue) { - var toSeq = Array.isArray(value) - ? IndexedSeq - : isPlainObj(value) - ? KeyedSeq - : null; - if (toSeq) { - if (~stack.indexOf(value)) { - throw new TypeError('Cannot convert circular structure to Immutable'); - } - stack.push(value); - keyPath && key !== '' && keyPath.push(key); - var converted = converter.call(parentValue, key, toSeq(value).map(function (v, k) { return fromJSWith(stack, converter, v, k, keyPath, value); }), keyPath && keyPath.slice()); - stack.pop(); - keyPath && keyPath.pop(); - return converted; - } - return value; -} -function defaultConverter(k, v) { - return isKeyed(v) ? v.toMap() : v.toList(); -} -var version$1 = "4.0.0-rc.11"; -var Immutable = { - version: version$1, - Collection: Collection, - // Note: Iterable is deprecated - Iterable: Collection, - Seq: Seq, - Map: Map$1, - OrderedMap: OrderedMap, - List: List, - Stack: Stack, - Set: Set$1, - OrderedSet: OrderedSet, - Record: Record, - Range: Range, - Repeat: Repeat, - is: is, - fromJS: fromJS, - hash: hash, - isImmutable: isImmutable, - isCollection: isCollection, - isKeyed: isKeyed, - isIndexed: isIndexed, - isAssociative: isAssociative, - isOrdered: isOrdered, - isValueObject: isValueObject, - isSeq: isSeq, - isList: isList, - isMap: isMap, - isOrderedMap: isOrderedMap, - isStack: isStack, - isSet: isSet, - isOrderedSet: isOrderedSet, - isRecord: isRecord, - get: get, - getIn: getIn, - has: has, - hasIn: hasIn, - merge: merge$1, - mergeDeep: mergeDeep, - mergeWith: mergeWith$1, - mergeDeepWith: mergeDeepWith, - remove: remove, - removeIn: removeIn, - set: set, - setIn: setIn, - update: update, - updateIn: updateIn, -}; - -var OptionTypes; -(function (OptionTypes) { - OptionTypes[OptionTypes["IGNORED_LABELS"] = 0] = "IGNORED_LABELS"; - OptionTypes[OptionTypes["ACCESSED_NODES"] = 1] = "ACCESSED_NODES"; - OptionTypes[OptionTypes["ASSIGNED_NODES"] = 2] = "ASSIGNED_NODES"; - OptionTypes[OptionTypes["IGNORE_BREAK_STATEMENTS"] = 3] = "IGNORE_BREAK_STATEMENTS"; - OptionTypes[OptionTypes["IGNORE_RETURN_AWAIT_YIELD"] = 4] = "IGNORE_RETURN_AWAIT_YIELD"; - OptionTypes[OptionTypes["NODES_CALLED_AT_PATH_WITH_OPTIONS"] = 5] = "NODES_CALLED_AT_PATH_WITH_OPTIONS"; - OptionTypes[OptionTypes["REPLACED_VARIABLE_INITS"] = 6] = "REPLACED_VARIABLE_INITS"; - OptionTypes[OptionTypes["RETURN_EXPRESSIONS_ACCESSED_AT_PATH"] = 7] = "RETURN_EXPRESSIONS_ACCESSED_AT_PATH"; - OptionTypes[OptionTypes["RETURN_EXPRESSIONS_ASSIGNED_AT_PATH"] = 8] = "RETURN_EXPRESSIONS_ASSIGNED_AT_PATH"; - OptionTypes[OptionTypes["RETURN_EXPRESSIONS_CALLED_AT_PATH"] = 9] = "RETURN_EXPRESSIONS_CALLED_AT_PATH"; -})(OptionTypes || (OptionTypes = {})); -const RESULT_KEY = {}; -class ExecutionPathOptions { - static create() { - return new this(Immutable.Map()); - } - constructor(optionValues) { - this.optionValues = optionValues; - } - addAccessedNodeAtPath(path, node) { - return this.setIn([OptionTypes.ACCESSED_NODES, node, ...path, RESULT_KEY], true); - } - addAccessedReturnExpressionAtPath(path, callExpression) { - return this.setIn([OptionTypes.RETURN_EXPRESSIONS_ACCESSED_AT_PATH, callExpression, ...path, RESULT_KEY], true); - } - addAssignedNodeAtPath(path, node) { - return this.setIn([OptionTypes.ASSIGNED_NODES, node, ...path, RESULT_KEY], true); - } - addAssignedReturnExpressionAtPath(path, callExpression) { - return this.setIn([OptionTypes.RETURN_EXPRESSIONS_ASSIGNED_AT_PATH, callExpression, ...path, RESULT_KEY], true); - } - addCalledNodeAtPathWithOptions(path, node, callOptions) { - return this.setIn([OptionTypes.NODES_CALLED_AT_PATH_WITH_OPTIONS, node, ...path, RESULT_KEY, callOptions], true); - } - addCalledReturnExpressionAtPath(path, callExpression) { - return this.setIn([OptionTypes.RETURN_EXPRESSIONS_CALLED_AT_PATH, callExpression, ...path, RESULT_KEY], true); - } - getHasEffectsWhenCalledOptions() { - return this.setIgnoreReturnAwaitYield() - .setIgnoreBreakStatements(false) - .setIgnoreNoLabels(); - } - getReplacedVariableInit(variable) { - return this.optionValues.getIn([OptionTypes.REPLACED_VARIABLE_INITS, variable]); - } - hasNodeBeenAccessedAtPath(path, node) { - return this.optionValues.getIn([OptionTypes.ACCESSED_NODES, node, ...path, RESULT_KEY]); - } - hasNodeBeenAssignedAtPath(path, node) { - return this.optionValues.getIn([OptionTypes.ASSIGNED_NODES, node, ...path, RESULT_KEY]); - } - hasNodeBeenCalledAtPathWithOptions(path, node, callOptions) { - const previousCallOptions = this.optionValues.getIn([ - OptionTypes.NODES_CALLED_AT_PATH_WITH_OPTIONS, - node, - ...path, - RESULT_KEY - ]); - return (previousCallOptions && - previousCallOptions.find((_, otherCallOptions) => otherCallOptions.equals(callOptions))); - } - hasReturnExpressionBeenAccessedAtPath(path, callExpression) { - return this.optionValues.getIn([ - OptionTypes.RETURN_EXPRESSIONS_ACCESSED_AT_PATH, - callExpression, - ...path, - RESULT_KEY - ]); - } - hasReturnExpressionBeenAssignedAtPath(path, callExpression) { - return this.optionValues.getIn([ - OptionTypes.RETURN_EXPRESSIONS_ASSIGNED_AT_PATH, - callExpression, - ...path, - RESULT_KEY - ]); - } - hasReturnExpressionBeenCalledAtPath(path, callExpression) { - return this.optionValues.getIn([ - OptionTypes.RETURN_EXPRESSIONS_CALLED_AT_PATH, - callExpression, - ...path, - RESULT_KEY - ]); - } - ignoreBreakStatements() { - return this.get(OptionTypes.IGNORE_BREAK_STATEMENTS); - } - ignoreLabel(labelName) { - return this.optionValues.getIn([OptionTypes.IGNORED_LABELS, labelName]); - } - ignoreReturnAwaitYield() { - return this.get(OptionTypes.IGNORE_RETURN_AWAIT_YIELD); - } - replaceVariableInit(variable, init) { - return this.setIn([OptionTypes.REPLACED_VARIABLE_INITS, variable], init); - } - setIgnoreBreakStatements(value = true) { - return this.set(OptionTypes.IGNORE_BREAK_STATEMENTS, value); - } - setIgnoreLabel(labelName) { - return this.setIn([OptionTypes.IGNORED_LABELS, labelName], true); - } - setIgnoreNoLabels() { - return this.remove(OptionTypes.IGNORED_LABELS); - } - setIgnoreReturnAwaitYield(value = true) { - return this.set(OptionTypes.IGNORE_RETURN_AWAIT_YIELD, value); - } - get(option) { - return this.optionValues.get(option); - } - remove(option) { - return new ExecutionPathOptions(this.optionValues.remove(option)); - } - set(option, value) { - return new ExecutionPathOptions(this.optionValues.set(option, value)); - } - setIn(optionPath, value) { - return new ExecutionPathOptions(this.optionValues.setIn(optionPath, value)); - } -} - const keys = { Literal: [], Program: ['body'] }; function getAndCreateKeys(esTreeNode) { keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object'); return keys[esTreeNode.type]; } const INCLUDE_PARAMETERS = 'variables'; -const NEW_EXECUTION_PATH = ExecutionPathOptions.create(); class NodeBase { constructor(esTreeNode, parent, parentScope) { this.included = false; this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode); this.parent = parent; @@ -7995,64 +3171,64 @@ declare(_kind, _init) { return []; } deoptimizePath(_path) { } getLiteralValueAtPath(_path, _recursionTracker, _origin) { - return UNKNOWN_VALUE; + return UnknownValue; } getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) { return UNKNOWN_EXPRESSION; } - hasEffects(options) { + hasEffects(context) { for (const key of this.keys) { const value = this[key]; if (value === null || key === 'annotations') continue; if (Array.isArray(value)) { for (const child of value) { - if (child !== null && child.hasEffects(options)) + if (child !== null && child.hasEffects(context)) return true; } } - else if (value.hasEffects(options)) + else if (value.hasEffects(context)) return true; } return false; } - hasEffectsWhenAccessedAtPath(path, _options) { + hasEffectsWhenAccessedAtPath(path, _context) { return path.length > 0; } - hasEffectsWhenAssignedAtPath(_path, _options) { + hasEffectsWhenAssignedAtPath(_path, _context) { return true; } - hasEffectsWhenCalledAtPath(_path, _callOptions, _options) { + hasEffectsWhenCalledAtPath(_path, _callOptions, _context) { return true; } - include(includeChildrenRecursively) { + include(context, includeChildrenRecursively) { this.included = true; for (const key of this.keys) { const value = this[key]; if (value === null || key === 'annotations') continue; if (Array.isArray(value)) { for (const child of value) { if (child !== null) - child.include(includeChildrenRecursively); + child.include(context, includeChildrenRecursively); } } else { - value.include(includeChildrenRecursively); + value.include(context, includeChildrenRecursively); } } } - includeCallArguments(args) { + includeCallArguments(context, args) { for (const arg of args) { - arg.include(false); + arg.include(context, false); } } - includeWithAllDeclaredVariables(includeChildrenRecursively) { - this.include(includeChildrenRecursively); + includeWithAllDeclaredVariables(includeChildrenRecursively, context) { + this.include(context, includeChildrenRecursively); } /** * Override to perform special initialisation steps after the scope is initialised */ initialise() { } @@ -8106,32 +3282,34 @@ else { value.render(code, options); } } } - shouldBeIncluded() { - return this.included || this.hasEffects(NEW_EXECUTION_PATH); + shouldBeIncluded(context) { + return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext())); } toString() { return this.context.code.slice(this.start, this.end); } } class ClassNode extends NodeBase { createScope(parentScope) { this.scope = new ChildScope(parentScope); } - hasEffectsWhenAccessedAtPath(path, _options) { + hasEffectsWhenAccessedAtPath(path) { return path.length > 1; } - hasEffectsWhenAssignedAtPath(path, _options) { + hasEffectsWhenAssignedAtPath(path) { return path.length > 1; } - hasEffectsWhenCalledAtPath(path, callOptions, options) { - return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, options) || + hasEffectsWhenCalledAtPath(path, callOptions, context) { + if (!callOptions.withNew) + return true; + return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, context) || (this.superClass !== null && - this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, options))); + this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, context))); } initialise() { if (this.id !== null) { this.id.declare('class', this); } @@ -8177,28 +3355,28 @@ class ThisVariable extends LocalVariable { constructor(context) { super('this', null, null, context); } - _getInit(options) { - return options.getReplacedVariableInit(this) || UNKNOWN_EXPRESSION; - } getLiteralValueAtPath() { - return UNKNOWN_VALUE; + return UnknownValue; } - hasEffectsWhenAccessedAtPath(path, options) { - return (this._getInit(options).hasEffectsWhenAccessedAtPath(path, options) || - super.hasEffectsWhenAccessedAtPath(path, options)); + hasEffectsWhenAccessedAtPath(path, context) { + return (this.getInit(context).hasEffectsWhenAccessedAtPath(path, context) || + super.hasEffectsWhenAccessedAtPath(path, context)); } - hasEffectsWhenAssignedAtPath(path, options) { - return (this._getInit(options).hasEffectsWhenAssignedAtPath(path, options) || - super.hasEffectsWhenAssignedAtPath(path, options)); + hasEffectsWhenAssignedAtPath(path, context) { + return (this.getInit(context).hasEffectsWhenAssignedAtPath(path, context) || + super.hasEffectsWhenAssignedAtPath(path, context)); } - hasEffectsWhenCalledAtPath(path, callOptions, options) { - return (this._getInit(options).hasEffectsWhenCalledAtPath(path, callOptions, options) || - super.hasEffectsWhenCalledAtPath(path, callOptions, options)); + hasEffectsWhenCalledAtPath(path, callOptions, context) { + return (this.getInit(context).hasEffectsWhenCalledAtPath(path, callOptions, context) || + super.hasEffectsWhenCalledAtPath(path, callOptions, context)); } + getInit(context) { + return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION; + } } class ParameterScope extends ChildScope { constructor(parent, context) { super(parent); @@ -8230,11 +3408,11 @@ parameter.alwaysRendered = true; } } this.hasRest = hasRest; } - includeCallArguments(args) { + includeCallArguments(context, args) { let calledFromTryStatement = false; let argIncluded = false; const restParam = this.hasRest && this.parameters[this.parameters.length - 1]; for (let index = args.length - 1; index >= 0; index--) { const paramVars = this.parameters[index] || restParam; @@ -8248,15 +3426,15 @@ if (variable.calledFromTryStatement) { calledFromTryStatement = true; } } } - if (!argIncluded && arg.shouldBeIncluded()) { + if (!argIncluded && arg.shouldBeIncluded(context)) { argIncluded = true; } if (argIncluded) { - arg.include(calledFromTryStatement); + arg.include(context, calledFromTryStatement); } } } } @@ -8294,19 +3472,16 @@ this.variables.set('this', (this.thisVariable = new ThisVariable(context))); } findLexicalBoundary() { return this; } - getOptionsWhenCalledWith({ withNew }, options) { - return options.replaceVariableInit(this.thisVariable, withNew ? new UnknownObjectExpression() : UNKNOWN_EXPRESSION); - } - includeCallArguments(args) { - super.includeCallArguments(args); + includeCallArguments(context, args) { + super.includeCallArguments(context, args); if (this.argumentsVariable.included) { for (const arg of args) { if (!arg.included) { - arg.include(false); + arg.include(context, false); } } } } } @@ -8323,22 +3498,903 @@ 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 `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 }` - case 'ExportSpecifier': return node === parent.local; + // 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 BLANK = Object.create(null); + +const ValueProperties = Symbol('Value Properties'); +const PURE = { pure: true }; +const IMPURE = { pure: false }; +// We use shortened variables to reduce file size here +/* OBJECT */ +const O = { + // @ts-ignore + __proto__: null, + [ValueProperties]: IMPURE +}; +/* PURE FUNCTION */ +const PF = { + // @ts-ignore + __proto__: null, + [ValueProperties]: PURE +}; +/* CONSTRUCTOR */ +const C = { + // @ts-ignore + __proto__: null, + [ValueProperties]: IMPURE, + prototype: O +}; +/* PURE CONSTRUCTOR */ +const PC = { + // @ts-ignore + __proto__: null, + [ValueProperties]: PURE, + prototype: O +}; +const ARRAY_TYPE = { + // @ts-ignore + __proto__: null, + [ValueProperties]: PURE, + from: PF, + of: PF, + prototype: O +}; +const INTL_MEMBER = { + // @ts-ignore + __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 + // @ts-ignore + __proto__: null, + [ValueProperties]: IMPURE, + Array: { + // @ts-ignore + __proto__: null, + [ValueProperties]: IMPURE, + from: PF, + isArray: PF, + of: PF, + prototype: O + }, + ArrayBuffer: { + // @ts-ignore + __proto__: null, + [ValueProperties]: PURE, + isView: PF, + prototype: O + }, + Atomics: O, + BigInt: C, + BigInt64Array: C, + BigUint64Array: C, + Boolean: PC, + // @ts-ignore + constructor: C, + DataView: PC, + Date: { + // @ts-ignore + __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, + // @ts-ignore + hasOwnProperty: O, + Infinity: O, + Int16Array: ARRAY_TYPE, + Int32Array: ARRAY_TYPE, + Int8Array: ARRAY_TYPE, + isFinite: PF, + isNaN: PF, + // @ts-ignore + isPrototypeOf: O, + JSON: O, + Map: PC, + Math: { + // @ts-ignore + __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: { + // @ts-ignore + __proto__: null, + [ValueProperties]: PURE, + isFinite: PF, + isInteger: PF, + isNaN: PF, + isSafeInteger: PF, + parseFloat: PF, + parseInt: PF, + prototype: O + }, + Object: { + // @ts-ignore + __proto__: null, + [ValueProperties]: PURE, + create: PF, + getNotifier: PF, + getOwn: PF, + getOwnPropertyDescriptor: PF, + getOwnPropertyNames: PF, + getOwnPropertySymbols: PF, + getPrototypeOf: PF, + is: PF, + isExtensible: PF, + isFrozen: PF, + isSealed: PF, + keys: PF, + prototype: O + }, + parseFloat: PF, + parseInt: PF, + Promise: { + // @ts-ignore + __proto__: null, + [ValueProperties]: IMPURE, + all: PF, + prototype: O, + race: PF, + resolve: PF + }, + // @ts-ignore + propertyIsEnumerable: O, + Proxy: O, + RangeError: PC, + ReferenceError: PC, + Reflect: O, + RegExp: PC, + Set: PC, + SharedArrayBuffer: C, + String: { + // @ts-ignore + __proto__: null, + [ValueProperties]: PURE, + fromCharCode: PF, + fromCodePoint: PF, + prototype: O, + raw: PF + }, + Symbol: { + // @ts-ignore + __proto__: null, + [ValueProperties]: PURE, + for: PF, + keyFor: PF, + prototype: O + }, + SyntaxError: PC, + // @ts-ignore + toLocaleString: O, + // @ts-ignore + 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, + // @ts-ignore + valueOf: O, + WeakMap: PC, + WeakSet: PC, + // Additional globals shared by Node and Browser that are not strictly part of the language + clearInterval: C, + clearTimeout: C, + console: O, + Intl: { + // @ts-ignore + __proto__: null, + [ValueProperties]: IMPURE, + Collator: INTL_MEMBER, + DateTimeFormat: INTL_MEMBER, + ListFormat: INTL_MEMBER, + NumberFormat: INTL_MEMBER, + PluralRules: INTL_MEMBER, + RelativeTimeFormat: INTL_MEMBER + }, + setInterval: C, + setTimeout: C, + TextDecoder: C, + TextEncoder: C, + URL: C, + URLSearchParams: C, + // Browser specific globals + AbortController: C, + AbortSignal: C, + addEventListener: O, + alert: O, + AnalyserNode: C, + Animation: C, + AnimationEvent: C, + applicationCache: O, + ApplicationCache: C, + ApplicationCacheErrorEvent: C, + atob: O, + Attr: C, + Audio: C, + AudioBuffer: C, + AudioBufferSourceNode: C, + AudioContext: C, + AudioDestinationNode: C, + AudioListener: C, + AudioNode: C, + AudioParam: C, + AudioProcessingEvent: C, + AudioScheduledSourceNode: C, + AudioWorkletNode: C, + BarProp: C, + BaseAudioContext: C, + BatteryManager: C, + BeforeUnloadEvent: C, + BiquadFilterNode: C, + Blob: C, + BlobEvent: C, + blur: O, + BroadcastChannel: C, + btoa: O, + ByteLengthQueuingStrategy: C, + Cache: C, + caches: O, + CacheStorage: C, + cancelAnimationFrame: O, + cancelIdleCallback: O, + CanvasCaptureMediaStreamTrack: C, + CanvasGradient: C, + CanvasPattern: C, + CanvasRenderingContext2D: C, + ChannelMergerNode: C, + ChannelSplitterNode: C, + CharacterData: C, + clientInformation: O, + ClipboardEvent: C, + close: O, + closed: O, + CloseEvent: C, + Comment: C, + CompositionEvent: C, + confirm: O, + ConstantSourceNode: C, + ConvolverNode: C, + CountQueuingStrategy: C, + createImageBitmap: O, + Credential: C, + CredentialsContainer: C, + crypto: O, + Crypto: C, + CryptoKey: C, + CSS: C, + CSSConditionRule: C, + CSSFontFaceRule: C, + CSSGroupingRule: C, + CSSImportRule: C, + CSSKeyframeRule: C, + CSSKeyframesRule: C, + CSSMediaRule: C, + CSSNamespaceRule: C, + CSSPageRule: C, + CSSRule: C, + CSSRuleList: C, + CSSStyleDeclaration: C, + CSSStyleRule: C, + CSSStyleSheet: C, + CSSSupportsRule: C, + CustomElementRegistry: C, + customElements: O, + CustomEvent: C, + DataTransfer: C, + DataTransferItem: C, + DataTransferItemList: C, + defaultstatus: O, + defaultStatus: O, + DelayNode: C, + DeviceMotionEvent: C, + DeviceOrientationEvent: C, + devicePixelRatio: O, + dispatchEvent: O, + document: O, + Document: C, + DocumentFragment: C, + DocumentType: C, + DOMError: C, + DOMException: C, + DOMImplementation: C, + DOMMatrix: C, + DOMMatrixReadOnly: C, + DOMParser: C, + DOMPoint: C, + DOMPointReadOnly: C, + DOMQuad: C, + DOMRect: C, + DOMRectReadOnly: C, + DOMStringList: C, + DOMStringMap: C, + DOMTokenList: C, + DragEvent: C, + DynamicsCompressorNode: C, + Element: C, + ErrorEvent: C, + Event: C, + EventSource: C, + EventTarget: C, + external: O, + fetch: O, + File: C, + FileList: C, + FileReader: C, + find: O, + focus: O, + FocusEvent: C, + FontFace: C, + FontFaceSetLoadEvent: C, + FormData: C, + frames: O, + GainNode: C, + Gamepad: C, + GamepadButton: C, + GamepadEvent: C, + getComputedStyle: O, + getSelection: O, + HashChangeEvent: C, + Headers: C, + history: O, + History: C, + HTMLAllCollection: C, + HTMLAnchorElement: C, + HTMLAreaElement: C, + HTMLAudioElement: C, + HTMLBaseElement: C, + HTMLBodyElement: C, + HTMLBRElement: C, + HTMLButtonElement: C, + HTMLCanvasElement: C, + HTMLCollection: C, + HTMLContentElement: C, + HTMLDataElement: C, + HTMLDataListElement: C, + HTMLDetailsElement: C, + HTMLDialogElement: C, + HTMLDirectoryElement: C, + HTMLDivElement: C, + HTMLDListElement: C, + HTMLDocument: C, + HTMLElement: C, + HTMLEmbedElement: C, + HTMLFieldSetElement: C, + HTMLFontElement: C, + HTMLFormControlsCollection: C, + HTMLFormElement: C, + HTMLFrameElement: C, + HTMLFrameSetElement: C, + HTMLHeadElement: C, + HTMLHeadingElement: C, + HTMLHRElement: C, + HTMLHtmlElement: C, + HTMLIFrameElement: C, + HTMLImageElement: C, + HTMLInputElement: C, + HTMLLabelElement: C, + HTMLLegendElement: C, + HTMLLIElement: C, + HTMLLinkElement: C, + HTMLMapElement: C, + HTMLMarqueeElement: C, + HTMLMediaElement: C, + HTMLMenuElement: C, + HTMLMetaElement: C, + HTMLMeterElement: C, + HTMLModElement: C, + HTMLObjectElement: C, + HTMLOListElement: C, + HTMLOptGroupElement: C, + HTMLOptionElement: C, + HTMLOptionsCollection: C, + HTMLOutputElement: C, + HTMLParagraphElement: C, + HTMLParamElement: C, + HTMLPictureElement: C, + HTMLPreElement: C, + HTMLProgressElement: C, + HTMLQuoteElement: C, + HTMLScriptElement: C, + HTMLSelectElement: C, + HTMLShadowElement: C, + HTMLSlotElement: C, + HTMLSourceElement: C, + HTMLSpanElement: C, + HTMLStyleElement: C, + HTMLTableCaptionElement: C, + HTMLTableCellElement: C, + HTMLTableColElement: C, + HTMLTableElement: C, + HTMLTableRowElement: C, + HTMLTableSectionElement: C, + HTMLTemplateElement: C, + HTMLTextAreaElement: C, + HTMLTimeElement: C, + HTMLTitleElement: C, + HTMLTrackElement: C, + HTMLUListElement: C, + HTMLUnknownElement: C, + HTMLVideoElement: C, + IDBCursor: C, + IDBCursorWithValue: C, + IDBDatabase: C, + IDBFactory: C, + IDBIndex: C, + IDBKeyRange: C, + IDBObjectStore: C, + IDBOpenDBRequest: C, + IDBRequest: C, + IDBTransaction: C, + IDBVersionChangeEvent: C, + IdleDeadline: C, + IIRFilterNode: C, + Image: C, + ImageBitmap: C, + ImageBitmapRenderingContext: C, + ImageCapture: C, + ImageData: C, + indexedDB: O, + innerHeight: O, + innerWidth: O, + InputEvent: C, + IntersectionObserver: C, + IntersectionObserverEntry: C, + isSecureContext: O, + KeyboardEvent: C, + KeyframeEffect: C, + length: O, + localStorage: O, + location: O, + Location: C, + locationbar: O, + matchMedia: O, + MediaDeviceInfo: C, + MediaDevices: C, + MediaElementAudioSourceNode: C, + MediaEncryptedEvent: C, + MediaError: C, + MediaKeyMessageEvent: C, + MediaKeySession: C, + MediaKeyStatusMap: C, + MediaKeySystemAccess: C, + MediaList: C, + MediaQueryList: C, + MediaQueryListEvent: C, + MediaRecorder: C, + MediaSettingsRange: C, + MediaSource: C, + MediaStream: C, + MediaStreamAudioDestinationNode: C, + MediaStreamAudioSourceNode: C, + MediaStreamEvent: C, + MediaStreamTrack: C, + MediaStreamTrackEvent: C, + menubar: O, + MessageChannel: C, + MessageEvent: C, + MessagePort: C, + MIDIAccess: C, + MIDIConnectionEvent: C, + MIDIInput: C, + MIDIInputMap: C, + MIDIMessageEvent: C, + MIDIOutput: C, + MIDIOutputMap: C, + MIDIPort: C, + MimeType: C, + MimeTypeArray: C, + MouseEvent: C, + moveBy: O, + moveTo: O, + MutationEvent: C, + MutationObserver: C, + MutationRecord: C, + name: O, + NamedNodeMap: C, + NavigationPreloadManager: C, + navigator: O, + Navigator: C, + NetworkInformation: C, + Node: C, + NodeFilter: O, + NodeIterator: C, + NodeList: C, + Notification: C, + OfflineAudioCompletionEvent: C, + OfflineAudioContext: C, + offscreenBuffering: O, + OffscreenCanvas: C, + open: O, + openDatabase: O, + Option: C, + origin: O, + OscillatorNode: C, + outerHeight: O, + outerWidth: O, + PageTransitionEvent: C, + pageXOffset: O, + pageYOffset: O, + PannerNode: C, + parent: O, + Path2D: C, + PaymentAddress: C, + PaymentRequest: C, + PaymentRequestUpdateEvent: C, + PaymentResponse: C, + performance: O, + Performance: C, + PerformanceEntry: C, + PerformanceLongTaskTiming: C, + PerformanceMark: C, + PerformanceMeasure: C, + PerformanceNavigation: C, + PerformanceNavigationTiming: C, + PerformanceObserver: C, + PerformanceObserverEntryList: C, + PerformancePaintTiming: C, + PerformanceResourceTiming: C, + PerformanceTiming: C, + PeriodicWave: C, + Permissions: C, + PermissionStatus: C, + personalbar: O, + PhotoCapabilities: C, + Plugin: C, + PluginArray: C, + PointerEvent: C, + PopStateEvent: C, + postMessage: O, + Presentation: C, + PresentationAvailability: C, + PresentationConnection: C, + PresentationConnectionAvailableEvent: C, + PresentationConnectionCloseEvent: C, + PresentationConnectionList: C, + PresentationReceiver: C, + PresentationRequest: C, + print: O, + ProcessingInstruction: C, + ProgressEvent: C, + PromiseRejectionEvent: C, + prompt: O, + PushManager: C, + PushSubscription: C, + PushSubscriptionOptions: C, + queueMicrotask: O, + RadioNodeList: C, + Range: C, + ReadableStream: C, + RemotePlayback: C, + removeEventListener: O, + Request: C, + requestAnimationFrame: O, + requestIdleCallback: O, + resizeBy: O, + ResizeObserver: C, + ResizeObserverEntry: C, + resizeTo: O, + Response: C, + RTCCertificate: C, + RTCDataChannel: C, + RTCDataChannelEvent: C, + RTCDtlsTransport: C, + RTCIceCandidate: C, + RTCIceTransport: C, + RTCPeerConnection: C, + RTCPeerConnectionIceEvent: C, + RTCRtpReceiver: C, + RTCRtpSender: C, + RTCSctpTransport: C, + RTCSessionDescription: C, + RTCStatsReport: C, + RTCTrackEvent: C, + screen: O, + Screen: C, + screenLeft: O, + ScreenOrientation: C, + screenTop: O, + screenX: O, + screenY: O, + ScriptProcessorNode: C, + scroll: O, + scrollbars: O, + scrollBy: O, + scrollTo: O, + scrollX: O, + scrollY: O, + SecurityPolicyViolationEvent: C, + Selection: C, + ServiceWorker: C, + ServiceWorkerContainer: C, + ServiceWorkerRegistration: C, + sessionStorage: O, + ShadowRoot: C, + SharedWorker: C, + SourceBuffer: C, + SourceBufferList: C, + speechSynthesis: O, + SpeechSynthesisEvent: C, + SpeechSynthesisUtterance: C, + StaticRange: C, + status: O, + statusbar: O, + StereoPannerNode: C, + stop: O, + Storage: C, + StorageEvent: C, + StorageManager: C, + styleMedia: O, + StyleSheet: C, + StyleSheetList: C, + SubtleCrypto: C, + SVGAElement: C, + SVGAngle: C, + SVGAnimatedAngle: C, + SVGAnimatedBoolean: C, + SVGAnimatedEnumeration: C, + SVGAnimatedInteger: C, + SVGAnimatedLength: C, + SVGAnimatedLengthList: C, + SVGAnimatedNumber: C, + SVGAnimatedNumberList: C, + SVGAnimatedPreserveAspectRatio: C, + SVGAnimatedRect: C, + SVGAnimatedString: C, + SVGAnimatedTransformList: C, + SVGAnimateElement: C, + SVGAnimateMotionElement: C, + SVGAnimateTransformElement: C, + SVGAnimationElement: C, + SVGCircleElement: C, + SVGClipPathElement: C, + SVGComponentTransferFunctionElement: C, + SVGDefsElement: C, + SVGDescElement: C, + SVGDiscardElement: C, + SVGElement: C, + SVGEllipseElement: C, + SVGFEBlendElement: C, + SVGFEColorMatrixElement: C, + SVGFEComponentTransferElement: C, + SVGFECompositeElement: C, + SVGFEConvolveMatrixElement: C, + SVGFEDiffuseLightingElement: C, + SVGFEDisplacementMapElement: C, + SVGFEDistantLightElement: C, + SVGFEDropShadowElement: C, + SVGFEFloodElement: C, + SVGFEFuncAElement: C, + SVGFEFuncBElement: C, + SVGFEFuncGElement: C, + SVGFEFuncRElement: C, + SVGFEGaussianBlurElement: C, + SVGFEImageElement: C, + SVGFEMergeElement: C, + SVGFEMergeNodeElement: C, + SVGFEMorphologyElement: C, + SVGFEOffsetElement: C, + SVGFEPointLightElement: C, + SVGFESpecularLightingElement: C, + SVGFESpotLightElement: C, + SVGFETileElement: C, + SVGFETurbulenceElement: C, + SVGFilterElement: C, + SVGForeignObjectElement: C, + SVGGElement: C, + SVGGeometryElement: C, + SVGGradientElement: C, + SVGGraphicsElement: C, + SVGImageElement: C, + SVGLength: C, + SVGLengthList: C, + SVGLinearGradientElement: C, + SVGLineElement: C, + SVGMarkerElement: C, + SVGMaskElement: C, + SVGMatrix: C, + SVGMetadataElement: C, + SVGMPathElement: C, + SVGNumber: C, + SVGNumberList: C, + SVGPathElement: C, + SVGPatternElement: C, + SVGPoint: C, + SVGPointList: C, + SVGPolygonElement: C, + SVGPolylineElement: C, + SVGPreserveAspectRatio: C, + SVGRadialGradientElement: C, + SVGRect: C, + SVGRectElement: C, + SVGScriptElement: C, + SVGSetElement: C, + SVGStopElement: C, + SVGStringList: C, + SVGStyleElement: C, + SVGSVGElement: C, + SVGSwitchElement: C, + SVGSymbolElement: C, + SVGTextContentElement: C, + SVGTextElement: C, + SVGTextPathElement: C, + SVGTextPositioningElement: C, + SVGTitleElement: C, + SVGTransform: C, + SVGTransformList: C, + SVGTSpanElement: C, + SVGUnitTypes: C, + SVGUseElement: C, + SVGViewElement: C, + TaskAttributionTiming: C, + Text: C, + TextEvent: C, + TextMetrics: C, + TextTrack: C, + TextTrackCue: C, + TextTrackCueList: C, + TextTrackList: C, + TimeRanges: C, + toolbar: O, + top: O, + Touch: C, + TouchEvent: C, + TouchList: C, + TrackEvent: C, + TransitionEvent: C, + TreeWalker: C, + UIEvent: C, + ValidityState: C, + visualViewport: O, + VisualViewport: C, + VTTCue: C, + WaveShaperNode: C, + WebAssembly: O, + WebGL2RenderingContext: C, + WebGLActiveInfo: C, + WebGLBuffer: C, + WebGLContextEvent: C, + WebGLFramebuffer: C, + WebGLProgram: C, + WebGLQuery: C, + WebGLRenderbuffer: C, + WebGLRenderingContext: C, + WebGLSampler: C, + WebGLShader: C, + WebGLShaderPrecisionFormat: C, + WebGLSync: C, + WebGLTexture: C, + WebGLTransformFeedback: C, + WebGLUniformLocation: C, + WebGLVertexArrayObject: C, + WebSocket: C, + WheelEvent: C, + Window: C, + Worker: C, + WritableStream: C, + XMLDocument: C, + XMLHttpRequest: C, + XMLHttpRequestEventTarget: C, + XMLHttpRequestUpload: C, + XMLSerializer: C, + XPathEvaluator: C, + XPathExpression: C, + XPathResult: C, + XSLTProcessor: C +}; +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]; +} +function isPureGlobal(path) { + const globalAtPath = getGlobalAtPath(path); + return globalAtPath !== null && globalAtPath.pure; +} +function isGlobalMember(path) { + if (path.length === 1) { + return path[0] === 'undefined' || getGlobalAtPath(path) !== null; + } + return getGlobalAtPath(path.slice(0, -1)) !== null; +} + +class GlobalVariable extends Variable { + hasEffectsWhenAccessedAtPath(path) { + return !isGlobalMember([this.name, ...path]); + } + hasEffectsWhenCalledAtPath(path) { + return !isPureGlobal([this.name, ...path]); + } +} + class Identifier$1 extends NodeBase { constructor() { super(...arguments); this.variable = null; this.bound = false; @@ -8364,75 +4420,72 @@ } declare(kind, init) { let variable; switch (kind) { case 'var': - case 'function': variable = this.scope.addDeclaration(this, this.context, init, true); break; + case 'function': + variable = this.scope.addDeclaration(this, this.context, init, 'function'); + 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: - throw new Error(`Unexpected identifier kind ${kind}.`); + /* istanbul ignore next */ + throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`); } return [(this.variable = variable)]; } deoptimizePath(path) { if (!this.bound) this.bind(); - if (this.variable !== null) { - if (path.length === 0 && - this.name in this.context.importDescriptions && - !this.scope.contains(this.name)) { - this.disallowImportReassignment(); - } - this.variable.deoptimizePath(path); + if (path.length === 0 && !this.scope.contains(this.name)) { + this.disallowImportReassignment(); } + this.variable.deoptimizePath(path); } getLiteralValueAtPath(path, recursionTracker, origin) { if (!this.bound) this.bind(); - if (this.variable !== null) { - return this.variable.getLiteralValueAtPath(path, recursionTracker, origin); - } - return UNKNOWN_VALUE; + return this.variable.getLiteralValueAtPath(path, recursionTracker, origin); } getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) { if (!this.bound) this.bind(); - if (this.variable !== null) { - return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin); - } - return UNKNOWN_EXPRESSION; + return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin); } - hasEffectsWhenAccessedAtPath(path, options) { - return this.variable !== null && this.variable.hasEffectsWhenAccessedAtPath(path, options); + hasEffects() { + return (this.context.unknownGlobalSideEffects && + this.variable instanceof GlobalVariable && + this.variable.hasEffectsWhenAccessedAtPath(EMPTY_PATH)); } - hasEffectsWhenAssignedAtPath(path, options) { - return !this.variable || this.variable.hasEffectsWhenAssignedAtPath(path, options); + hasEffectsWhenAccessedAtPath(path, context) { + return this.variable !== null && this.variable.hasEffectsWhenAccessedAtPath(path, context); } - hasEffectsWhenCalledAtPath(path, callOptions, options) { - return !this.variable || this.variable.hasEffectsWhenCalledAtPath(path, callOptions, options); + hasEffectsWhenAssignedAtPath(path, context) { + return !this.variable || this.variable.hasEffectsWhenAssignedAtPath(path, context); } - include() { + hasEffectsWhenCalledAtPath(path, callOptions, context) { + return !this.variable || this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context); + } + include(context) { if (!this.included) { this.included = true; if (this.variable !== null) { - this.context.includeVariable(this.variable); + this.context.includeVariable(context, this.variable); } } } - includeCallArguments(args) { - if (this.variable) { - this.variable.includeCallArguments(args); - } + includeCallArguments(context, args) { + this.variable.includeCallArguments(context, args); } render(code, _options, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) { if (this.variable) { const name = this.variable.getName(); if (name !== this.name) { @@ -8469,22 +4522,22 @@ this.argument.addExportedVariables(variables); } bind() { super.bind(); if (this.declarationInit !== null) { - this.declarationInit.deoptimizePath([UNKNOWN_KEY, UNKNOWN_KEY]); + this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]); } } declare(kind, init) { this.declarationInit = init; return this.argument.declare(kind, UNKNOWN_EXPRESSION); } deoptimizePath(path) { path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH); } - hasEffectsWhenAssignedAtPath(path, options) { - return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options); + hasEffectsWhenAssignedAtPath(path, context) { + return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context); } } class FunctionNode extends NodeBase { constructor() { @@ -8497,62 +4550,80 @@ deoptimizePath(path) { if (path.length === 1) { if (path[0] === 'prototype') { this.isPrototypeDeoptimized = true; } - else if (path[0] === UNKNOWN_KEY) { + else if (path[0] === UnknownKey) { this.isPrototypeDeoptimized = true; // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track // which means the return expression needs to be reassigned as well this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH); } } } getReturnExpressionWhenCalledAtPath(path) { return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION; } - hasEffects(options) { - return this.id !== null && this.id.hasEffects(options); + hasEffects() { + return this.id !== null && this.id.hasEffects(); } hasEffectsWhenAccessedAtPath(path) { - if (path.length <= 1) { + if (path.length <= 1) return false; - } return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized; } hasEffectsWhenAssignedAtPath(path) { if (path.length <= 1) { return false; } return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized; } - hasEffectsWhenCalledAtPath(path, callOptions, options) { - if (path.length > 0) { + hasEffectsWhenCalledAtPath(path, callOptions, context) { + if (path.length > 0) return true; - } - const innerOptions = this.scope.getOptionsWhenCalledWith(callOptions, options); for (const param of this.params) { - if (param.hasEffects(innerOptions)) + if (param.hasEffects(context)) return true; } - return this.body.hasEffects(innerOptions); + const thisInit = context.replacedVariableInits.get(this.scope.thisVariable); + context.replacedVariableInits.set(this.scope.thisVariable, callOptions.withNew ? new UnknownObjectExpression() : UNKNOWN_EXPRESSION); + const { brokenFlow, ignore } = context; + context.ignore = { + breaks: false, + continues: false, + labels: new Set(), + returnAwaitYield: true + }; + if (this.body.hasEffects(context)) + return true; + context.brokenFlow = brokenFlow; + if (thisInit) { + context.replacedVariableInits.set(this.scope.thisVariable, thisInit); + } + else { + context.replacedVariableInits.delete(this.scope.thisVariable); + } + context.ignore = ignore; + return false; } - include(includeChildrenRecursively) { + include(context, includeChildrenRecursively) { this.included = true; - this.body.include(includeChildrenRecursively); - if (this.id) { - this.id.include(); - } + if (this.id) + this.id.include(context); const hasArguments = this.scope.argumentsVariable.included; for (const param of this.params) { if (!(param instanceof Identifier$1) || hasArguments) { - param.include(includeChildrenRecursively); + param.include(context, includeChildrenRecursively); } } + const { brokenFlow } = context; + context.brokenFlow = BROKEN_FLOW_NONE; + this.body.include(context, includeChildrenRecursively); + context.brokenFlow = brokenFlow; } - includeCallArguments(args) { - this.scope.includeCallArguments(args); + includeCallArguments(context, args) { + this.scope.includeCallArguments(context, args); } initialise() { if (this.id !== null) { this.id.declare('function', this); } @@ -8598,24 +4669,25 @@ return declarationEnd; } return declarationEnd + generatorStarPos + 1; } class ExportDefaultDeclaration extends NodeBase { - include(includeChildrenRecursively) { - super.include(includeChildrenRecursively); + include(context, includeChildrenRecursively) { + super.include(context, includeChildrenRecursively); if (includeChildrenRecursively) { - this.context.includeVariable(this.variable); + this.context.includeVariable(context, 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, { start, end } = BLANK) { + render(code, options, nodeRenderOptions) { + const { start, end } = nodeRenderOptions; const declarationStart = getDeclarationStart(code.original, this.start); if (this.declaration instanceof FunctionDeclaration) { this.renderNamedDeclaration(code, declarationStart, 'function', this.declaration.id === null, options); } else if (this.declaration instanceof ClassDeclaration) { @@ -8763,159 +4835,20 @@ super(MISSING_EXPORT_SHIM_VARIABLE); this.module = module; } } -const pureFunctions = [ - 'Array.isArray', - 'Error', - 'EvalError', - 'InternalError', - 'RangeError', - 'ReferenceError', - 'SyntaxError', - 'TypeError', - 'URIError', - 'isFinite', - 'isNaN', - 'parseFloat', - 'parseInt', - 'decodeURI', - 'decodeURIComponent', - 'encodeURI', - 'encodeURIComponent', - 'escape', - 'unescape', - 'Object', - 'Object.create', - 'Object.getNotifier', - 'Object.getOwn', - 'Object.getOwnPropertyDescriptor', - 'Object.getOwnPropertyNames', - 'Object.getOwnPropertySymbols', - 'Object.getPrototypeOf', - 'Object.is', - 'Object.isExtensible', - 'Object.isFrozen', - 'Object.isSealed', - 'Object.keys', - 'Boolean', - 'Number', - 'Number.isFinite', - 'Number.isInteger', - 'Number.isNaN', - 'Number.isSafeInteger', - 'Number.parseFloat', - 'Number.parseInt', - 'Symbol', - 'Symbol.for', - 'Symbol.keyFor', - 'Math.abs', - 'Math.acos', - 'Math.acosh', - 'Math.asin', - 'Math.asinh', - 'Math.atan', - 'Math.atan2', - 'Math.atanh', - 'Math.cbrt', - 'Math.ceil', - 'Math.clz32', - 'Math.cos', - 'Math.cosh', - 'Math.exp', - 'Math.expm1', - 'Math.floor', - 'Math.fround', - 'Math.hypot', - 'Math.imul', - 'Math.log', - 'Math.log10', - 'Math.log1p', - 'Math.log2', - 'Math.max', - 'Math.min', - 'Math.pow', - 'Math.random', - 'Math.round', - 'Math.sign', - 'Math.sin', - 'Math.sinh', - 'Math.sqrt', - 'Math.tan', - 'Math.tanh', - 'Math.trunc', - 'Date', - 'Date.UTC', - 'Date.now', - 'Date.parse', - 'String', - 'String.fromCharCode', - 'String.fromCodePoint', - 'String.raw', - 'RegExp', - 'Map', - 'Set', - 'WeakMap', - 'WeakSet', - 'ArrayBuffer', - 'ArrayBuffer.isView', - 'DataView', - 'Promise.all', - 'Promise.race', - 'Promise.resolve', - 'Intl.Collator', - 'Intl.Collator.supportedLocalesOf', - 'Intl.DateTimeFormat', - 'Intl.DateTimeFormat.supportedLocalesOf', - 'Intl.NumberFormat', - 'Intl.NumberFormat.supportedLocalesOf' -]; -const arrayTypes = 'Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split(' '); -for (const type of arrayTypes) { - pureFunctions.push(type, `${type}.from`, `${type}.of`); -} -const simdTypes = 'Int8x16 Int16x8 Int32x4 Float32x4 Float64x2'.split(' '); -const simdMethods = 'abs add and bool check div equal extractLane fromFloat32x4 fromFloat32x4Bits fromFloat64x2 fromFloat64x2Bits fromInt16x8Bits fromInt32x4 fromInt32x4Bits fromInt8x16Bits greaterThan greaterThanOrEqual lessThan lessThanOrEqual load max maxNum min minNum mul neg not notEqual or reciprocalApproximation reciprocalSqrtApproximation replaceLane select selectBits shiftLeftByScalar shiftRightArithmeticByScalar shiftRightLogicalByScalar shuffle splat sqrt store sub swizzle xor'.split(' '); -for (const type of simdTypes) { - const typeString = `SIMD.${type}`; - pureFunctions.push(typeString); - for (const method of simdMethods) { - pureFunctions.push(`${typeString}.${method}`); - } -} -// TODO add others to this list from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects -var pureFunctions$1 = new Set(pureFunctions); - -class GlobalVariable extends Variable { - hasEffectsWhenAccessedAtPath(path) { - // path.length == 0 can also have an effect but we postpone this for now - return (path.length > 0 && - !this.isPureFunctionMember(path) && - !(this.name === 'Reflect' && path.length === 1)); - } - hasEffectsWhenCalledAtPath(path) { - return !pureFunctions$1.has([this.name, ...path].join('.')); - } - isPureFunctionMember(path) { - return (pureFunctions$1.has([this.name, ...path].join('.')) || - (path.length >= 1 && pureFunctions$1.has([this.name, ...path.slice(0, -1)].join('.'))) || - (path.length >= 2 && - pureFunctions$1.has([this.name, ...path.slice(0, -2)].join('.')) && - path[path.length - 2] === 'prototype')); - } -} - class NamespaceVariable extends Variable { - constructor(context) { + constructor(context, syntheticNamedExports) { super(context.getModuleName()); this.memberVariables = Object.create(null); this.containsExternalNamespace = false; this.referencedEarly = false; this.references = []; this.context = context; this.module = context.module; + this.syntheticNamedExports = syntheticNamedExports; } addReference(identifier) { this.references.push(identifier); this.name = identifier.name; } @@ -8926,11 +4859,11 @@ deoptimizePath() { for (const key in this.memberVariables) { this.memberVariables[key].deoptimizePath(UNKNOWN_PATH); } } - include() { + include(context) { if (!this.included) { if (this.containsExternalNamespace) { this.context.error({ code: 'NAMESPACE_CANNOT_CONTAIN_EXTERNAL', id: this.module.id, @@ -8944,15 +4877,15 @@ break; } } if (this.context.preserveModules) { for (const memberName of Object.keys(this.memberVariables)) - this.memberVariables[memberName].include(); + this.memberVariables[memberName].include(context); } else { for (const memberName of Object.keys(this.memberVariables)) - this.context.includeVariable(this.memberVariables[memberName]); + this.context.includeVariable(context, this.memberVariables[memberName]); } } } initialise() { for (const name of this.context.getExports().concat(this.context.getReexports())) { @@ -8971,22 +4904,23 @@ return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${options.compact ? '' : ';'}${_}}`; } const safeName = RESERVED_NAMES[name] ? `'${name}'` : name; return `${t}${safeName}: ${original.getName()}`; }); - const name = this.getName(); - const callee = options.freeze ? `/*#__PURE__*/Object.freeze` : ''; - let output = `${options.varOrConst} ${name} = ${options.namespaceToStringTag - ? `{${n}${members.join(`,${n}`)}${n}};` - : `${callee}({${n}${members.join(`,${n}`)}${n}});`}`; + members.unshift(`${t}__proto__:${_}null`); if (options.namespaceToStringTag) { - output += `${n}if${_}(typeof Symbol${_}!==${_}'undefined'${_}&&${_}Symbol.toStringTag)${n}`; - output += `${t}Object.defineProperty(${name},${_}Symbol.toStringTag,${_}{${_}value:${_}'Module'${_}});${n}`; - output += `else${n || ' '}`; - output += `${t}Object.defineProperty(${name},${_}'toString',${_}{${_}value:${_}function${_}()${_}{${_}return${_}'[object Module]'${options.compact ? ';' : ''}${_}}${_}});${n}`; - output += `${callee}(${name});`; + members.unshift(`${t}[Symbol.toStringTag]:${_}'Module'`); } + const name = this.getName(); + let output = `{${n}${members.join(`,${n}`)}${n}}`; + if (this.syntheticNamedExports) { + output = `/*#__PURE__*/Object.assign(${output}, ${this.module.getDefaultExport().getName()})`; + } + if (options.freeze) { + output = `/*#__PURE__*/Object.freeze(${output})`; + } + output = `${options.varOrConst} ${name}${_}=${_}${output};`; if (options.format === 'system' && this.exportName) { output += `${n}exports('${this.exportName}',${_}${name});`; } return output; } @@ -9002,41 +4936,35 @@ function getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, mechanism = 'return ') { const _ = compact ? '' : ' '; const n = compact ? '' : '\n'; if (!namedExportsMode) { let local; - exports.some(expt => { - if (expt.exported === 'default') { - local = expt.local; - return true; + if (exports.length > 0) { + local = exports[0].local; + } + else { + for (const dep of dependencies) { + if (dep.reexports) { + const expt = dep.reexports[0]; + local = + dep.namedExportsMode && expt.imported !== '*' && expt.imported !== 'default' + ? `${dep.name}.${expt.imported}` + : dep.name; + break; + } } - return false; - }); - // search for reexported default otherwise - if (!local) { - dependencies.some(dep => { - if (!dep.reexports) - return false; - return dep.reexports.some(expt => { - if (expt.reexported === 'default') { - local = dep.namedExportsMode && expt.imported !== '*' ? `${dep.name}.${expt.imported}` : dep.name; - return true; - } - return false; - }); - }); } return `${mechanism}${local};`; } let exportBlock = ''; // star exports must always output first for precedence - dependencies.forEach(({ name, reexports }) => { + for (const { name, reexports } of dependencies) { if (reexports && namedExportsMode) { - reexports.forEach(specifier => { + for (const specifier of reexports) { if (specifier.reexported === '*') { - if (!compact && exportBlock) - exportBlock += '\n'; + if (exportBlock) + exportBlock += n; if (specifier.needsLiveBinding) { exportBlock += `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` + `${t}if${_}(k${_}!==${_}'default')${_}Object.defineProperty(exports,${_}k,${_}{${n}` + `${t}${t}enumerable:${_}true,${n}` + @@ -9048,32 +4976,33 @@ exportBlock += `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` + `${t}if${_}(k${_}!==${_}'default')${_}exports[k]${_}=${_}${name}[k];${n}});`; } } - }); + } } - }); - dependencies.forEach(({ name, imports, reexports, isChunk, namedExportsMode: depNamedExportsMode }) => { + } + for (const { name, imports, reexports, isChunk, namedExportsMode: depNamedExportsMode, exportsNames } of dependencies) { if (reexports && namedExportsMode) { - reexports.forEach(specifier => { + for (const specifier of reexports) { if (specifier.imported === 'default' && !isChunk) { - const exportsNamesOrNamespace = (imports && imports.some(specifier => specifier.imported !== 'default')) || - (reexports && - reexports.some(specifier => specifier.imported !== 'default' && specifier.imported !== '*')); - const reexportsDefaultAsDefault = reexports && - reexports.some(specifier => specifier.imported === 'default' && specifier.reexported === 'default'); - if (exportBlock && !compact) - exportBlock += '\n'; - if (exportsNamesOrNamespace || reexportsDefaultAsDefault) + if (exportBlock) + exportBlock += n; + if (exportsNames && + (reexports.some(specifier => specifier.imported === 'default' + ? specifier.reexported === 'default' + : specifier.imported !== '*') || + (imports && imports.some(specifier => specifier.imported !== 'default')))) { exportBlock += `exports.${specifier.reexported}${_}=${_}${name}${interop !== false ? '__default' : '.default'};`; - else + } + else { exportBlock += `exports.${specifier.reexported}${_}=${_}${name};`; + } } else if (specifier.imported !== '*') { - if (exportBlock && !compact) - exportBlock += '\n'; + if (exportBlock) + exportBlock += n; const importName = specifier.imported === 'default' && !depNamedExportsMode ? name : `${name}.${specifier.imported}`; exportBlock += specifier.needsLiveBinding ? `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` + @@ -9081,45 +5010,41 @@ `${t}get:${_}function${_}()${_}{${n}` + `${t}${t}return ${importName};${n}${t}}${n}});` : `exports.${specifier.reexported}${_}=${_}${importName};`; } else if (specifier.reexported !== '*') { - if (exportBlock && !compact) - exportBlock += '\n'; + if (exportBlock) + exportBlock += n; exportBlock += `exports.${specifier.reexported}${_}=${_}${name};`; } - }); + } } - }); - exports.forEach(expt => { + } + for (const expt of exports) { const lhs = `exports.${expt.exported}`; const rhs = expt.local; - if (lhs === rhs) { - return; + if (lhs !== rhs) { + if (exportBlock) + exportBlock += n; + exportBlock += `${lhs}${_}=${_}${rhs};`; } - if (exportBlock && !compact) - exportBlock += '\n'; - exportBlock += `${lhs}${_}=${_}${rhs};`; - }); + } return exportBlock; } function getInteropBlock(dependencies, options, varOrConst) { + const _ = options.compact ? '' : ' '; return dependencies .map(({ name, exportsNames, exportsDefault, namedExportsMode }) => { - if (!namedExportsMode) - return; - if (!exportsDefault || options.interop === false) + if (!namedExportsMode || !exportsDefault || options.interop === false) return null; if (exportsNames) { - if (options.compact) - return `${varOrConst} ${name}__default='default'in ${name}?${name}['default']:${name};`; - return `${varOrConst} ${name}__default = 'default' in ${name} ? ${name}['default'] : ${name};`; + return (`${varOrConst} ${name}__default${_}=${_}'default'${_}in ${name}${_}?` + + `${_}${name}['default']${_}:${_}${name};`); } - if (options.compact) - return `${name}=${name}&&${name}.hasOwnProperty('default')?${name}['default']:${name};`; - return `${name} = ${name} && ${name}.hasOwnProperty('default') ? ${name}['default'] : ${name};`; + return (`${name}${_}=${_}${name}${_}&&${_}${name}.hasOwnProperty('default')${_}?` + + `${_}${name}['default']${_}:${_}${name};`); }) .filter(Boolean) .join(options.compact ? '' : '\n'); } @@ -9308,104 +5233,123 @@ } function esm(magicString, { intro, outro, dependencies, exports }, options) { const _ = options.compact ? '' : ' '; const n = options.compact ? '' : '\n'; - const importBlock = dependencies - .map(({ id, reexports, imports, name }) => { + const importBlock = getImportBlock(dependencies, _); + if (importBlock.length > 0) + intro += importBlock.join(n) + n + n; + if (intro) + magicString.prepend(intro); + const exportBlock = getExportBlock$1(exports, _); + if (exportBlock.length) + magicString.append(n + n + exportBlock.join(n).trim()); + if (outro) + magicString.append(outro); + return magicString.trim(); +} +function getImportBlock(dependencies, _) { + const importBlock = []; + for (const { id, reexports, imports, name } of dependencies) { if (!reexports && !imports) { - return `import${_}'${id}';`; + importBlock.push(`import${_}'${id}';`); + continue; } - let output = ''; if (imports) { - const defaultImport = imports.find(specifier => specifier.imported === 'default'); - const starImport = imports.find(specifier => specifier.imported === '*'); + 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) { - output += `import${_}*${_}as ${starImport.local} from${_}'${id}';`; - if (imports.length > 1) - output += n; + importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`); } - if (defaultImport && imports.length === 1) { - output += `import ${defaultImport.local} from${_}'${id}';`; + if (defaultImport && importedNames.length === 0) { + importBlock.push(`import ${defaultImport.local} from${_}'${id}';`); } - else if (!starImport || imports.length > 1) { - output += `import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${imports - .filter(specifier => specifier !== defaultImport && specifier !== starImport) + else if (importedNames.length > 0) { + importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames .map(specifier => { if (specifier.imported === specifier.local) { return specifier.imported; } else { return `${specifier.imported} as ${specifier.local}`; } }) - .join(`,${_}`)}${_}}${_}from${_}'${id}';`; + .join(`,${_}`)}${_}}${_}from${_}'${id}';`); } } if (reexports) { - if (imports) - output += n; - const starExport = reexports.find(specifier => specifier.reexported === '*'); - const namespaceReexport = reexports.find(specifier => specifier.imported === '*' && specifier.reexported !== '*'); - if (starExport) { - output += `export${_}*${_}from${_}'${id}';`; - if (reexports.length === 1) { - return output; + let starExport = null; + const namespaceReexports = []; + const namedReexports = []; + for (const specifier of reexports) { + if (specifier.reexported === '*') { + starExport = specifier; } - output += n; + else if (specifier.imported === '*') { + namespaceReexports.push(specifier); + } + else { + namedReexports.push(specifier); + } } - if (namespaceReexport) { + if (starExport) { + importBlock.push(`export${_}*${_}from${_}'${id}';`); + } + if (namespaceReexports.length > 0) { if (!imports || - !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) - output += `import${_}*${_}as ${name} from${_}'${id}';${n}`; - output += `export${_}{${_}${name === namespaceReexport.reexported - ? name - : `${name} as ${namespaceReexport.reexported}`} };`; - if (reexports.length === (starExport ? 2 : 1)) { - return output; + !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) { + importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`); } - output += n; - } - output += `export${_}{${_}${reexports - .filter(specifier => specifier !== starExport && specifier !== namespaceReexport) - .map(specifier => { - if (specifier.imported === specifier.reexported) { - return specifier.imported; + for (const specifier of namespaceReexports) { + importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`); } - else { - return `${specifier.imported} as ${specifier.reexported}`; - } - }) - .join(`,${_}`)}${_}}${_}from${_}'${id}';`; + } + if (namedReexports.length > 0) { + importBlock.push(`export${_}{${_}${namedReexports + .map(specifier => { + if (specifier.imported === specifier.reexported) { + return specifier.imported; + } + else { + return `${specifier.imported} as ${specifier.reexported}`; + } + }) + .join(`,${_}`)}${_}}${_}from${_}'${id}';`); + } } - return output; - }) - .join(n); - if (importBlock) - intro += importBlock + n + n; - if (intro) - magicString.prepend(intro); + } + return importBlock; +} +function getExportBlock$1(exports, _) { const exportBlock = []; const exportDeclaration = []; - exports.forEach(specifier => { + for (const specifier of exports) { if (specifier.exported === 'default') { exportBlock.push(`export default ${specifier.local};`); } else { exportDeclaration.push(specifier.exported === specifier.local ? specifier.local : `${specifier.local} as ${specifier.exported}`); } - }); + } if (exportDeclaration.length) { exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`); } - if (exportBlock.length) - magicString.append(n + n + exportBlock.join(n).trim()); - if (outro) - magicString.append(outro); - return magicString.trim(); + return exportBlock; } function spaces(i) { let result = ''; while (i--) @@ -9492,20 +5436,25 @@ Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK"; Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED"; Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE"; Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND"; Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT"; + Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN"; Errors["INVALID_CHUNK"] = "INVALID_CHUNK"; + Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION"; Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID"; Errors["INVALID_OPTION"] = "INVALID_OPTION"; Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK"; Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE"; + Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS"; Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT"; Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR"; Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY"; Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT"; Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR"; + Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS"; + Errors["SYNTHETIC_NAMED_EXPORTS_NEED_DEFAULT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_DEFAULT"; })(Errors || (Errors = {})); function errAssetNotFinalisedForFileName(name) { return { code: Errors.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.` @@ -9557,19 +5506,38 @@ }; } function errFileNameConflict(fileName) { return { code: Errors.FILE_NAME_CONFLICT, - message: `Could not emit file "${fileName}" as it conflicts with an already emitted file.` + message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.` }; } +function errInputHookInOutputPlugin(pluginName, hookName) { + return { + code: Errors.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 errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) { return { code: Errors.INVALID_CHUNK, message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.` }; } +function errInvalidExportOptionValue(optionValue) { + return { + code: Errors.INVALID_EXPORT_OPTION, + message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`, + url: `https://rollupjs.org/guide/en/#output-exports` + }; +} +function errIncompatibleExportOptionValue(optionValue, keys, entryModule) { + return { + code: 'INVALID_EXPORT_OPTION', + message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}` + }; +} function errInternalIdCannotBeExternal(source, importer) { return { code: Errors.INVALID_EXTERNAL_ID, message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.` }; @@ -9590,10 +5558,19 @@ return { code: Errors.INVALID_ROLLUP_PHASE, message: `Cannot emit chunks after module loading has finished.` }; } +function errMixedExport(facadeModuleId, name) { + return { + code: Errors.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: `https://rollupjs.org/guide/en/#output-exports` + }; +} function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) { return { code: Errors.NAMESPACE_CONFLICT, message: `Conflicting namespaces: ${relativeId(reexportingModule.id)} re-exports '${name}' from both ${relativeId(reexportingModule.exportsAll[name])} and ${relativeId(additionalExportAllModule.exportsAll[name])} (will be ignored)`, name, @@ -9626,10 +5603,18 @@ message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`, source, url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency' }; } +function errExternalSyntheticExports(source, importer) { + return { + code: Errors.EXTERNAL_SYNTHETIC_EXPORTS, + importer: relativeId(importer), + message: `External '${source}' can not have 'syntheticNamedExports' enabled.`, + source + }; +} function errFailedValidation(message) { return { code: Errors.VALIDATION_ERROR, message }; @@ -9698,21 +5683,20 @@ const isNamespaced = name && name.indexOf('.') !== -1; const useVariableAssignment = !extend && !isNamespaced; if (name && useVariableAssignment && !isLegal(name)) { error({ code: 'ILLEGAL_IDENTIFIER_AS_NAME', - message: `Given name (${name}) is not legal JS identifier. If you need this you can try --extend option` + message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".` }); } warnOnBuiltins(warn, dependencies); const external = trimEmptyImports(dependencies); const deps = external.map(dep => dep.globalName || 'null'); const args = external.map(m => m.name); if (hasExports && !name) { - error({ - code: 'INVALID_OPTION', - message: `You must supply "output.name" for IIFE bundles.` + warn({ + message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.` }); } if (namedExportsMode && hasExports) { if (extend) { deps.unshift(`${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{}`); @@ -9723,18 +5707,17 @@ args.unshift('exports'); } } const useStrict = options.strict !== false ? `${t}'use strict';${n}${n}` : ``; let wrapperIntro = `(function${_}(${args.join(`,${_}`)})${_}{${n}${useStrict}`; - if (hasExports && (!extend || !namedExportsMode)) { + if (hasExports && (!extend || !namedExportsMode) && name) { wrapperIntro = (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name)) + `${_}=${_}${wrapperIntro}`; } if (isNamespaced && hasExports) { - wrapperIntro = - setupNamespace(name, 'this', options.globals, options.compact) + wrapperIntro; + wrapperIntro = setupNamespace(name, 'this', options.globals, options.compact) + wrapperIntro; } let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`; if (!extend && namedExportsMode && hasExports) { wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`; } @@ -9758,17 +5741,18 @@ function getStarExcludes({ dependencies, exports }) { const starExcludes = new Set(exports.map(expt => expt.exported)); if (!starExcludes.has('default')) starExcludes.add('default'); // also include reexport names - dependencies.forEach(({ reexports }) => { - if (reexports) - reexports.forEach(reexport => { + for (const { reexports } of dependencies) { + if (reexports) { + for (const reexport of reexports) { if (reexport.imported !== '*' && !starExcludes.has(reexport.reexported)) starExcludes.add(reexport.reexported); - }); - }); + } + } + } return starExcludes; } const getStarExcludesBlock = (starExcludes, varOrConst, _, t, n) => starExcludes ? `${n}${t}${varOrConst} _starExcludes${_}=${_}{${_}${Array.from(starExcludes).join(`:${_}1,${_}`)}${starExcludes.size ? `:${_}1` : ''}${_}};` : ''; @@ -9795,33 +5779,33 @@ const _ = options.compact ? '' : ' '; const dependencyIds = dependencies.map(m => `'${m.id}'`); const importBindings = []; let starExcludes; const setters = []; - dependencies.forEach(({ imports, reexports }) => { + for (const { imports, reexports } of dependencies) { const setter = []; if (imports) { - imports.forEach(specifier => { + for (const specifier of imports) { importBindings.push(specifier.local); if (specifier.imported === '*') { setter.push(`${specifier.local}${_}=${_}module;`); } else { setter.push(`${specifier.local}${_}=${_}module.${specifier.imported};`); } - }); + } } if (reexports) { let createdSetter = false; // bulk-reexport form if (reexports.length > 1 || (reexports.length === 1 && (reexports[0].reexported === '*' || reexports[0].imported === '*'))) { // star reexports - reexports.forEach(specifier => { + for (const specifier of reexports) { if (specifier.reexported !== '*') - return; + continue; // need own exports list for deduping in star export case if (!starExcludes) { starExcludes = getStarExcludes({ dependencies, exports }); } if (!createdSetter) { @@ -9829,49 +5813,49 @@ createdSetter = true; } setter.push(`for${_}(var _$p${_}in${_}module)${_}{`); setter.push(`${t}if${_}(!_starExcludes[_$p])${_}_setter[_$p]${_}=${_}module[_$p];`); setter.push('}'); - }); + } // star import reexport - reexports.forEach(specifier => { + for (const specifier of reexports) { if (specifier.imported !== '*' || specifier.reexported === '*') - return; + continue; setter.push(`exports('${specifier.reexported}',${_}module);`); - }); + } // reexports - reexports.forEach(specifier => { + for (const specifier of reexports) { if (specifier.reexported === '*' || specifier.imported === '*') - return; + continue; if (!createdSetter) { setter.push(`${varOrConst} _setter${_}=${_}{};`); createdSetter = true; } setter.push(`_setter.${specifier.reexported}${_}=${_}module.${specifier.imported};`); - }); + } if (createdSetter) { setter.push('exports(_setter);'); } } else { // single reexport - reexports.forEach(specifier => { + for (const specifier of reexports) { setter.push(`exports('${specifier.reexported}',${_}module.${specifier.imported});`); - }); + } } } setters.push(setter.join(`${n}${t}${t}${t}`)); - }); + } const registeredName = options.name ? `'${options.name}',${_}` : ''; const wrapperParams = accessedGlobals.has('module') ? `exports,${_}module` : hasExports ? 'exports' : ''; let wrapperStart = `System.register(${registeredName}[` + dependencyIds.join(`,${_}`) + - `],${_}function${_}(${wrapperParams})${_}{${n}${t}'use strict';` + + `],${_}function${_}(${wrapperParams})${_}{${n}${t}${options.strict ? "'use strict';" : ''}` + getStarExcludesBlock(starExcludes, varOrConst, _, t, n) + getImportBindingsBlock(importBindings, _, t, n) + `${n}${t}return${_}{${setters.length ? `${n}${t}${t}setters:${_}[${setters .map(s => s @@ -9968,16 +5952,17 @@ const iifeEnd = iifeNeedsGlobal ? ')' : ''; const cjsIntro = iifeNeedsGlobal ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` + `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}` : ''; + // factory function should be wrapped by parentheses to avoid lazy parsing const wrapperIntro = `(function${_}(${globalParam}${factoryVar})${_}{${n}` + cjsIntro + `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` + `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` + - `}(${globalArg}function${_}(${factoryArgs.join(', ')})${_}{${useStrict}${n}`; - const wrapperOutro = n + n + '}));'; + `}(${globalArg}(function${_}(${factoryArgs.join(', ')})${_}{${useStrict}${n}`; + const wrapperOutro = n + n + '})));'; // var foo__default = 'default' in foo ? foo['default'] : foo; const interopBlock = getInteropBlock(dependencies, options, varOrConst); if (interopBlock) magicString.prepend(interopBlock + n + n); if (intro) @@ -10030,10 +6015,23 @@ const names = []; extractors[param.type](names, param); return names; }; +class ExportAllDeclaration extends NodeBase { + hasEffects() { + return false; + } + initialise() { + this.context.addExport(this); + } + render(code, _options, nodeRenderOptions) { + code.remove(nodeRenderOptions.start, nodeRenderOptions.end); + } +} +ExportAllDeclaration.prototype.needsBoundaries = true; + class ArrayExpression extends NodeBase { bind() { super.bind(); for (const element of this.elements) { if (element !== null) @@ -10046,13 +6044,13 @@ return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]); } hasEffectsWhenAccessedAtPath(path) { return path.length > 1; } - hasEffectsWhenCalledAtPath(path, callOptions, options) { + hasEffectsWhenCalledAtPath(path, callOptions, context) { if (path.length === 1) { - return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, options); + return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context); } return true; } } @@ -10062,11 +6060,11 @@ if (element !== null) { element.addExportedVariables(variables); } } } - declare(kind, _init) { + declare(kind) { const variables = []; for (const element of this.elements) { if (element !== null) { variables.push(...element.declare(kind, UNKNOWN_EXPRESSION)); } @@ -10080,25 +6078,25 @@ element.deoptimizePath(path); } } } } - hasEffectsWhenAssignedAtPath(path, options) { + hasEffectsWhenAssignedAtPath(path, context) { if (path.length > 0) return true; for (const element of this.elements) { - if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options)) + if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)) return true; } return false; } } class BlockScope extends ChildScope { - addDeclaration(identifier, context, init = null, isHoisted = false) { + addDeclaration(identifier, context, init = null, isHoisted) { if (isHoisted) { - return this.parent.addDeclaration(identifier, context, UNKNOWN_EXPRESSION, true); + return this.parent.addDeclaration(identifier, context, isHoisted === 'function' ? init : UNKNOWN_EXPRESSION, isHoisted); } else { return super.addDeclaration(identifier, context, init, false); } } @@ -10114,22 +6112,24 @@ createScope(parentScope) { this.scope = this.parent.preventChildBlockScope ? parentScope : new BlockScope(parentScope); } - hasEffects(options) { + hasEffects(context) { for (const node of this.body) { - if (node.hasEffects(options)) + if (node.hasEffects(context)) return true; + if (context.brokenFlow) + break; } return false; } - include(includeChildrenRecursively) { + include(context, includeChildrenRecursively) { this.included = true; for (const node of this.body) { - if (includeChildrenRecursively || node.shouldBeIncluded()) - node.include(includeChildrenRecursively); + if (includeChildrenRecursively || node.shouldBeIncluded(context)) + node.include(context, includeChildrenRecursively); } } render(code, options) { if (this.body.length) { renderStatementList(this.body, code, this.start + 1, this.end - 1, options); @@ -10145,47 +6145,60 @@ this.scope = new ReturnValueScope(parentScope, this.context); } deoptimizePath(path) { // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track // which means the return expression needs to be reassigned - if (path.length === 1 && path[0] === UNKNOWN_KEY) { + if (path.length === 1 && path[0] === UnknownKey) { this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH); } } getReturnExpressionWhenCalledAtPath(path) { return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION; } - hasEffects(_options) { + hasEffects() { return false; } - hasEffectsWhenAccessedAtPath(path, _options) { + hasEffectsWhenAccessedAtPath(path) { return path.length > 1; } - hasEffectsWhenAssignedAtPath(path, _options) { + hasEffectsWhenAssignedAtPath(path) { return path.length > 1; } - hasEffectsWhenCalledAtPath(path, _callOptions, options) { - if (path.length > 0) { + hasEffectsWhenCalledAtPath(path, _callOptions, context) { + if (path.length > 0) return true; - } for (const param of this.params) { - if (param.hasEffects(options)) + if (param.hasEffects(context)) return true; } - return this.body.hasEffects(options); + const { ignore, brokenFlow } = context; + context.ignore = { + breaks: false, + continues: false, + labels: new Set(), + returnAwaitYield: true + }; + if (this.body.hasEffects(context)) + return true; + context.ignore = ignore; + context.brokenFlow = brokenFlow; + return false; } - include(includeChildrenRecursively) { + include(context, includeChildrenRecursively) { this.included = true; - this.body.include(includeChildrenRecursively); for (const param of this.params) { if (!(param instanceof Identifier$1)) { - param.include(includeChildrenRecursively); + param.include(context, includeChildrenRecursively); } } + const { brokenFlow } = context; + context.brokenFlow = BROKEN_FLOW_NONE; + this.body.include(context, includeChildrenRecursively); + context.brokenFlow = brokenFlow; } - includeCallArguments(args) { - this.scope.includeCallArguments(args); + includeCallArguments(context, args) { + this.scope.includeCallArguments(context, args); } initialise() { this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement); if (this.body instanceof BlockStatement$1) { this.body.addImplicitReturnExpressionToScope(); @@ -10214,30 +6227,41 @@ .join(', ')}});`; } } class AssignmentExpression extends NodeBase { - bind() { - super.bind(); - this.left.deoptimizePath(EMPTY_PATH); - // We cannot propagate mutations of the new binding to the old binding with certainty - this.right.deoptimizePath(UNKNOWN_PATH); + constructor() { + super(...arguments); + this.deoptimized = false; } - hasEffects(options) { - return (this.right.hasEffects(options) || - this.left.hasEffects(options) || - this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options)); + hasEffects(context) { + if (!this.deoptimized) + this.applyDeoptimizations(); + return (this.right.hasEffects(context) || + this.left.hasEffects(context) || + this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)); } - hasEffectsWhenAccessedAtPath(path, options) { - return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, options); + hasEffectsWhenAccessedAtPath(path, context) { + return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, context); } + include(context, includeChildrenRecursively) { + if (!this.deoptimized) + this.applyDeoptimizations(); + this.included = true; + this.left.include(context, includeChildrenRecursively); + this.right.include(context, includeChildrenRecursively); + } render(code, options) { this.left.render(code, options); this.right.render(code, options); if (options.format === 'system') { if (this.left.variable && this.left.variable.exportName) { - code.prependLeft(code.original.indexOf('=', this.left.end) + 1, ` exports('${this.left.variable.exportName}',`); + const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end); + const operation = this.operator.length > 1 + ? ` ${this.left.variable.exportName} ${this.operator.slice(0, -1)}` + : ''; + code.overwrite(operatorPos, operatorPos + this.operator.length, `= exports('${this.left.variable.exportName}',${operation}`); code.appendLeft(this.right.end, `)`); } else if ('addExportedVariables' in this.left) { const systemPatternExports = []; this.left.addExportedVariables(systemPatternExports); @@ -10246,10 +6270,15 @@ code.appendLeft(this.end, ')'); } } } } + applyDeoptimizations() { + this.deoptimized = true; + this.left.deoptimizePath(EMPTY_PATH); + this.right.deoptimizePath(UNKNOWN_PATH); + } } class AssignmentPattern extends NodeBase { addExportedVariables(variables) { this.left.addExportedVariables(variables); @@ -10263,53 +6292,39 @@ return this.left.declare(kind, init); } deoptimizePath(path) { path.length === 0 && this.left.deoptimizePath(path); } - hasEffectsWhenAssignedAtPath(path, options) { - return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options); + hasEffectsWhenAssignedAtPath(path, context) { + return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context); } render(code, options, { isShorthandProperty } = BLANK) { this.left.render(code, options, { isShorthandProperty }); this.right.render(code, options); } } class AwaitExpression extends NodeBase { - hasEffects(options) { - return super.hasEffects(options) || !options.ignoreReturnAwaitYield(); + hasEffects(context) { + return !context.ignore.returnAwaitYield || this.argument.hasEffects(context); } - include(includeChildrenRecursively) { - checkTopLevelAwait: if (!this.included && !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; + include(context, includeChildrenRecursively) { + 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; + } } - super.include(includeChildrenRecursively); + this.argument.include(context, includeChildrenRecursively); } - render(code, options) { - super.render(code, options); - } } -const RESULT_KEY$1 = {}; -class ImmutableEntityPathTracker { - constructor(existingEntityPaths = Immutable.Map()) { - this.entityPaths = existingEntityPaths; - } - isTracked(entity, path) { - return this.entityPaths.getIn([entity, ...path, RESULT_KEY$1]); - } - track(entity, path) { - return new ImmutableEntityPathTracker(this.entityPaths.setIn([entity, ...path, RESULT_KEY$1], true)); - } -} -const EMPTY_IMMUTABLE_TRACKER = new ImmutableEntityPathTracker(); - class ExpressionStatement$1 extends NodeBase { initialise() { if (this.directive && this.directive !== 'use strict' && this.parent.type === Program) { @@ -10324,14 +6339,14 @@ render(code, options) { super.render(code, options); if (this.included) this.insertSemicolon(code); } - shouldBeIncluded() { + shouldBeIncluded(context) { if (this.directive && this.directive !== 'use strict') return this.parent.type !== Program; - return super.shouldBeIncluded(); + return super.shouldBeIncluded(context); } } const binaryOperators = { '!=': (left, right) => left != right, @@ -10352,58 +6367,346 @@ '>': (left, right) => left > right, '>=': (left, right) => left >= right, '>>': (left, right) => left >> right, '>>>': (left, right) => left >>> right, '^': (left, right) => left ^ right, - in: () => UNKNOWN_VALUE, - instanceof: () => UNKNOWN_VALUE, + in: () => UnknownValue, + instanceof: () => UnknownValue, '|': (left, right) => left | right }; class BinaryExpression extends NodeBase { deoptimizeCache() { } getLiteralValueAtPath(path, recursionTracker, origin) { if (path.length > 0) - return UNKNOWN_VALUE; + return UnknownValue; const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin); - if (leftValue === UNKNOWN_VALUE) - return UNKNOWN_VALUE; + if (leftValue === UnknownValue) + return UnknownValue; const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin); - if (rightValue === UNKNOWN_VALUE) - return UNKNOWN_VALUE; + if (rightValue === UnknownValue) + return UnknownValue; const operatorFn = binaryOperators[this.operator]; if (!operatorFn) - return UNKNOWN_VALUE; + return UnknownValue; return operatorFn(leftValue, rightValue); } - hasEffects(options) { + hasEffects(context) { // support some implicit type coercion runtime errors if (this.operator === '+' && this.parent instanceof ExpressionStatement$1 && - this.left.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this) === '') { + this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') return true; - } - return super.hasEffects(options); + return super.hasEffects(context); } - hasEffectsWhenAccessedAtPath(path, _options) { + hasEffectsWhenAccessedAtPath(path) { return path.length > 1; } } class BreakStatement extends NodeBase { - hasEffects(options) { - return (super.hasEffects(options) || - !options.ignoreBreakStatements() || - (this.label !== null && !options.ignoreLabel(this.label.name))); + hasEffects(context) { + if (this.label) { + if (!context.ignore.labels.has(this.label.name)) + return true; + context.includedLabels.add(this.label.name); + context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL; + } + else { + if (!context.ignore.breaks) + return true; + context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE; + } + return false; } + include(context) { + this.included = true; + if (this.label) { + this.label.include(context); + context.includedLabels.add(this.label.name); + } + context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE; + } } +class Literal extends NodeBase { + 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_EXPRESSION; + return getMemberReturnExpressionWhenCalled(this.members, path[0]); + } + hasEffectsWhenAccessedAtPath(path) { + if (this.value === null) { + return path.length > 0; + } + return path.length > 1; + } + hasEffectsWhenAssignedAtPath(path) { + return path.length > 0; + } + hasEffectsWhenCalledAtPath(path, callOptions, context) { + if (path.length === 1) { + return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, context); + } + return true; + } + initialise() { + this.members = getLiteralMembersForValue(this.value); + } + render(code) { + if (typeof this.value === 'string') { + code.indentExclusionRanges.push([this.start + 1, this.end - 1]); + } + } +} + +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$1) { + 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 { + constructor() { + super(...arguments); + this.variable = null; + this.bound = false; + this.expressionsToBeDeoptimized = []; + this.replacement = null; + this.wasPathDeoptimizedWhileOptimized = false; + } + addExportedVariables() { } + bind() { + if (this.bound) + return; + this.bound = true; + const path = getPathIfNotComputed(this); + const baseVariable = path && this.scope.findVariable(path[0].key); + if (baseVariable && baseVariable.isNamespace) { + const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1)); + if (!resolvedVariable) { + super.bind(); + } + else if (typeof resolvedVariable === 'string') { + this.replacement = resolvedVariable; + } + else { + if (resolvedVariable instanceof ExternalVariable && resolvedVariable.module) { + resolvedVariable.module.suggestName(path[0].key); + } + this.variable = resolvedVariable; + this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable); + } + } + else { + super.bind(); + // ensure the propertyKey is set for the tree-shaking passes + this.getPropertyKey(); + } + } + deoptimizeCache() { + const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized; + this.expressionsToBeDeoptimized = []; + this.propertyKey = UnknownKey; + if (this.wasPathDeoptimizedWhileOptimized) { + this.object.deoptimizePath(UNKNOWN_PATH); + } + for (const expression of expressionsToBeDeoptimized) { + expression.deoptimizeCache(); + } + } + deoptimizePath(path) { + if (!this.bound) + this.bind(); + if (path.length === 0) + this.disallowNamespaceReassignment(); + if (this.variable) { + this.variable.deoptimizePath(path); + } + else { + const propertyKey = this.getPropertyKey(); + if (propertyKey === UnknownKey) { + this.object.deoptimizePath(UNKNOWN_PATH); + } + else { + this.wasPathDeoptimizedWhileOptimized = true; + this.object.deoptimizePath([propertyKey, ...path]); + } + } + } + getLiteralValueAtPath(path, recursionTracker, origin) { + if (!this.bound) + this.bind(); + if (this.variable !== null) { + return this.variable.getLiteralValueAtPath(path, recursionTracker, origin); + } + this.expressionsToBeDeoptimized.push(origin); + return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin); + } + getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) { + if (!this.bound) + this.bind(); + if (this.variable !== null) { + return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin); + } + this.expressionsToBeDeoptimized.push(origin); + return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], recursionTracker, origin); + } + hasEffects(context) { + return (this.property.hasEffects(context) || + this.object.hasEffects(context) || + (this.context.propertyReadSideEffects && + this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], context))); + } + hasEffectsWhenAccessedAtPath(path, context) { + if (path.length === 0) + return false; + if (this.variable !== null) { + return this.variable.hasEffectsWhenAccessedAtPath(path, context); + } + return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey, ...path], context); + } + hasEffectsWhenAssignedAtPath(path, context) { + if (this.variable !== null) { + return this.variable.hasEffectsWhenAssignedAtPath(path, context); + } + return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey, ...path], context); + } + hasEffectsWhenCalledAtPath(path, callOptions, context) { + if (this.variable !== null) { + return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context); + } + return this.object.hasEffectsWhenCalledAtPath([this.propertyKey, ...path], callOptions, context); + } + include(context, includeChildrenRecursively) { + if (!this.included) { + this.included = true; + if (this.variable !== null) { + this.context.includeVariable(context, this.variable); + } + } + this.object.include(context, includeChildrenRecursively); + this.property.include(context, includeChildrenRecursively); + } + includeCallArguments(context, args) { + if (this.variable) { + this.variable.includeCallArguments(context, args); + } + else { + super.includeCallArguments(context, args); + } + } + initialise() { + this.propertyKey = getResolvablePropertyKey(this); + } + render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) { + const isCalleeOfDifferentParent = renderedParentType === CallExpression && isCalleeOfRenderedParent; + if (this.variable || this.replacement) { + let replacement = this.variable ? this.variable.getName() : this.replacement; + if (isCalleeOfDifferentParent) + replacement = '0, ' + replacement; + code.overwrite(this.start, this.end, replacement, { + contentOnly: true, + storeName: true + }); + } + else { + if (isCalleeOfDifferentParent) { + code.appendRight(this.start, '0, '); + } + super.render(code, options); + } + } + disallowNamespaceReassignment() { + if (this.object instanceof Identifier$1 && + this.scope.findVariable(this.object.name).isNamespace) { + this.context.error({ + code: 'ILLEGAL_NAMESPACE_REASSIGNMENT', + message: `Illegal reassignment to import '${this.object.name}'` + }, 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 === UnknownValue ? UnknownKey : String(value)); + } + return this.propertyKey; + } + resolveNamespaceVariables(baseVariable, path) { + if (path.length === 0) + return baseVariable; + if (!baseVariable.isNamespace) + return null; + const exportName = path[0].key; + const variable = baseVariable instanceof ExternalVariable + ? baseVariable.module.getVariableForExportName(exportName) + : baseVariable.context.traceExport(exportName); + if (!variable) { + const fileName = baseVariable instanceof ExternalVariable + ? baseVariable.module.id + : baseVariable.context.fileName; + this.context.warn({ + code: 'MISSING_EXPORT', + exporter: relativeId(fileName), + importer: relativeId(this.context.fileName), + message: `'${exportName}' is not exported by '${relativeId(fileName)}'`, + missing: exportName, + url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module` + }, path[0].pos); + return 'undefined'; + } + return this.resolveNamespaceVariables(variable, path.slice(1)); + } +} + class CallExpression$1 extends NodeBase { constructor() { super(...arguments); - // We collect deoptimization information if returnExpression !== UNKNOWN_EXPRESSION this.expressionsToBeDeoptimized = []; this.returnExpression = null; + this.wasPathDeoptmizedWhileOptimized = false; } bind() { super.bind(); if (this.callee instanceof Identifier$1) { const variable = this.scope.findVariable(this.callee.name); @@ -10419,105 +6722,143 @@ message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`, url: 'https://rollupjs.org/guide/en/#avoiding-eval' }, this.start); } } - if (this.returnExpression === null) { - this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this); + // ensure the returnExpression is set for the tree-shaking passes + this.getReturnExpression(SHARED_RECURSION_TRACKER); + // This deoptimizes "this" for non-namespace calls until we have a better solution + if (this.callee instanceof MemberExpression && !this.callee.variable) { + this.callee.object.deoptimizePath(UNKNOWN_PATH); } for (const argument of this.arguments) { // This will make sure all properties of parameters behave as "unknown" argument.deoptimizePath(UNKNOWN_PATH); } } deoptimizeCache() { if (this.returnExpression !== UNKNOWN_EXPRESSION) { - this.returnExpression = UNKNOWN_EXPRESSION; - for (const expression of this.expressionsToBeDeoptimized) { + this.returnExpression = null; + const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER); + const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized; + if (returnExpression !== UNKNOWN_EXPRESSION) { + // We need to replace here because is possible new expressions are added + // while we are deoptimizing the old ones + this.expressionsToBeDeoptimized = []; + if (this.wasPathDeoptmizedWhileOptimized) { + returnExpression.deoptimizePath(UNKNOWN_PATH); + this.wasPathDeoptmizedWhileOptimized = false; + } + } + for (const expression of expressionsToBeDeoptimized) { expression.deoptimizeCache(); } } } deoptimizePath(path) { - if (path.length > 0 && !this.context.deoptimizationTracker.track(this, path)) { - if (this.returnExpression === null) { - this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this); - } - this.returnExpression.deoptimizePath(path); + if (path.length === 0) + return; + const trackedEntities = this.context.deoptimizationTracker.getEntities(path); + if (trackedEntities.has(this)) + return; + trackedEntities.add(this); + const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER); + if (returnExpression !== UNKNOWN_EXPRESSION) { + this.wasPathDeoptmizedWhileOptimized = true; + returnExpression.deoptimizePath(path); } } getLiteralValueAtPath(path, recursionTracker, origin) { - if (this.returnExpression === null) { - this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this); + const returnExpression = this.getReturnExpression(recursionTracker); + if (returnExpression === UNKNOWN_EXPRESSION) { + return UnknownValue; } - if (this.returnExpression === UNKNOWN_EXPRESSION || - recursionTracker.isTracked(this.returnExpression, path)) { - return UNKNOWN_VALUE; + const trackedEntities = recursionTracker.getEntities(path); + if (trackedEntities.has(returnExpression)) { + return UnknownValue; } this.expressionsToBeDeoptimized.push(origin); - return this.returnExpression.getLiteralValueAtPath(path, recursionTracker.track(this.returnExpression, path), origin); + trackedEntities.add(returnExpression); + const value = returnExpression.getLiteralValueAtPath(path, recursionTracker, origin); + trackedEntities.delete(returnExpression); + return value; } getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) { - if (this.returnExpression === null) { - this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this); + const returnExpression = this.getReturnExpression(recursionTracker); + if (this.returnExpression === UNKNOWN_EXPRESSION) { + return UNKNOWN_EXPRESSION; } - if (this.returnExpression === UNKNOWN_EXPRESSION || - recursionTracker.isTracked(this.returnExpression, path)) { + const trackedEntities = recursionTracker.getEntities(path); + if (trackedEntities.has(returnExpression)) { return UNKNOWN_EXPRESSION; } this.expressionsToBeDeoptimized.push(origin); - return this.returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker.track(this.returnExpression, path), origin); + trackedEntities.add(returnExpression); + const value = returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin); + trackedEntities.delete(returnExpression); + return value; } - hasEffects(options) { + hasEffects(context) { for (const argument of this.arguments) { - if (argument.hasEffects(options)) + if (argument.hasEffects(context)) return true; } if (this.context.annotations && this.annotatedPure) return false; - return (this.callee.hasEffects(options) || - this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, options.getHasEffectsWhenCalledOptions())); + return (this.callee.hasEffects(context) || + this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context)); } - hasEffectsWhenAccessedAtPath(path, options) { - return (path.length > 0 && - !options.hasReturnExpressionBeenAccessedAtPath(path, this) && - this.returnExpression.hasEffectsWhenAccessedAtPath(path, options.addAccessedReturnExpressionAtPath(path, this))); + hasEffectsWhenAccessedAtPath(path, context) { + if (path.length === 0) + return false; + const trackedExpressions = context.accessed.getEntities(path); + if (trackedExpressions.has(this)) + return false; + trackedExpressions.add(this); + return this.returnExpression.hasEffectsWhenAccessedAtPath(path, context); } - hasEffectsWhenAssignedAtPath(path, options) { - return (path.length === 0 || - (!options.hasReturnExpressionBeenAssignedAtPath(path, this) && - this.returnExpression.hasEffectsWhenAssignedAtPath(path, options.addAssignedReturnExpressionAtPath(path, this)))); + hasEffectsWhenAssignedAtPath(path, context) { + if (path.length === 0) + return true; + const trackedExpressions = context.assigned.getEntities(path); + if (trackedExpressions.has(this)) + return false; + trackedExpressions.add(this); + return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context); } - hasEffectsWhenCalledAtPath(path, callOptions, options) { - if (options.hasReturnExpressionBeenCalledAtPath(path, this)) + hasEffectsWhenCalledAtPath(path, callOptions, context) { + const trackedExpressions = (callOptions.withNew + ? context.instantiated + : context.called).getEntities(path); + if (trackedExpressions.has(this)) return false; - return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, options.addCalledReturnExpressionAtPath(path, this)); + trackedExpressions.add(this); + return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context); } - include(includeChildrenRecursively) { + include(context, includeChildrenRecursively) { if (includeChildrenRecursively) { - super.include(includeChildrenRecursively); + super.include(context, includeChildrenRecursively); if (includeChildrenRecursively === INCLUDE_PARAMETERS && this.callee instanceof Identifier$1 && this.callee.variable) { this.callee.variable.markCalledFromTryStatement(); } } else { this.included = true; - this.callee.include(false); + this.callee.include(context, false); } - this.callee.includeCallArguments(this.arguments); + this.callee.includeCallArguments(context, this.arguments); if (!this.returnExpression.included) { - this.returnExpression.include(false); + this.returnExpression.include(context, false); } } initialise() { - this.callOptions = CallOptions.create({ + this.callOptions = { args: this.arguments, - callIdentifier: this, withNew: false - }); + }; } render(code, options, { renderedParentType } = BLANK) { this.callee.render(code, options); if (this.arguments.length > 0) { if (this.arguments[this.arguments.length - 1].included) { @@ -10545,16 +6886,23 @@ this.callee.type === FunctionExpression) { code.appendRight(this.start, '('); code.prependLeft(this.end, ')'); } } + getReturnExpression(recursionTracker) { + if (this.returnExpression === null) { + this.returnExpression = UNKNOWN_EXPRESSION; + return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this)); + } + return this.returnExpression; + } } class CatchScope extends ParameterScope { - addDeclaration(identifier, context, init = null, isHoisted = false) { + addDeclaration(identifier, context, init, isHoisted) { if (isHoisted) { - return this.parent.addDeclaration(identifier, context, init, true); + return this.parent.addDeclaration(identifier, context, init, isHoisted); } else { return super.addDeclaration(identifier, context, init, false); } } @@ -10575,16 +6923,15 @@ } } CatchClause.prototype.preventChildBlockScope = true; class ClassBody extends NodeBase { - hasEffectsWhenCalledAtPath(path, callOptions, options) { - if (path.length > 0) { + hasEffectsWhenCalledAtPath(path, callOptions, context) { + if (path.length > 0) return true; - } return (this.classConstructor !== null && - this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, options)); + this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context)); } initialise() { for (const method of this.body) { if (method.kind === 'constructor') { this.classConstructor = method; @@ -10607,143 +6954,141 @@ for (const expression of this.expressions) { expression.deoptimizePath(path); } } getLiteralValueAtPath() { - return UNKNOWN_VALUE; + return UnknownValue; } getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) { return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin))); } - hasEffectsWhenAccessedAtPath(path, options) { + hasEffectsWhenAccessedAtPath(path, context) { for (const expression of this.expressions) { - if (expression.hasEffectsWhenAccessedAtPath(path, options)) + if (expression.hasEffectsWhenAccessedAtPath(path, context)) return true; } return false; } - hasEffectsWhenAssignedAtPath(path, options) { + hasEffectsWhenAssignedAtPath(path, context) { for (const expression of this.expressions) { - if (expression.hasEffectsWhenAssignedAtPath(path, options)) + if (expression.hasEffectsWhenAssignedAtPath(path, context)) return true; } return false; } - hasEffectsWhenCalledAtPath(path, callOptions, options) { + hasEffectsWhenCalledAtPath(path, callOptions, context) { for (const expression of this.expressions) { - if (expression.hasEffectsWhenCalledAtPath(path, callOptions, options)) + if (expression.hasEffectsWhenCalledAtPath(path, callOptions, context)) return true; } return false; } include() { } - includeCallArguments(args) { - for (const expression of this.expressions) { - expression.includeCallArguments(args); - } - } + includeCallArguments() { } } class ConditionalExpression extends NodeBase { constructor() { super(...arguments); - // We collect deoptimization information if usedBranch !== null this.expressionsToBeDeoptimized = []; this.isBranchResolutionAnalysed = false; - this.unusedBranch = null; this.usedBranch = null; + this.wasPathDeoptimizedWhileOptimized = false; } bind() { super.bind(); - if (!this.isBranchResolutionAnalysed) - this.analyseBranchResolution(); + // ensure the usedBranch is set for the tree-shaking passes + this.getUsedBranch(); } deoptimizeCache() { if (this.usedBranch !== null) { - // We did not track if there were reassignments to the previous branch. - // Also, the return value might need to be reassigned. + const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent; this.usedBranch = null; - this.unusedBranch.deoptimizePath(UNKNOWN_PATH); - for (const expression of this.expressionsToBeDeoptimized) { + const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized; + this.expressionsToBeDeoptimized = []; + if (this.wasPathDeoptimizedWhileOptimized) { + unusedBranch.deoptimizePath(UNKNOWN_PATH); + } + for (const expression of expressionsToBeDeoptimized) { expression.deoptimizeCache(); } } } deoptimizePath(path) { if (path.length > 0) { - if (!this.isBranchResolutionAnalysed) - this.analyseBranchResolution(); - if (this.usedBranch === null) { + const usedBranch = this.getUsedBranch(); + if (usedBranch === null) { this.consequent.deoptimizePath(path); this.alternate.deoptimizePath(path); } else { - this.usedBranch.deoptimizePath(path); + this.wasPathDeoptimizedWhileOptimized = true; + usedBranch.deoptimizePath(path); } } } getLiteralValueAtPath(path, recursionTracker, origin) { - if (!this.isBranchResolutionAnalysed) - this.analyseBranchResolution(); - if (this.usedBranch === null) - return UNKNOWN_VALUE; + const usedBranch = this.getUsedBranch(); + if (usedBranch === null) + return UnknownValue; this.expressionsToBeDeoptimized.push(origin); - return this.usedBranch.getLiteralValueAtPath(path, recursionTracker, origin); + return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin); } getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) { - if (!this.isBranchResolutionAnalysed) - this.analyseBranchResolution(); - if (this.usedBranch === null) + const usedBranch = this.getUsedBranch(); + if (usedBranch === null) return new MultiExpression([ this.consequent.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin), this.alternate.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) ]); this.expressionsToBeDeoptimized.push(origin); - return this.usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin); + return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin); } - hasEffects(options) { - if (this.test.hasEffects(options)) + hasEffects(context) { + if (this.test.hasEffects(context)) return true; if (this.usedBranch === null) { - return this.consequent.hasEffects(options) || this.alternate.hasEffects(options); + return this.consequent.hasEffects(context) || this.alternate.hasEffects(context); } - return this.usedBranch.hasEffects(options); + return this.usedBranch.hasEffects(context); } - hasEffectsWhenAccessedAtPath(path, options) { + hasEffectsWhenAccessedAtPath(path, context) { if (path.length === 0) return false; if (this.usedBranch === null) { - return (this.consequent.hasEffectsWhenAccessedAtPath(path, options) || - this.alternate.hasEffectsWhenAccessedAtPath(path, options)); + return (this.consequent.hasEffectsWhenAccessedAtPath(path, context) || + this.alternate.hasEffectsWhenAccessedAtPath(path, context)); } - return this.usedBranch.hasEffectsWhenAccessedAtPath(path, options); + return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context); } - hasEffectsWhenAssignedAtPath(path, options) { + hasEffectsWhenAssignedAtPath(path, context) { if (path.length === 0) return true; if (this.usedBranch === null) { - return (this.consequent.hasEffectsWhenAssignedAtPath(path, options) || - this.alternate.hasEffectsWhenAssignedAtPath(path, options)); + return (this.consequent.hasEffectsWhenAssignedAtPath(path, context) || + this.alternate.hasEffectsWhenAssignedAtPath(path, context)); } - return this.usedBranch.hasEffectsWhenAssignedAtPath(path, options); + return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context); } - hasEffectsWhenCalledAtPath(path, callOptions, options) { + hasEffectsWhenCalledAtPath(path, callOptions, context) { if (this.usedBranch === null) { - return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, options) || - this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, options)); + return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, context) || + this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, context)); } - return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, options); + return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context); } - include(includeChildrenRecursively) { + include(context, includeChildrenRecursively) { this.included = true; - if (includeChildrenRecursively || this.usedBranch === null || this.test.shouldBeIncluded()) { - this.test.include(includeChildrenRecursively); - this.consequent.include(includeChildrenRecursively); - this.alternate.include(includeChildrenRecursively); + if (includeChildrenRecursively || + this.usedBranch === null || + this.test.shouldBeIncluded(context)) { + this.test.include(context, includeChildrenRecursively); + this.consequent.include(context, includeChildrenRecursively); + this.alternate.include(context, includeChildrenRecursively); } else { - this.usedBranch.include(includeChildrenRecursively); + this.usedBranch.include(context, includeChildrenRecursively); } } render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) { if (!this.test.included) { const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end); @@ -10767,64 +7112,90 @@ } else { super.render(code, options); } } - analyseBranchResolution() { - this.isBranchResolutionAnalysed = true; - const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this); - if (testValue !== UNKNOWN_VALUE) { - if (testValue) { - this.usedBranch = this.consequent; - this.unusedBranch = this.alternate; - } - else { - this.usedBranch = this.alternate; - this.unusedBranch = this.consequent; - } + getUsedBranch() { + if (this.isBranchResolutionAnalysed) { + return this.usedBranch; } + this.isBranchResolutionAnalysed = true; + const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this); + return testValue === UnknownValue + ? null + : (this.usedBranch = testValue ? this.consequent : this.alternate); } } -class DoWhileStatement extends NodeBase { - hasEffects(options) { - return (this.test.hasEffects(options) || this.body.hasEffects(options.setIgnoreBreakStatements())); +class ContinueStatement extends NodeBase { + hasEffects(context) { + if (this.label) { + if (!context.ignore.labels.has(this.label.name)) + return true; + context.includedLabels.add(this.label.name); + context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL; + } + else { + if (!context.ignore.continues) + return true; + context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE; + } + return false; } + include(context) { + this.included = true; + if (this.label) { + this.label.include(context); + context.includedLabels.add(this.label.name); + } + context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE; + } } -class EmptyStatement extends NodeBase { - hasEffects() { +class DoWhileStatement extends NodeBase { + hasEffects(context) { + if (this.test.hasEffects(context)) + return true; + const { brokenFlow, ignore: { breaks, continues } } = context; + context.ignore.breaks = true; + context.ignore.continues = true; + if (this.body.hasEffects(context)) + return true; + context.ignore.breaks = breaks; + context.ignore.continues = continues; + context.brokenFlow = brokenFlow; return false; } + include(context, includeChildrenRecursively) { + this.included = true; + this.test.include(context, includeChildrenRecursively); + const { brokenFlow } = context; + this.body.include(context, includeChildrenRecursively); + context.brokenFlow = brokenFlow; + } } -class ExportAllDeclaration$1 extends NodeBase { +class EmptyStatement extends NodeBase { hasEffects() { return false; } - initialise() { - this.context.addExport(this); - } - render(code, _options, { start, end } = BLANK) { - code.remove(start, end); - } } -ExportAllDeclaration$1.prototype.needsBoundaries = true; class ExportNamedDeclaration extends NodeBase { bind() { // Do not bind specifiers if (this.declaration !== null) this.declaration.bind(); } - hasEffects(options) { - return this.declaration !== null && this.declaration.hasEffects(options); + hasEffects(context) { + return this.declaration !== null && this.declaration.hasEffects(context); } initialise() { this.context.addExport(this); } - render(code, options, { start, end } = BLANK) { + render(code, options, nodeRenderOptions) { + const { start, end } = nodeRenderOptions; if (this.declaration === null) { code.remove(start, end); } else { code.remove(this.start, this.declaration.start); @@ -10842,27 +7213,42 @@ this.body.bind(); } createScope(parentScope) { this.scope = new BlockScope(parentScope); } - hasEffects(options) { - return ((this.left && - (this.left.hasEffects(options) || - this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))) || - (this.right && this.right.hasEffects(options)) || - this.body.hasEffects(options.setIgnoreBreakStatements())); + hasEffects(context) { + if ((this.left && + (this.left.hasEffects(context) || + this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))) || + (this.right && this.right.hasEffects(context))) + return true; + const { brokenFlow, ignore: { breaks, continues } } = context; + context.ignore.breaks = true; + context.ignore.continues = true; + if (this.body.hasEffects(context)) + return true; + context.ignore.breaks = breaks; + context.ignore.continues = continues; + context.brokenFlow = brokenFlow; + return false; } - include(includeChildrenRecursively) { + include(context, includeChildrenRecursively) { this.included = true; - this.left.includeWithAllDeclaredVariables(includeChildrenRecursively); + this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context); this.left.deoptimizePath(EMPTY_PATH); - this.right.include(includeChildrenRecursively); - this.body.include(includeChildrenRecursively); + this.right.include(context, includeChildrenRecursively); + const { brokenFlow } = context; + this.body.include(context, includeChildrenRecursively); + context.brokenFlow = brokenFlow; } 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); } } class ForOfStatement extends NodeBase { @@ -10873,41 +7259,65 @@ this.body.bind(); } createScope(parentScope) { this.scope = new BlockScope(parentScope); } - hasEffects(options) { - return ((this.left && - (this.left.hasEffects(options) || - this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))) || - (this.right && this.right.hasEffects(options)) || - this.body.hasEffects(options.setIgnoreBreakStatements())); + hasEffects() { + // Placeholder until proper Symbol.Iterator support + return true; } - include(includeChildrenRecursively) { + include(context, includeChildrenRecursively) { this.included = true; - this.left.includeWithAllDeclaredVariables(includeChildrenRecursively); + this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context); this.left.deoptimizePath(EMPTY_PATH); - this.right.include(includeChildrenRecursively); - this.body.include(includeChildrenRecursively); + this.right.include(context, includeChildrenRecursively); + const { brokenFlow } = context; + this.body.include(context, includeChildrenRecursively); + context.brokenFlow = brokenFlow; } 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); } } class ForStatement extends NodeBase { createScope(parentScope) { this.scope = new BlockScope(parentScope); } - hasEffects(options) { - return ((this.init && this.init.hasEffects(options)) || - (this.test && this.test.hasEffects(options)) || - (this.update && this.update.hasEffects(options)) || - this.body.hasEffects(options.setIgnoreBreakStatements())); + hasEffects(context) { + if ((this.init && this.init.hasEffects(context)) || + (this.test && this.test.hasEffects(context)) || + (this.update && this.update.hasEffects(context))) + return true; + const { brokenFlow, ignore: { breaks, continues } } = context; + context.ignore.breaks = true; + context.ignore.continues = true; + if (this.body.hasEffects(context)) + return true; + context.ignore.breaks = breaks; + context.ignore.continues = continues; + context.brokenFlow = brokenFlow; + return false; } + include(context, includeChildrenRecursively) { + this.included = true; + if (this.init) + this.init.include(context, includeChildrenRecursively); + if (this.test) + this.test.include(context, includeChildrenRecursively); + const { brokenFlow } = context; + if (this.update) + this.update.include(context, includeChildrenRecursively); + this.body.include(context, includeChildrenRecursively); + context.brokenFlow = brokenFlow; + } render(code, options) { if (this.init) this.init.render(code, options, NO_SEMICOLON); if (this.test) this.test.render(code, options, NO_SEMICOLON); @@ -10918,79 +7328,74 @@ } class FunctionExpression$1 extends FunctionNode { } +const unset = Symbol('unset'); class IfStatement extends NodeBase { constructor() { super(...arguments); - this.isTestValueAnalysed = false; + this.testValue = unset; } - bind() { - super.bind(); - if (!this.isTestValueAnalysed) { - this.testValue = UNKNOWN_VALUE; - this.isTestValueAnalysed = true; - this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this); - } - } deoptimizeCache() { - this.testValue = UNKNOWN_VALUE; + this.testValue = UnknownValue; } - hasEffects(options) { - if (this.test.hasEffects(options)) + hasEffects(context) { + if (this.test.hasEffects(context)) { return true; - if (this.testValue === UNKNOWN_VALUE) { - return (this.consequent.hasEffects(options) || - (this.alternate !== null && this.alternate.hasEffects(options))); } - return this.testValue - ? this.consequent.hasEffects(options) - : this.alternate !== null && this.alternate.hasEffects(options); + const testValue = this.getTestValue(); + if (testValue === UnknownValue) { + const { brokenFlow } = context; + if (this.consequent.hasEffects(context)) + return true; + const consequentBrokenFlow = context.brokenFlow; + context.brokenFlow = brokenFlow; + if (this.alternate === null) + return false; + if (this.alternate.hasEffects(context)) + return true; + context.brokenFlow = + context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow; + return false; + } + return testValue + ? this.consequent.hasEffects(context) + : this.alternate !== null && this.alternate.hasEffects(context); } - include(includeChildrenRecursively) { + include(context, includeChildrenRecursively) { this.included = true; if (includeChildrenRecursively) { - this.test.include(includeChildrenRecursively); - this.consequent.include(includeChildrenRecursively); - if (this.alternate !== null) { - this.alternate.include(includeChildrenRecursively); + this.includeRecursively(includeChildrenRecursively, context); + } + else { + const testValue = this.getTestValue(); + if (testValue === UnknownValue) { + this.includeUnknownTest(context); } - return; + else { + this.includeKnownTest(context, testValue); + } } - const hasUnknownTest = this.testValue === UNKNOWN_VALUE; - if (hasUnknownTest || this.test.shouldBeIncluded()) { - this.test.include(false); - } - if ((hasUnknownTest || this.testValue) && this.consequent.shouldBeIncluded()) { - this.consequent.include(false); - } - if (this.alternate !== null && - ((hasUnknownTest || !this.testValue) && this.alternate.shouldBeIncluded())) { - this.alternate.include(false); - } } render(code, options) { // Note that unknown test values are always included + const testValue = this.getTestValue(); if (!this.test.included && - (this.testValue - ? this.alternate === null || !this.alternate.included - : !this.consequent.included)) { - const singleRetainedBranch = (this.testValue - ? this.consequent - : this.alternate); + (testValue ? this.alternate === null || !this.alternate.included : !this.consequent.included)) { + const singleRetainedBranch = (testValue ? this.consequent : this.alternate); code.remove(this.start, singleRetainedBranch.start); code.remove(singleRetainedBranch.end, this.end); removeAnnotations(this, code); singleRetainedBranch.render(code, options); } else { if (this.test.included) { this.test.render(code, options); } else { - code.overwrite(this.test.start, this.test.end, this.testValue ? 'true' : 'false'); + code.overwrite(this.test.start, this.test.end, testValue ? 'true' : 'false'); } if (this.consequent.included) { this.consequent.render(code, options); } else { @@ -11004,22 +7409,61 @@ code.remove(this.consequent.end, this.alternate.end); } } } } + 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); + } + if (this.alternate !== null && !testValue && this.alternate.shouldBeIncluded(context)) { + this.alternate.include(context, false); + } + } + includeRecursively(includeChildrenRecursively, context) { + this.test.include(context, includeChildrenRecursively); + this.consequent.include(context, includeChildrenRecursively); + if (this.alternate !== null) { + this.alternate.include(context, includeChildrenRecursively); + } + } + includeUnknownTest(context) { + this.test.include(context, false); + const { brokenFlow } = context; + let consequentBrokenFlow = BROKEN_FLOW_NONE; + if (this.consequent.shouldBeIncluded(context)) { + this.consequent.include(context, false); + consequentBrokenFlow = context.brokenFlow; + context.brokenFlow = brokenFlow; + } + if (this.alternate !== null && this.alternate.shouldBeIncluded(context)) { + this.alternate.include(context, false); + context.brokenFlow = + context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow; + } + } } class ImportDeclaration extends NodeBase { bind() { } hasEffects() { return false; } initialise() { this.context.addImport(this); } - render(code, _options, { start, end } = BLANK) { - code.remove(start, end); + render(code, _options, nodeRenderOptions) { + code.remove(nodeRenderOptions.start, nodeRenderOptions.end); } } ImportDeclaration.prototype.needsBoundaries = true; class Import extends NodeBase { @@ -11028,16 +7472,17 @@ this.exportMode = 'auto'; } hasEffects() { return true; } - include(includeChildrenRecursively) { + include(context, includeChildrenRecursively) { if (!this.included) { this.included = true; this.context.includeDynamicImport(this); + this.scope.addAccessedDynamicImport(this); } - this.source.include(includeChildrenRecursively); + this.source.include(context, includeChildrenRecursively); } initialise() { this.context.addDynamicImport(this); } render(code, options) { @@ -11134,54 +7579,40 @@ return null; } } class LabeledStatement extends NodeBase { - hasEffects(options) { - return this.body.hasEffects(options.setIgnoreLabel(this.label.name).setIgnoreBreakStatements()); - } -} - -class Literal extends NodeBase { - 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 UNKNOWN_VALUE; + 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 this.value; + return false; } - getReturnExpressionWhenCalledAtPath(path) { - if (path.length !== 1) - return UNKNOWN_EXPRESSION; - return getMemberReturnExpressionWhenCalled(this.members, path[0]); - } - hasEffectsWhenAccessedAtPath(path) { - if (this.value === null) { - return path.length > 0; + include(context, includeChildrenRecursively) { + this.included = true; + const brokenFlow = context.brokenFlow; + this.body.include(context, includeChildrenRecursively); + if (context.includedLabels.has(this.label.name)) { + this.label.include(context); + context.includedLabels.delete(this.label.name); + context.brokenFlow = brokenFlow; } - return path.length > 1; } - hasEffectsWhenAssignedAtPath(path) { - return path.length > 0; - } - hasEffectsWhenCalledAtPath(path, callOptions, options) { - if (path.length === 1) { - return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, options); + render(code, options) { + if (this.label.included) { + this.label.render(code, options); } - return true; - } - initialise() { - this.members = getLiteralMembersForValue(this.value); - } - render(code, _options) { - if (typeof this.value === 'string') { - code.indentExclusionRanges.push([this.start + 1, this.end - 1]); + else { + code.remove(this.start, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1); } + this.body.render(code, options); } } class LogicalExpression extends NodeBase { constructor() { @@ -11189,100 +7620,99 @@ // We collect deoptimization information if usedBranch !== null this.expressionsToBeDeoptimized = []; this.isBranchResolutionAnalysed = false; this.unusedBranch = null; this.usedBranch = null; + this.wasPathDeoptimizedWhileOptimized = false; } bind() { super.bind(); - if (!this.isBranchResolutionAnalysed) - this.analyseBranchResolution(); + // ensure the usedBranch is set for the tree-shaking passes + this.getUsedBranch(); } deoptimizeCache() { if (this.usedBranch !== null) { - // We did not track if there were reassignments to any of the branches. - // Also, the return values might need reassignment. this.usedBranch = null; - this.unusedBranch.deoptimizePath(UNKNOWN_PATH); - for (const expression of this.expressionsToBeDeoptimized) { + const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized; + this.expressionsToBeDeoptimized = []; + if (this.wasPathDeoptimizedWhileOptimized) { + this.unusedBranch.deoptimizePath(UNKNOWN_PATH); + } + for (const expression of expressionsToBeDeoptimized) { expression.deoptimizeCache(); } } } deoptimizePath(path) { - if (path.length > 0) { - if (!this.isBranchResolutionAnalysed) - this.analyseBranchResolution(); - if (this.usedBranch === null) { - this.left.deoptimizePath(path); - this.right.deoptimizePath(path); - } - else { - this.usedBranch.deoptimizePath(path); - } + const usedBranch = this.getUsedBranch(); + if (usedBranch === null) { + this.left.deoptimizePath(path); + this.right.deoptimizePath(path); } + else { + this.wasPathDeoptimizedWhileOptimized = true; + usedBranch.deoptimizePath(path); + } } getLiteralValueAtPath(path, recursionTracker, origin) { - if (!this.isBranchResolutionAnalysed) - this.analyseBranchResolution(); - if (this.usedBranch === null) - return UNKNOWN_VALUE; + const usedBranch = this.getUsedBranch(); + if (usedBranch === null) + return UnknownValue; this.expressionsToBeDeoptimized.push(origin); - return this.usedBranch.getLiteralValueAtPath(path, recursionTracker, origin); + return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin); } getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) { - if (!this.isBranchResolutionAnalysed) - this.analyseBranchResolution(); - if (this.usedBranch === null) + const usedBranch = this.getUsedBranch(); + if (usedBranch === null) return new MultiExpression([ this.left.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin), this.right.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) ]); this.expressionsToBeDeoptimized.push(origin); - return this.usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin); + return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin); } - hasEffects(options) { + hasEffects(context) { if (this.usedBranch === null) { - return this.left.hasEffects(options) || this.right.hasEffects(options); + return this.left.hasEffects(context) || this.right.hasEffects(context); } - return this.usedBranch.hasEffects(options); + return this.usedBranch.hasEffects(context); } - hasEffectsWhenAccessedAtPath(path, options) { + hasEffectsWhenAccessedAtPath(path, context) { if (path.length === 0) return false; if (this.usedBranch === null) { - return (this.left.hasEffectsWhenAccessedAtPath(path, options) || - this.right.hasEffectsWhenAccessedAtPath(path, options)); + return (this.left.hasEffectsWhenAccessedAtPath(path, context) || + this.right.hasEffectsWhenAccessedAtPath(path, context)); } - return this.usedBranch.hasEffectsWhenAccessedAtPath(path, options); + return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context); } - hasEffectsWhenAssignedAtPath(path, options) { + hasEffectsWhenAssignedAtPath(path, context) { if (path.length === 0) return true; if (this.usedBranch === null) { - return (this.left.hasEffectsWhenAssignedAtPath(path, options) || - this.right.hasEffectsWhenAssignedAtPath(path, options)); + return (this.left.hasEffectsWhenAssignedAtPath(path, context) || + this.right.hasEffectsWhenAssignedAtPath(path, context)); } - return this.usedBranch.hasEffectsWhenAssignedAtPath(path, options); + return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context); } - hasEffectsWhenCalledAtPath(path, callOptions, options) { + hasEffectsWhenCalledAtPath(path, callOptions, context) { if (this.usedBranch === null) { - return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, options) || - this.right.hasEffectsWhenCalledAtPath(path, callOptions, options)); + return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, context) || + this.right.hasEffectsWhenCalledAtPath(path, callOptions, context)); } - return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, options); + return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context); } - include(includeChildrenRecursively) { + include(context, includeChildrenRecursively) { this.included = true; if (includeChildrenRecursively || this.usedBranch === null || - this.unusedBranch.shouldBeIncluded()) { - this.left.include(includeChildrenRecursively); - this.right.include(includeChildrenRecursively); + this.unusedBranch.shouldBeIncluded(context)) { + this.left.include(context, includeChildrenRecursively); + this.right.include(context, includeChildrenRecursively); } else { - this.usedBranch.include(includeChildrenRecursively); + this.usedBranch.include(context, includeChildrenRecursively); } } render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) { if (!this.left.included || !this.right.included) { const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end); @@ -11305,244 +7735,30 @@ } else { super.render(code, options); } } - analyseBranchResolution() { - this.isBranchResolutionAnalysed = true; - const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this); - if (leftValue !== UNKNOWN_VALUE) { - if (this.operator === '||' ? leftValue : !leftValue) { - this.usedBranch = this.left; - this.unusedBranch = this.right; + getUsedBranch() { + if (!this.isBranchResolutionAnalysed) { + this.isBranchResolutionAnalysed = true; + const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this); + if (leftValue === UnknownValue) { + return null; } else { - this.usedBranch = this.right; - this.unusedBranch = this.left; - } - } - } -} - -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$1) { - 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 { - constructor() { - super(...arguments); - this.variable = null; - this.bound = false; - this.expressionsToBeDeoptimized = []; - this.replacement = null; - } - addExportedVariables() { } - bind() { - if (this.bound) - return; - this.bound = true; - const path = getPathIfNotComputed(this); - const baseVariable = path && this.scope.findVariable(path[0].key); - if (baseVariable && baseVariable.isNamespace) { - const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1)); - if (!resolvedVariable) { - super.bind(); - } - else if (typeof resolvedVariable === 'string') { - this.replacement = resolvedVariable; - } - else { - if (resolvedVariable instanceof ExternalVariable && resolvedVariable.module) { - resolvedVariable.module.suggestName(path[0].key); + if (this.operator === '||' ? leftValue : !leftValue) { + this.usedBranch = this.left; + this.unusedBranch = this.right; } - this.variable = resolvedVariable; - this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable); + else { + this.usedBranch = this.right; + this.unusedBranch = this.left; + } } } - else { - super.bind(); - if (this.propertyKey === null) - this.analysePropertyKey(); - } + return this.usedBranch; } - deoptimizeCache() { - for (const expression of this.expressionsToBeDeoptimized) { - expression.deoptimizeCache(); - } - } - deoptimizePath(path) { - if (!this.bound) - this.bind(); - if (path.length === 0) - this.disallowNamespaceReassignment(); - if (this.variable) { - this.variable.deoptimizePath(path); - } - else { - if (this.propertyKey === null) - this.analysePropertyKey(); - this.object.deoptimizePath([this.propertyKey, ...path]); - } - } - getLiteralValueAtPath(path, recursionTracker, origin) { - if (!this.bound) - this.bind(); - if (this.variable !== null) { - return this.variable.getLiteralValueAtPath(path, recursionTracker, origin); - } - if (this.propertyKey === null) - this.analysePropertyKey(); - this.expressionsToBeDeoptimized.push(origin); - return this.object.getLiteralValueAtPath([this.propertyKey, ...path], recursionTracker, origin); - } - getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) { - if (!this.bound) - this.bind(); - if (this.variable !== null) { - return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin); - } - if (this.propertyKey === null) - this.analysePropertyKey(); - this.expressionsToBeDeoptimized.push(origin); - return this.object.getReturnExpressionWhenCalledAtPath([this.propertyKey, ...path], recursionTracker, origin); - } - hasEffects(options) { - return (this.property.hasEffects(options) || - this.object.hasEffects(options) || - (this.context.propertyReadSideEffects && - this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], options))); - } - hasEffectsWhenAccessedAtPath(path, options) { - if (path.length === 0) { - return false; - } - if (this.variable !== null) { - return this.variable.hasEffectsWhenAccessedAtPath(path, options); - } - return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey, ...path], options); - } - hasEffectsWhenAssignedAtPath(path, options) { - if (this.variable !== null) { - return this.variable.hasEffectsWhenAssignedAtPath(path, options); - } - return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey, ...path], options); - } - hasEffectsWhenCalledAtPath(path, callOptions, options) { - if (this.variable !== null) { - return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, options); - } - return this.object.hasEffectsWhenCalledAtPath([this.propertyKey, ...path], callOptions, options); - } - include(includeChildrenRecursively) { - if (!this.included) { - this.included = true; - if (this.variable !== null) { - this.context.includeVariable(this.variable); - } - } - this.object.include(includeChildrenRecursively); - this.property.include(includeChildrenRecursively); - } - includeCallArguments(args) { - if (this.variable) { - this.variable.includeCallArguments(args); - } - else { - super.includeCallArguments(args); - } - } - initialise() { - this.propertyKey = getResolvablePropertyKey(this); - } - render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) { - const isCalleeOfDifferentParent = renderedParentType === CallExpression && isCalleeOfRenderedParent; - if (this.variable || this.replacement) { - let replacement = this.variable ? this.variable.getName() : this.replacement; - if (isCalleeOfDifferentParent) - replacement = '0, ' + replacement; - code.overwrite(this.start, this.end, replacement, { - contentOnly: true, - storeName: true - }); - } - else { - if (isCalleeOfDifferentParent) { - code.appendRight(this.start, '0, '); - } - super.render(code, options); - } - } - analysePropertyKey() { - this.propertyKey = UNKNOWN_KEY; - const value = this.property.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this); - this.propertyKey = value === UNKNOWN_VALUE ? UNKNOWN_KEY : String(value); - } - disallowNamespaceReassignment() { - if (this.object instanceof Identifier$1 && - this.scope.findVariable(this.object.name).isNamespace) { - this.context.error({ - code: 'ILLEGAL_NAMESPACE_REASSIGNMENT', - message: `Illegal reassignment to import '${this.object.name}'` - }, this.start); - } - } - resolveNamespaceVariables(baseVariable, path) { - if (path.length === 0) - return baseVariable; - if (!baseVariable.isNamespace) - return null; - const exportName = path[0].key; - const variable = baseVariable instanceof ExternalVariable - ? baseVariable.module.getVariableForExportName(exportName) - : baseVariable.context.traceExport(exportName); - if (!variable) { - const fileName = baseVariable instanceof ExternalVariable - ? baseVariable.module.id - : baseVariable.context.fileName; - this.context.warn({ - code: 'MISSING_EXPORT', - exporter: relativeId(fileName), - importer: relativeId(this.context.fileName), - message: `'${exportName}' is not exported by '${relativeId(fileName)}'`, - missing: exportName, - url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module` - }, path[0].pos); - return 'undefined'; - } - return this.resolveNamespaceVariables(variable, path.slice(1)); - } } const readFile = (file) => new Promise((fulfil, reject) => readFile$1(file, 'utf-8', (err, contents) => (err ? reject(err) : fulfil(contents)))); function mkdirpath(path) { const dir = dirname(path); @@ -11697,28 +7913,27 @@ const parent = this.parent; const metaProperty = (this.metaProperty = parent instanceof MemberExpression && typeof parent.propertyKey === 'string' ? parent.propertyKey : null); - if (metaProperty) { - if (metaProperty === 'url') { - this.scope.addAccessedGlobalsByFormat(accessedMetaUrlGlobals); - } - else if (metaProperty.startsWith(FILE_PREFIX) || + if (metaProperty && + (metaProperty.startsWith(FILE_PREFIX) || metaProperty.startsWith(ASSET_PREFIX) || - metaProperty.startsWith(CHUNK_PREFIX)) { - this.scope.addAccessedGlobalsByFormat(accessedFileUrlGlobals); - } + metaProperty.startsWith(CHUNK_PREFIX))) { + this.scope.addAccessedGlobalsByFormat(accessedFileUrlGlobals); } + else { + this.scope.addAccessedGlobalsByFormat(accessedMetaUrlGlobals); + } } } initialise() { if (this.meta.name === 'import') { this.context.addImportMeta(this); } } - renderFinalMechanism(code, chunkId, format, pluginDriver) { + renderFinalMechanism(code, chunkId, format, outputPluginDriver) { if (!this.included) return; const parent = this.parent; const metaProperty = this.metaProperty; if (metaProperty && @@ -11729,37 +7944,37 @@ let assetReferenceId = null; let chunkReferenceId = null; let fileName; if (metaProperty.startsWith(FILE_PREFIX)) { referenceId = metaProperty.substr(FILE_PREFIX.length); - fileName = this.context.getFileName(referenceId); + fileName = outputPluginDriver.getFileName(referenceId); } else if (metaProperty.startsWith(ASSET_PREFIX)) { this.context.warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, false); assetReferenceId = metaProperty.substr(ASSET_PREFIX.length); - fileName = this.context.getFileName(assetReferenceId); + fileName = outputPluginDriver.getFileName(assetReferenceId); } else { this.context.warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, false); chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length); - fileName = this.context.getFileName(chunkReferenceId); + fileName = outputPluginDriver.getFileName(chunkReferenceId); } const relativePath = normalize(relative$1(dirname(chunkId), fileName)); let replacement; if (assetReferenceId !== null) { - replacement = pluginDriver.hookFirstSync('resolveAssetUrl', [ + replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [ { assetFileName: fileName, chunkId, format, moduleId: this.context.module.id, relativeAssetPath: relativePath } ]); } if (!replacement) { - replacement = pluginDriver.hookFirstSync('resolveFileUrl', [ + replacement = outputPluginDriver.hookFirstSync('resolveFileUrl', [ { assetReferenceId, chunkId, chunkReferenceId, fileName, @@ -11771,11 +7986,11 @@ ]); } code.overwrite(parent.start, parent.end, replacement, { contentOnly: true }); return; } - const replacement = pluginDriver.hookFirstSync('resolveImportMeta', [ + const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [ metaProperty, { chunkId, format, moduleId: this.context.module.id @@ -11791,15 +8006,15 @@ } } } class MethodDefinition extends NodeBase { - hasEffects(options) { - return this.key.hasEffects(options); + hasEffects(context) { + return this.key.hasEffects(context); } - hasEffectsWhenCalledAtPath(path, callOptions, options) { - return (path.length > 0 || this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, options)); + hasEffectsWhenCalledAtPath(path, callOptions, context) { + return (path.length > 0 || this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context)); } } class NewExpression extends NodeBase { bind() { @@ -11807,37 +8022,37 @@ for (const argument of this.arguments) { // This will make sure all properties of parameters behave as "unknown" argument.deoptimizePath(UNKNOWN_PATH); } } - hasEffects(options) { + hasEffects(context) { for (const argument of this.arguments) { - if (argument.hasEffects(options)) + if (argument.hasEffects(context)) return true; } - if (this.annotatedPure) + if (this.context.annotations && this.annotatedPure) return false; - return this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, options.getHasEffectsWhenCalledOptions()); + return (this.callee.hasEffects(context) || + this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context)); } - hasEffectsWhenAccessedAtPath(path, _options) { + hasEffectsWhenAccessedAtPath(path) { return path.length > 1; } initialise() { - this.callOptions = CallOptions.create({ + this.callOptions = { args: this.arguments, - callIdentifier: this, withNew: true - }); + }; } } class SpreadElement extends NodeBase { bind() { super.bind(); // Only properties of properties of the argument could become subject to reassignment // This will also reassign the return values of iterators - this.argument.deoptimizePath([UNKNOWN_KEY, UNKNOWN_KEY]); + this.argument.deoptimizePath([UnknownKey, UnknownKey]); } } class ObjectExpression extends NodeBase { constructor() { @@ -11850,27 +8065,22 @@ this.unmatchablePropertiesRead = []; this.unmatchablePropertiesWrite = []; } bind() { super.bind(); - if (this.propertyMap === null) - this.buildPropertyMap(); + // ensure the propertyMap is set for the tree-shaking passes + this.getPropertyMap(); } // We could also track this per-property but this would quickly become much more complex deoptimizeCache() { if (!this.hasUnknownDeoptimizedProperty) this.deoptimizeAllProperties(); } deoptimizePath(path) { if (this.hasUnknownDeoptimizedProperty) return; - if (this.propertyMap === null) - this.buildPropertyMap(); - if (path.length === 0) { - this.deoptimizeAllProperties(); - return; - } + const propertyMap = this.getPropertyMap(); const key = path[0]; if (path.length === 1) { if (typeof key !== 'string') { this.deoptimizeAllProperties(); return; @@ -11887,171 +8097,180 @@ } } } const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1); for (const property of typeof key === 'string' - ? this.propertyMap[key] - ? this.propertyMap[key].propertiesRead + ? propertyMap[key] + ? propertyMap[key].propertiesRead : [] : this.properties) { property.deoptimizePath(subPath); } } getLiteralValueAtPath(path, recursionTracker, origin) { - if (this.propertyMap === null) - this.buildPropertyMap(); + const propertyMap = this.getPropertyMap(); const key = path[0]; if (path.length === 0 || this.hasUnknownDeoptimizedProperty || typeof key !== 'string' || this.deoptimizedPaths.has(key)) - return UNKNOWN_VALUE; + return UnknownValue; if (path.length === 1 && - !this.propertyMap[key] && + !propertyMap[key] && !objectMembers[key] && - (this.unmatchablePropertiesRead).length === 0) { + this.unmatchablePropertiesRead.length === 0) { const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key); if (expressionsToBeDeoptimized) { expressionsToBeDeoptimized.push(origin); } else { this.expressionsToBeDeoptimized.set(key, [origin]); } return undefined; } - if (!this.propertyMap[key] || - this.propertyMap[key].exactMatchRead === null || - this.propertyMap[key].propertiesRead.length > 1) { - return UNKNOWN_VALUE; + if (!propertyMap[key] || + propertyMap[key].exactMatchRead === null || + propertyMap[key].propertiesRead.length > 1) { + return UnknownValue; } const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key); if (expressionsToBeDeoptimized) { expressionsToBeDeoptimized.push(origin); } else { this.expressionsToBeDeoptimized.set(key, [origin]); } - return this.propertyMap[key] - .exactMatchRead.getLiteralValueAtPath(path.slice(1), recursionTracker, origin); + return propertyMap[key].exactMatchRead.getLiteralValueAtPath(path.slice(1), recursionTracker, origin); } getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) { - if (this.propertyMap === null) - this.buildPropertyMap(); + const propertyMap = this.getPropertyMap(); const key = path[0]; if (path.length === 0 || this.hasUnknownDeoptimizedProperty || typeof key !== 'string' || this.deoptimizedPaths.has(key)) return UNKNOWN_EXPRESSION; if (path.length === 1 && objectMembers[key] && this.unmatchablePropertiesRead.length === 0 && - (!this.propertyMap[key] || - this.propertyMap[key].exactMatchRead === null)) + (!propertyMap[key] || propertyMap[key].exactMatchRead === null)) return getMemberReturnExpressionWhenCalled(objectMembers, key); - if (!this.propertyMap[key] || - this.propertyMap[key].exactMatchRead === null || - this.propertyMap[key].propertiesRead.length > 1) + if (!propertyMap[key] || + propertyMap[key].exactMatchRead === null || + propertyMap[key].propertiesRead.length > 1) return UNKNOWN_EXPRESSION; const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key); if (expressionsToBeDeoptimized) { expressionsToBeDeoptimized.push(origin); } else { this.expressionsToBeDeoptimized.set(key, [origin]); } - return this.propertyMap[key] - .exactMatchRead.getReturnExpressionWhenCalledAtPath(path.slice(1), recursionTracker, origin); + return propertyMap[key].exactMatchRead.getReturnExpressionWhenCalledAtPath(path.slice(1), recursionTracker, origin); } - hasEffectsWhenAccessedAtPath(path, options) { + hasEffectsWhenAccessedAtPath(path, context) { if (path.length === 0) return false; const key = path[0]; + const propertyMap = this.propertyMap; if (path.length > 1 && (this.hasUnknownDeoptimizedProperty || typeof key !== 'string' || this.deoptimizedPaths.has(key) || - !this.propertyMap[key] || - this.propertyMap[key].exactMatchRead === null)) + !propertyMap[key] || + propertyMap[key].exactMatchRead === null)) return true; const subPath = path.slice(1); for (const property of typeof key !== 'string' ? this.properties - : this.propertyMap[key] - ? this.propertyMap[key].propertiesRead + : propertyMap[key] + ? propertyMap[key].propertiesRead : []) { - if (property.hasEffectsWhenAccessedAtPath(subPath, options)) + if (property.hasEffectsWhenAccessedAtPath(subPath, context)) return true; } return false; } - hasEffectsWhenAssignedAtPath(path, options) { - if (path.length === 0) - return false; + hasEffectsWhenAssignedAtPath(path, context) { const key = path[0]; + const propertyMap = this.propertyMap; if (path.length > 1 && (this.hasUnknownDeoptimizedProperty || - typeof key !== 'string' || this.deoptimizedPaths.has(key) || - !this.propertyMap[key] || - this.propertyMap[key].exactMatchRead === null)) + !propertyMap[key] || + propertyMap[key].exactMatchRead === null)) { return true; + } const subPath = path.slice(1); for (const property of typeof key !== 'string' ? this.properties : path.length > 1 - ? this.propertyMap[key].propertiesRead - : this.propertyMap[key] - ? this.propertyMap[key].propertiesSet + ? propertyMap[key].propertiesRead + : propertyMap[key] + ? propertyMap[key].propertiesWrite : []) { - if (property.hasEffectsWhenAssignedAtPath(subPath, options)) + if (property.hasEffectsWhenAssignedAtPath(subPath, context)) return true; } return false; } - hasEffectsWhenCalledAtPath(path, callOptions, options) { + hasEffectsWhenCalledAtPath(path, callOptions, context) { const key = path[0]; - if (path.length === 0 || + if (typeof key !== 'string' || this.hasUnknownDeoptimizedProperty || - typeof key !== 'string' || this.deoptimizedPaths.has(key) || (this.propertyMap[key] ? !this.propertyMap[key].exactMatchRead - : path.length > 1 || !objectMembers[key])) + : path.length > 1 || !objectMembers[key])) { return true; + } const subPath = path.slice(1); - for (const property of this.propertyMap[key] - ? this.propertyMap[key].propertiesRead - : []) { - if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, options)) - return true; + if (this.propertyMap[key]) { + for (const property of this.propertyMap[key].propertiesRead) { + if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, context)) + return true; + } } if (path.length === 1 && objectMembers[key]) - return hasMemberEffectWhenCalled(objectMembers, key, this.included, callOptions, options); + return hasMemberEffectWhenCalled(objectMembers, key, this.included, callOptions, context); return false; } render(code, options, { renderedParentType } = BLANK) { super.render(code, options); if (renderedParentType === ExpressionStatement) { code.appendRight(this.start, '('); code.prependLeft(this.end, ')'); } } - buildPropertyMap() { - this.propertyMap = Object.create(null); + deoptimizeAllProperties() { + this.hasUnknownDeoptimizedProperty = true; + for (const property of this.properties) { + property.deoptimizePath(UNKNOWN_PATH); + } + for (const expressionsToBeDeoptimized of this.expressionsToBeDeoptimized.values()) { + for (const expression of expressionsToBeDeoptimized) { + expression.deoptimizeCache(); + } + } + } + getPropertyMap() { + if (this.propertyMap !== null) { + return this.propertyMap; + } + const propertyMap = (this.propertyMap = Object.create(null)); for (let index = this.properties.length - 1; index >= 0; index--) { const property = this.properties[index]; if (property instanceof SpreadElement) { this.unmatchablePropertiesRead.push(property); continue; } const isWrite = property.kind !== 'get'; const isRead = property.kind !== 'set'; let key; if (property.computed) { - const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this); - if (keyValue === UNKNOWN_VALUE) { + const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this); + if (keyValue === UnknownValue) { if (isRead) { this.unmatchablePropertiesRead.push(property); } else { this.unmatchablePropertiesWrite.push(property); @@ -12064,41 +8283,31 @@ key = property.key.name; } else { key = String(property.key.value); } - const propertyMapProperty = this.propertyMap[key]; + const propertyMapProperty = propertyMap[key]; if (!propertyMapProperty) { - this.propertyMap[key] = { + propertyMap[key] = { exactMatchRead: isRead ? property : null, exactMatchWrite: isWrite ? property : null, propertiesRead: isRead ? [property, ...this.unmatchablePropertiesRead] : [], - propertiesSet: isWrite && !isRead ? [property, ...this.unmatchablePropertiesWrite] : [] + propertiesWrite: isWrite && !isRead ? [property, ...this.unmatchablePropertiesWrite] : [] }; continue; } if (isRead && propertyMapProperty.exactMatchRead === null) { propertyMapProperty.exactMatchRead = property; propertyMapProperty.propertiesRead.push(property, ...this.unmatchablePropertiesRead); } if (isWrite && !isRead && propertyMapProperty.exactMatchWrite === null) { propertyMapProperty.exactMatchWrite = property; - propertyMapProperty.propertiesSet.push(property, ...this.unmatchablePropertiesWrite); + propertyMapProperty.propertiesWrite.push(property, ...this.unmatchablePropertiesWrite); } } + return propertyMap; } - deoptimizeAllProperties() { - this.hasUnknownDeoptimizedProperty = true; - for (const property of this.properties) { - property.deoptimizePath(UNKNOWN_PATH); - } - for (const expressionsToBeDeoptimized of this.expressionsToBeDeoptimized.values()) { - for (const expression of expressionsToBeDeoptimized) { - expression.deoptimizeCache(); - } - } - } } class ObjectPattern extends NodeBase { addExportedVariables(variables) { for (const property of this.properties) { @@ -12122,34 +8331,34 @@ for (const property of this.properties) { property.deoptimizePath(path); } } } - hasEffectsWhenAssignedAtPath(path, options) { + hasEffectsWhenAssignedAtPath(path, context) { if (path.length > 0) return true; for (const property of this.properties) { - if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options)) + if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)) return true; } return false; } } class Program$1 extends NodeBase { - hasEffects(options) { + hasEffects(context) { for (const node of this.body) { - if (node.hasEffects(options)) + if (node.hasEffects(context)) return true; } return false; } - include(includeChildrenRecursively) { + include(context, includeChildrenRecursively) { this.included = true; for (const node of this.body) { - if (includeChildrenRecursively || node.shouldBeIncluded()) { - node.include(includeChildrenRecursively); + if (includeChildrenRecursively || node.shouldBeIncluded(context)) { + node.include(context, includeChildrenRecursively); } } } render(code, options) { if (this.body.length) { @@ -12167,110 +8376,124 @@ this.declarationInit = null; this.returnExpression = null; } bind() { super.bind(); - if (this.kind === 'get' && this.returnExpression === null) - this.updateReturnExpression(); + if (this.kind === 'get') { + // ensure the returnExpression is set for the tree-shaking passes + this.getReturnExpression(); + } if (this.declarationInit !== null) { - this.declarationInit.deoptimizePath([UNKNOWN_KEY, UNKNOWN_KEY]); + this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]); } } declare(kind, init) { this.declarationInit = init; return this.value.declare(kind, UNKNOWN_EXPRESSION); } - deoptimizeCache() { - // As getter properties directly receive their values from function expressions that always - // have a fixed return value, there is no known situation where a getter is deoptimized. - throw new Error('Unexpected deoptimization'); - } + // As getter properties directly receive their values from function expressions that always + // have a fixed return value, there is no known situation where a getter is deoptimized. + deoptimizeCache() { } deoptimizePath(path) { if (this.kind === 'get') { - if (path.length > 0) { - if (this.returnExpression === null) - this.updateReturnExpression(); - this.returnExpression.deoptimizePath(path); - } + this.getReturnExpression().deoptimizePath(path); } - else if (this.kind !== 'set') { + else { this.value.deoptimizePath(path); } } getLiteralValueAtPath(path, recursionTracker, origin) { - if (this.kind === 'set') { - return UNKNOWN_VALUE; - } if (this.kind === 'get') { - if (this.returnExpression === null) - this.updateReturnExpression(); - return this.returnExpression.getLiteralValueAtPath(path, recursionTracker, origin); + return this.getReturnExpression().getLiteralValueAtPath(path, recursionTracker, origin); } return this.value.getLiteralValueAtPath(path, recursionTracker, origin); } getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) { - if (this.kind === 'set') { - return UNKNOWN_EXPRESSION; - } if (this.kind === 'get') { - if (this.returnExpression === null) - this.updateReturnExpression(); - return this.returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin); + return this.getReturnExpression().getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin); } return this.value.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin); } - hasEffects(options) { - return this.key.hasEffects(options) || this.value.hasEffects(options); + hasEffects(context) { + return this.key.hasEffects(context) || this.value.hasEffects(context); } - hasEffectsWhenAccessedAtPath(path, options) { + hasEffectsWhenAccessedAtPath(path, context) { if (this.kind === 'get') { - return (this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, options.getHasEffectsWhenCalledOptions()) || - (path.length > 0 && - this.returnExpression.hasEffectsWhenAccessedAtPath(path, options))); + const trackedExpressions = context.accessed.getEntities(path); + if (trackedExpressions.has(this)) + return false; + trackedExpressions.add(this); + return (this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context) || + (path.length > 0 && this.returnExpression.hasEffectsWhenAccessedAtPath(path, context))); } - return this.value.hasEffectsWhenAccessedAtPath(path, options); + return this.value.hasEffectsWhenAccessedAtPath(path, context); } - hasEffectsWhenAssignedAtPath(path, options) { + hasEffectsWhenAssignedAtPath(path, context) { if (this.kind === 'get') { - return (path.length === 0 || - this.returnExpression.hasEffectsWhenAssignedAtPath(path, options)); + const trackedExpressions = context.assigned.getEntities(path); + if (trackedExpressions.has(this)) + return false; + trackedExpressions.add(this); + return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context); } if (this.kind === 'set') { - return (path.length > 0 || - this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, options.getHasEffectsWhenCalledOptions())); + const trackedExpressions = context.assigned.getEntities(path); + if (trackedExpressions.has(this)) + return false; + trackedExpressions.add(this); + return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context); } - return this.value.hasEffectsWhenAssignedAtPath(path, options); + return this.value.hasEffectsWhenAssignedAtPath(path, context); } - hasEffectsWhenCalledAtPath(path, callOptions, options) { + hasEffectsWhenCalledAtPath(path, callOptions, context) { if (this.kind === 'get') { - return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, options); + const trackedExpressions = (callOptions.withNew + ? context.instantiated + : context.called).getEntities(path); + if (trackedExpressions.has(this)) + return false; + trackedExpressions.add(this); + return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context); } - return this.value.hasEffectsWhenCalledAtPath(path, callOptions, options); + return this.value.hasEffectsWhenCalledAtPath(path, callOptions, context); } initialise() { - this.accessorCallOptions = CallOptions.create({ - callIdentifier: this, + this.accessorCallOptions = { + args: NO_ARGS, withNew: false - }); + }; } render(code, options) { if (!this.shorthand) { this.key.render(code, options); } this.value.render(code, options, { isShorthandProperty: this.shorthand }); } - updateReturnExpression() { - this.returnExpression = UNKNOWN_EXPRESSION; - this.returnExpression = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this); + getReturnExpression() { + if (this.returnExpression === null) { + this.returnExpression = UNKNOWN_EXPRESSION; + return (this.returnExpression = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)); + } + return this.returnExpression; } } class ReturnStatement$1 extends NodeBase { - hasEffects(options) { - return (!options.ignoreReturnAwaitYield() || - (this.argument !== null && this.argument.hasEffects(options))); + hasEffects(context) { + if (!context.ignore.returnAwaitYield || + (this.argument !== null && this.argument.hasEffects(context))) + return true; + context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL; + return false; } + include(context, includeChildrenRecursively) { + this.included = true; + if (this.argument) { + this.argument.include(context, includeChildrenRecursively); + } + context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL; + } initialise() { this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION); } render(code, options) { if (this.argument) { @@ -12288,36 +8511,36 @@ this.expressions[this.expressions.length - 1].deoptimizePath(path); } getLiteralValueAtPath(path, recursionTracker, origin) { return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin); } - hasEffects(options) { + hasEffects(context) { for (const expression of this.expressions) { - if (expression.hasEffects(options)) + if (expression.hasEffects(context)) return true; } return false; } - hasEffectsWhenAccessedAtPath(path, options) { + hasEffectsWhenAccessedAtPath(path, context) { return (path.length > 0 && - this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, options)); + this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, context)); } - hasEffectsWhenAssignedAtPath(path, options) { + hasEffectsWhenAssignedAtPath(path, context) { return (path.length === 0 || - this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, options)); + this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, context)); } - hasEffectsWhenCalledAtPath(path, callOptions, options) { - return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, options); + hasEffectsWhenCalledAtPath(path, callOptions, context) { + return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, context); } - include(includeChildrenRecursively) { + include(context, includeChildrenRecursively) { this.included = true; for (let i = 0; i < this.expressions.length - 1; i++) { const node = this.expressions[i]; - if (includeChildrenRecursively || node.shouldBeIncluded()) - node.include(includeChildrenRecursively); + if (includeChildrenRecursively || node.shouldBeIncluded(context)) + node.include(context, includeChildrenRecursively); } - this.expressions[this.expressions.length - 1].include(includeChildrenRecursively); + this.expressions[this.expressions.length - 1].include(context, includeChildrenRecursively); } render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) { let includedNodes = 0; for (const { node, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) { if (!node.included) { @@ -12342,85 +8565,160 @@ } } } class SwitchCase extends NodeBase { - include(includeChildrenRecursively) { + hasEffects(context) { + if (this.test && 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; if (this.test) - this.test.include(includeChildrenRecursively); + this.test.include(context, includeChildrenRecursively); for (const node of this.consequent) { - if (includeChildrenRecursively || node.shouldBeIncluded()) - node.include(includeChildrenRecursively); + if (includeChildrenRecursively || node.shouldBeIncluded(context)) + node.include(context, includeChildrenRecursively); } } - render(code, options) { + render(code, options, nodeRenderOptions) { if (this.consequent.length) { 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, this.end, options); + renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options); } else { super.render(code, options); } } } +SwitchCase.prototype.needsBoundaries = true; class SwitchStatement extends NodeBase { createScope(parentScope) { this.scope = new BlockScope(parentScope); } - hasEffects(options) { - return super.hasEffects(options.setIgnoreBreakStatements()); + hasEffects(context) { + if (this.discriminant.hasEffects(context)) + return true; + const { brokenFlow, ignore: { breaks } } = context; + let minBrokenFlow = Infinity; + context.ignore.breaks = true; + for (const switchCase of this.cases) { + if (switchCase.hasEffects(context)) + return true; + minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow; + context.brokenFlow = brokenFlow; + } + if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) { + context.brokenFlow = minBrokenFlow; + } + context.ignore.breaks = breaks; + return false; } + include(context, includeChildrenRecursively) { + this.included = true; + this.discriminant.include(context, includeChildrenRecursively); + const { brokenFlow } = context; + let minBrokenFlow = Infinity; + 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); + minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow; + context.brokenFlow = brokenFlow; + } + else { + minBrokenFlow = brokenFlow; + } + } + if (isCaseIncluded && + this.defaultCase !== null && + !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) { + context.brokenFlow = minBrokenFlow; + } + } + initialise() { + for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) { + if (this.cases[caseIndex].test === null) { + this.defaultCase = caseIndex; + return; + } + } + this.defaultCase = null; + } + 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 NodeBase { bind() { super.bind(); if (this.tag.type === Identifier) { - const variable = this.scope.findVariable(this.tag.name); + const name = this.tag.name; + const variable = this.scope.findVariable(name); if (variable.isNamespace) { this.context.error({ code: 'CANNOT_CALL_NAMESPACE', - message: `Cannot call a namespace ('${this.tag.name}')` + message: `Cannot call a namespace ('${name}')` }, this.start); } - if (this.tag.name === 'eval') { + if (name === 'eval') { this.context.warn({ code: 'EVAL', message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`, url: 'https://rollupjs.org/guide/en/#avoiding-eval' }, this.start); } } } - hasEffects(options) { - return (super.hasEffects(options) || - this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, options.getHasEffectsWhenCalledOptions())); + hasEffects(context) { + return (super.hasEffects(context) || + this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context)); } initialise() { - this.callOptions = CallOptions.create({ - callIdentifier: this, + this.callOptions = { + args: NO_ARGS, withNew: false - }); + }; } } class TemplateElement extends NodeBase { - hasEffects(_options) { + hasEffects() { return false; } } class TemplateLiteral extends NodeBase { getLiteralValueAtPath(path) { if (path.length > 0 || this.quasis.length !== 1) { - return UNKNOWN_VALUE; + return UnknownValue; } return this.quasis[0].value.cooked; } render(code, options) { code.indentExclusionRanges.push([this.start, this.end]); @@ -12468,15 +8766,15 @@ class ThisExpression extends NodeBase { bind() { super.bind(); this.variable = this.scope.findVariable('this'); } - hasEffectsWhenAccessedAtPath(path, options) { - return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, options); + hasEffectsWhenAccessedAtPath(path, context) { + return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, context); } - hasEffectsWhenAssignedAtPath(path, options) { - return this.variable.hasEffectsWhenAssignedAtPath(path, options); + hasEffectsWhenAssignedAtPath(path, context) { + return this.variable.hasEffectsWhenAssignedAtPath(path, context); } initialise() { this.alias = this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null; if (this.alias === 'undefined') { @@ -12485,59 +8783,71 @@ message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`, url: `https://rollupjs.org/guide/en/#error-this-is-undefined` }, this.start); } } - render(code, _options) { + render(code) { if (this.alias !== null) { code.overwrite(this.start, this.end, this.alias, { contentOnly: false, storeName: true }); } } } class ThrowStatement extends NodeBase { - hasEffects(_options) { + hasEffects() { return true; } + include(context, includeChildrenRecursively) { + this.included = true; + this.argument.include(context, includeChildrenRecursively); + context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL; + } 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 { constructor() { super(...arguments); this.directlyIncluded = false; } - hasEffects(options) { - return (this.block.body.length > 0 || - (this.handler !== null && this.handler.hasEffects(options)) || - (this.finalizer !== null && this.finalizer.hasEffects(options))); + hasEffects(context) { + return ((this.context.tryCatchDeoptimization + ? this.block.body.length > 0 + : this.block.hasEffects(context)) || + (this.finalizer !== null && this.finalizer.hasEffects(context))); } - include(includeChildrenRecursively) { + include(context, includeChildrenRecursively) { + const { brokenFlow } = context; if (!this.directlyIncluded || !this.context.tryCatchDeoptimization) { this.included = true; this.directlyIncluded = true; - this.block.include(this.context.tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively); + this.block.include(context, this.context.tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively); + context.brokenFlow = brokenFlow; } if (this.handler !== null) { - this.handler.include(includeChildrenRecursively); + this.handler.include(context, includeChildrenRecursively); + context.brokenFlow = brokenFlow; } if (this.finalizer !== null) { - this.finalizer.include(includeChildrenRecursively); + this.finalizer.include(context, includeChildrenRecursively); } } } const unaryOperators = { '!': value => !value, '+': value => +value, '-': value => -value, - delete: () => UNKNOWN_VALUE, + delete: () => UnknownValue, typeof: value => typeof value, void: () => undefined, '~': value => ~value }; class UnaryExpression extends NodeBase { @@ -12547,35 +8857,37 @@ this.argument.deoptimizePath(EMPTY_PATH); } } getLiteralValueAtPath(path, recursionTracker, origin) { if (path.length > 0) - return UNKNOWN_VALUE; + return UnknownValue; const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin); - if (argumentValue === UNKNOWN_VALUE) - return UNKNOWN_VALUE; + if (argumentValue === UnknownValue) + return UnknownValue; return unaryOperators[this.operator](argumentValue); } - hasEffects(options) { - return (this.argument.hasEffects(options) || + hasEffects(context) { + if (this.operator === 'typeof' && this.argument instanceof Identifier$1) + return false; + return (this.argument.hasEffects(context) || (this.operator === 'delete' && - this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))); + this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))); } - hasEffectsWhenAccessedAtPath(path, _options) { + hasEffectsWhenAccessedAtPath(path) { if (this.operator === 'void') { return path.length > 0; } return path.length > 1; } } class UnknownNode extends NodeBase { - hasEffects(_options) { + hasEffects() { return true; } - include() { - super.include(true); + include(context) { + super.include(context, true); } } class UpdateExpression extends NodeBase { bind() { @@ -12584,15 +8896,15 @@ if (this.argument instanceof Identifier$1) { const variable = this.scope.findVariable(this.argument.name); variable.isReassigned = true; } } - hasEffects(options) { - return (this.argument.hasEffects(options) || - this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options)); + hasEffects(context) { + return (this.argument.hasEffects(context) || + this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)); } - hasEffectsWhenAccessedAtPath(path, _options) { + hasEffectsWhenAccessedAtPath(path) { return path.length > 1; } render(code, options) { this.argument.render(code, options); const variable = this.argument.variable; @@ -12620,13 +8932,12 @@ function isReassignedExportsMember(variable) { return variable.renderBaseName !== null && variable.exportName !== null && variable.isReassigned; } function areAllDeclarationsIncludedAndNotExported(declarations) { for (const declarator of declarations) { - if (!declarator.included) { + if (!declarator.included) return false; - } if (declarator.id.type === Identifier) { if (declarator.id.variable.exportName) return false; } else { @@ -12636,30 +8947,30 @@ return false; } } return true; } -class VariableDeclaration$1 extends NodeBase { - deoptimizePath(_path) { +class VariableDeclaration extends NodeBase { + deoptimizePath() { for (const declarator of this.declarations) { declarator.deoptimizePath(EMPTY_PATH); } } - hasEffectsWhenAssignedAtPath(_path, _options) { + hasEffectsWhenAssignedAtPath() { return false; } - include(includeChildrenRecursively) { + include(context, includeChildrenRecursively) { this.included = true; for (const declarator of this.declarations) { - if (includeChildrenRecursively || declarator.shouldBeIncluded()) - declarator.include(includeChildrenRecursively); + if (includeChildrenRecursively || declarator.shouldBeIncluded(context)) + declarator.include(context, includeChildrenRecursively); } } - includeWithAllDeclaredVariables(includeChildrenRecursively) { + includeWithAllDeclaredVariables(includeChildrenRecursively, context) { this.included = true; for (const declarator of this.declarations) { - declarator.include(includeChildrenRecursively); + declarator.include(context, includeChildrenRecursively); } } initialise() { for (const declarator of this.declarations) { declarator.declareDeclarator(this.kind); @@ -12746,12 +9057,11 @@ if (options.format === 'system' && node.init !== null) { if (node.id.type !== Identifier) { node.id.addExportedVariables(systemPatternExports); } else if (node.id.variable.exportName) { - code.prependLeft(code.original.indexOf('=', node.id.end) + 1, ` exports('${node.id.variable.safeExportName || - node.id.variable.exportName}',`); + code.prependLeft(code.original.indexOf('=', node.id.end) + 1, ` exports('${node.id.variable.safeExportName || node.id.variable.exportName}',`); nextSeparatorString += ')'; } } if (isInDeclaration) { separatorString += ','; @@ -12805,25 +9115,42 @@ } } } class WhileStatement extends NodeBase { - hasEffects(options) { - return (this.test.hasEffects(options) || this.body.hasEffects(options.setIgnoreBreakStatements())); + hasEffects(context) { + if (this.test.hasEffects(context)) + return true; + const { brokenFlow, ignore: { breaks, continues } } = context; + context.ignore.breaks = true; + context.ignore.continues = true; + if (this.body.hasEffects(context)) + return true; + context.ignore.breaks = breaks; + context.ignore.continues = continues; + context.brokenFlow = brokenFlow; + return false; } + include(context, includeChildrenRecursively) { + this.included = true; + this.test.include(context, includeChildrenRecursively); + const { brokenFlow } = context; + this.body.include(context, includeChildrenRecursively); + context.brokenFlow = brokenFlow; + } } class YieldExpression extends NodeBase { bind() { super.bind(); if (this.argument !== null) { this.argument.deoptimizePath(UNKNOWN_PATH); } } - hasEffects(options) { - return (!options.ignoreReturnAwaitYield() || - (this.argument !== null && this.argument.hasEffects(options))); + hasEffects(context) { + return (!context.ignore.returnAwaitYield || + (this.argument !== null && this.argument.hasEffects(context))); } render(code, options) { if (this.argument) { this.argument.render(code, options); if (this.argument.start === this.start + 5 /* 'yield'.length */) { @@ -12847,13 +9174,14 @@ CatchClause, ClassBody, ClassDeclaration, ClassExpression, ConditionalExpression, + ContinueStatement, DoWhileStatement, EmptyStatement, - ExportAllDeclaration: ExportAllDeclaration$1, + ExportAllDeclaration, ExportDefaultDeclaration, ExportNamedDeclaration, ExpressionStatement: ExpressionStatement$1, ForInStatement, ForOfStatement, @@ -12888,16 +9216,32 @@ ThrowStatement, TryStatement, UnaryExpression, UnknownNode, UpdateExpression, - VariableDeclaration: VariableDeclaration$1, + VariableDeclaration, VariableDeclarator, WhileStatement, YieldExpression }; +class SyntheticNamedExportVariableVariable extends Variable { + constructor(context, name, defaultVariable) { + super(name); + this.context = context; + this.module = context.module; + this.defaultVariable = defaultVariable; + this.setRenderNames(defaultVariable.getName(), name); + } + include(context) { + if (!this.included) { + this.included = true; + this.context.includeVariable(context, this.defaultVariable); + } + } +} + function getOriginalLocation(sourcemapChain, location) { // This cast is guaranteed. If it were a missing Map, it wouldn't have a mappings. const filteredSourcemapChain = sourcemapChain.filter(sourcemap => sourcemap.mappings); while (filteredSourcemapChain.length > 0) { const sourcemap = filteredSourcemapChain.pop(); @@ -13284,13 +9628,13 @@ timers[label].memory += currentMemory - timers[label].startMemory; } } function getTimings() { const newTimings = {}; - Object.keys(timers).forEach(label => { + for (const label of Object.keys(timers)) { newTimings[label] = [timers[label].time, timers[label].memory, timers[label].totalMemory]; - }); + } return newTimings; } let timeStart = NOOP, timeEnd = NOOP; const TIMED_PLUGIN_HOOKS = { load: true, @@ -13346,23 +9690,24 @@ preserveParens: false, sourceType: 'module' }; function tryParse(module, Parser, acornOptions) { try { - return Parser.parse(module.code, Object.assign({}, defaultAcornOptions, acornOptions, { onComment: (block, text, start, end) => module.comments.push({ block, text, start, end }) })); + return Parser.parse(module.code, Object.assign(Object.assign(Object.assign({}, defaultAcornOptions), acornOptions), { onComment: (block, text, start, end) => module.comments.push({ block, text, start, end }) })); } catch (err) { let message = err.message.replace(/ \(\d+:\d+\)$/, ''); if (module.id.endsWith('.json')) { - message += ' (Note that you need rollup-plugin-json to import JSON files)'; + message += ' (Note that you need @rollup/plugin-json to import JSON files)'; } else if (!module.id.endsWith('.js')) { message += ' (Note that you need plugins to import files that are not JavaScript)'; } module.error({ code: 'PARSE_ERROR', - message + message, + parserError: err }, err.pos); } } function handleMissingExport(exportName, importingModule, importedModule, importerStart) { importingModule.error({ @@ -13374,43 +9719,49 @@ const MISSING_EXPORT_SHIM_DESCRIPTION = { identifier: null, localName: MISSING_EXPORT_SHIM_VARIABLE }; class Module { - constructor(graph, id, moduleSideEffects, isEntry) { + constructor(graph, id, moduleSideEffects, syntheticNamedExports, isEntry) { + this.chunk = null; this.chunkFileNames = new Set(); this.chunkName = null; this.comments = []; this.dependencies = []; this.dynamicallyImportedBy = []; this.dynamicDependencies = []; this.dynamicImports = []; this.entryPointsHash = new Uint8Array(10); this.execIndex = Infinity; - this.exportAllModules = null; - this.exportAllSources = []; + this.exportAllModules = []; + this.exportAllSources = new Set(); this.exports = Object.create(null); this.exportsAll = Object.create(null); this.exportShimVariable = new ExportShimVariable(this); this.facadeChunk = null; this.importDescriptions = Object.create(null); this.importMetas = []; this.imports = new Set(); this.isExecuted = false; this.isUserDefinedEntryPoint = false; this.manualChunkAlias = null; - this.reexports = Object.create(null); - this.sources = []; + this.reexportDescriptions = Object.create(null); + this.sources = new Set(); this.userChunkNames = new Set(); this.usesTopLevelAwait = false; - this.namespaceVariable = undefined; - this.transformDependencies = null; + this.allExportNames = null; + this.defaultExport = null; + this.namespaceVariable = null; + this.syntheticExports = new Map(); + this.transformDependencies = []; + this.transitiveReexports = null; this.id = id; this.graph = graph; this.excludeFromSourcemap = /\0/.test(id); this.context = graph.getModuleContext(id); this.moduleSideEffects = moduleSideEffects; + this.syntheticNamedExports = syntheticNamedExports; this.isEntryPoint = isEntry; } basename() { const base = basename(this.id); const ext = extname(this.id); @@ -13453,11 +9804,11 @@ } const allExportNames = (this.allExportNames = new Set()); for (const name of Object.keys(this.exports)) { allExportNames.add(name); } - for (const name of Object.keys(this.reexports)) { + for (const name of Object.keys(this.reexportDescriptions)) { allExportNames.add(name); } for (const module of this.exportAllModules) { if (module instanceof ExternalModule) { allExportNames.add(`*${module.id}`); @@ -13468,10 +9819,24 @@ allExportNames.add(name); } } return allExportNames; } + getDefaultExport() { + if (this.defaultExport === null) { + this.defaultExport = undefined; + this.defaultExport = this.getVariableForExportName('default'); + } + if (!this.defaultExport) { + return error({ + code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_DEFAULT, + id: this.id, + message: `Modules with 'syntheticNamedExports' need a default export.` + }); + } + return this.defaultExport; + } getDynamicImportExpressions() { return this.dynamicImports.map(({ node }) => { const importArgument = node.source; if (importArgument instanceof TemplateLiteral && importArgument.quasis.length === 1 && @@ -13505,11 +9870,11 @@ getExports() { return Object.keys(this.exports); } getOrCreateNamespace() { if (!this.namespaceVariable) { - this.namespaceVariable = new NamespaceVariable(this.astContext); + this.namespaceVariable = new NamespaceVariable(this.astContext, this.syntheticNamedExports); this.namespaceVariable.initialise(); } return this.namespaceVariable; } getReexports() { @@ -13517,11 +9882,11 @@ return this.transitiveReexports; } // to avoid infinite recursion when using circular `export * from X` this.transitiveReexports = []; const reexports = new Set(); - for (const name in this.reexports) { + for (const name in this.reexportDescriptions) { reexports.add(name); } for (const module of this.exportAllModules) { if (module instanceof ExternalModule) { reexports.add(`*${module.id}`); @@ -13544,11 +9909,13 @@ (variable && variable.included ? renderedExports : removedExports).push(exportName); } return { renderedExports, removedExports }; } getTransitiveDependencies() { - return this.dependencies.concat(this.getReexports().map(exportName => this.getVariableForExportName(exportName).module)); + return this.dependencies.concat(this.getReexports() + .concat(this.getExports()) + .map((exportName) => this.getVariableForExportName(exportName).module)); } getVariableForExportName(name, isExportAllSearch) { if (name[0] === '*') { if (name.length === 1) { return this.getOrCreateNamespace(); @@ -13558,11 +9925,11 @@ const module = this.graph.moduleById.get(name.slice(1)); return module.getVariableForExportName('*'); } } // export { foo } from './other' - const reexportDeclaration = this.reexports[name]; + const reexportDeclaration = this.reexportDescriptions[name]; if (reexportDeclaration) { const declaration = reexportDeclaration.module.getVariableForExportName(reexportDeclaration.localName); if (!declaration) { handleMissingExport(reexportDeclaration.localName, this, reexportDeclaration.module.id, reexportDeclaration.start); } @@ -13583,47 +9950,61 @@ return declaration; } } // we don't want to create shims when we are just // probing export * modules for exports - if (this.graph.shimMissingExports && !isExportAllSearch) { - this.shimMissingExport(name); - return this.exportShimVariable; + if (!isExportAllSearch) { + if (this.syntheticNamedExports) { + let syntheticExport = this.syntheticExports.get(name); + if (!syntheticExport) { + const defaultExport = this.getDefaultExport(); + syntheticExport = new SyntheticNamedExportVariableVariable(this.astContext, name, defaultExport); + this.syntheticExports.set(name, syntheticExport); + return syntheticExport; + } + return syntheticExport; + } + if (this.graph.shimMissingExports) { + this.shimMissingExport(name); + return this.exportShimVariable; + } } return undefined; } include() { - if (this.ast.shouldBeIncluded()) - this.ast.include(false); + const context = createInclusionContext(); + if (this.ast.shouldBeIncluded(context)) + this.ast.include(context, false); } includeAllExports() { if (!this.isExecuted) { this.graph.needsTreeshakingPass = true; markModuleAndImpureDependenciesAsExecuted(this); } + const context = createInclusionContext(); for (const exportName of this.getExports()) { const variable = this.getVariableForExportName(exportName); variable.deoptimizePath(UNKNOWN_PATH); if (!variable.included) { - variable.include(); + variable.include(context); this.graph.needsTreeshakingPass = true; } } for (const name of this.getReexports()) { const variable = this.getVariableForExportName(name); variable.deoptimizePath(UNKNOWN_PATH); if (!variable.included) { - variable.include(); + variable.include(context); this.graph.needsTreeshakingPass = true; } if (variable instanceof ExternalVariable) { variable.module.reexported = true; } } } includeAllInBundle() { - this.ast.include(true); + this.ast.include(createInclusionContext(), true); } isIncluded() { return this.ast.included || (this.namespaceVariable && this.namespaceVariable.included); } linkDependencies() { @@ -13637,30 +10018,26 @@ for (const { resolution } of this.dynamicImports) { if (resolution instanceof Module || resolution instanceof ExternalModule) { this.dynamicDependencies.push(resolution); } } - this.addModulesToSpecifiers(this.importDescriptions); - this.addModulesToSpecifiers(this.reexports); - this.exportAllModules = this.exportAllSources - .map(source => { - const id = this.resolvedIds[source].id; - return this.graph.moduleById.get(id); - }) - .sort((moduleA, moduleB) => { - const aExternal = moduleA instanceof ExternalModule; - const bExternal = moduleB instanceof ExternalModule; - return aExternal === bExternal ? 0 : aExternal ? 1 : -1; - }); + this.addModulesToImportDescriptions(this.importDescriptions); + this.addModulesToImportDescriptions(this.reexportDescriptions); + const externalExportAllModules = []; + for (const source of this.exportAllSources) { + const module = this.graph.moduleById.get(this.resolvedIds[source].id); + (module instanceof ExternalModule ? externalExportAllModules : this.exportAllModules).push(module); + } + this.exportAllModules = this.exportAllModules.concat(externalExportAllModules); } render(options) { const magicString = this.magicString.clone(); this.ast.render(magicString, options); this.usesTopLevelAwait = this.astContext.usesTopLevelAwait; return magicString; } - setSource({ ast, code, customTransformCache, moduleSideEffects, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles }) { + setSource({ ast, code, customTransformCache, moduleSideEffects, originalCode, originalSourcemap, resolvedIds, sourcemapChain, syntheticNamedExports, transformDependencies, transformFiles }) { this.code = code; this.originalCode = originalCode; this.originalSourcemap = originalSourcemap; this.sourcemapChain = sourcemapChain; if (transformFiles) { @@ -13669,10 +10046,13 @@ this.transformDependencies = transformDependencies; this.customTransformCache = customTransformCache; if (typeof moduleSideEffects === 'boolean') { this.moduleSideEffects = moduleSideEffects; } + if (typeof syntheticNamedExports === 'boolean') { + this.syntheticNamedExports = syntheticNamedExports; + } timeStart('generate ast', 3); this.esTreeAst = ast || tryParse(this, this.graph.acornParser, this.graph.acornOptions); markPureCallExpressions(this.comments, this.esTreeAst); timeEnd('generate ast', 3); this.resolvedIds = resolvedIds || Object.create(null); @@ -13688,18 +10068,16 @@ this.astContext = { addDynamicImport: this.addDynamicImport.bind(this), addExport: this.addExport.bind(this), addImport: this.addImport.bind(this), addImportMeta: this.addImportMeta.bind(this), - annotations: (this.graph.treeshakingOptions && - this.graph.treeshakingOptions.annotations), + annotations: (this.graph.treeshakingOptions && this.graph.treeshakingOptions.annotations), code, deoptimizationTracker: this.graph.deoptimizationTracker, error: this.error.bind(this), fileName, getExports: this.getExports.bind(this), - getFileName: this.graph.pluginDriver.getFileName, getModuleExecIndex: () => this.execIndex, getModuleName: this.basename.bind(this), getReexports: this.getReexports.bind(this), importDescriptions: this.importDescriptions, includeDynamicImport: this.includeDynamicImport.bind(this), @@ -13715,10 +10093,12 @@ traceExport: this.getVariableForExportName.bind(this), traceVariable: this.traceVariable.bind(this), treeshake: !!this.graph.treeshakingOptions, tryCatchDeoptimization: (!this.graph.treeshakingOptions || this.graph.treeshakingOptions.tryCatchDeoptimization), + unknownGlobalSideEffects: (!this.graph.treeshakingOptions || + this.graph.treeshakingOptions.unknownGlobalSideEffects), usesTopLevelAwait: false, warn: this.warn.bind(this), warnDeprecation: this.graph.warnDeprecation.bind(this.graph) }; this.scope = new ModuleScope(this.graph.scope, this.astContext); @@ -13735,10 +10115,11 @@ moduleSideEffects: this.moduleSideEffects, originalCode: this.originalCode, originalSourcemap: this.originalSourcemap, resolvedIds: this.resolvedIds, sourcemapChain: this.sourcemapChain, + syntheticNamedExports: this.syntheticNamedExports, transformDependencies: this.transformDependencies, transformFiles: this.transformFiles }; } traceVariable(name) { @@ -13772,62 +10153,44 @@ } addDynamicImport(node) { this.dynamicImports.push({ node, resolution: null }); } addExport(node) { - const source = node.source && node.source.value; - // export { name } from './other' - if (source) { - if (this.sources.indexOf(source) === -1) - this.sources.push(source); - if (node.type === ExportAllDeclaration) { - // Store `export * from '...'` statements in an array of delegates. - // When an unknown import is encountered, we see if one of them can satisfy it. - this.exportAllSources.push(source); - } - else { - for (const specifier of node.specifiers) { - const name = specifier.exported.name; - if (this.exports[name] || this.reexports[name]) { - this.error({ - code: 'DUPLICATE_EXPORT', - message: `A module cannot have multiple exports with the same name ('${name}')` - }, specifier.start); - } - this.reexports[name] = { - localName: specifier.local.name, - module: null, - source, - start: specifier.start - }; - } - } - } - else if (node instanceof ExportDefaultDeclaration) { - // export default function foo () {} + if (node instanceof ExportDefaultDeclaration) { // export default foo; - // export default 42; - if (this.exports.default) { - this.error({ - code: 'DUPLICATE_EXPORT', - message: `A module can only have one default export` - }, node.start); - } this.exports.default = { identifier: node.variable.getAssignedVariableName(), localName: 'default' }; } + else if (node instanceof ExportAllDeclaration) { + // export * from './other' + const source = node.source.value; + this.sources.add(source); + this.exportAllSources.add(source); + } + else if (node.source instanceof Literal) { + // export { name } from './other' + const source = node.source.value; + this.sources.add(source); + for (const specifier of node.specifiers) { + const name = specifier.exported.name; + this.reexportDescriptions[name] = { + localName: specifier.type === ExportNamespaceSpecifier ? '*' : specifier.local.name, + module: null, + source, + start: specifier.start + }; + } + } else if (node.declaration) { - // export var { foo, bar } = ... - // export var foo = 42; - // export var a = 1, b = 2, c = 3; - // export function foo () {} const declaration = node.declaration; - if (declaration.type === VariableDeclaration) { - for (const decl of declaration.declarations) { - for (const localName of extractAssignedNames(decl.id)) { + 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(declarator.id)) { this.exports[localName] = { identifier: null, localName }; } } } else { @@ -13839,24 +10202,17 @@ else { // export { foo, bar, baz } for (const specifier of node.specifiers) { const localName = specifier.local.name; const exportedName = specifier.exported.name; - if (this.exports[exportedName] || this.reexports[exportedName]) { - this.error({ - code: 'DUPLICATE_EXPORT', - message: `A module cannot have multiple exports with the same name ('${exportedName}')` - }, specifier.start); - } this.exports[exportedName] = { identifier: null, localName }; } } } addImport(node) { const source = node.source.value; - if (this.sources.indexOf(source) === -1) - this.sources.push(source); + this.sources.add(source); for (const specifier of node.specifiers) { const localName = specifier.local.name; if (this.importDescriptions[localName]) { this.error({ code: 'DUPLICATE_IMPORT', @@ -13874,13 +10230,13 @@ } } addImportMeta(node) { this.importMetas.push(node); } - addModulesToSpecifiers(specifiers) { - for (const name of Object.keys(specifiers)) { - const specifier = specifiers[name]; + addModulesToImportDescriptions(importDescription) { + for (const name of Object.keys(importDescription)) { + const specifier = importDescription[name]; const id = this.resolvedIds[specifier.source].id; specifier.module = this.graph.moduleById.get(id); } } includeDynamicImport(node) { @@ -13888,14 +10244,14 @@ if (resolution instanceof Module) { resolution.dynamicallyImportedBy.push(this); resolution.includeAllExports(); } } - includeVariable(variable) { + includeVariable(context, variable) { const variableModule = variable.module; if (!variable.included) { - variable.include(); + variable.include(context); this.graph.needsTreeshakingPass = true; } if (variableModule && variableModule !== this) { this.imports.add(variable); } @@ -14021,11 +10377,13 @@ if (map.mappings) { return new Link(map, [source]); } graph.warn({ code: 'SOURCEMAP_BROKEN', - message: `Sourcemap is likely to be incorrect: a plugin${map.plugin ? ` ('${map.plugin}')` : ``} was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help`, + message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` + + "files, but didn't generate a sourcemap for the transformation. Consult the plugin " + + 'documentation for help', plugin: map.plugin, url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect` }); return new Link({ mappings: [], @@ -14083,34 +10441,19 @@ iife: deconflictImportsOther, system: deconflictImportsEsm, umd: deconflictImportsOther }; function deconflictChunk(modules, dependencies, imports, usedNames, format, interop, preserveModules) { - addUsedGlobalNames(usedNames, modules, format); + for (const module of modules) { + module.scope.addUsedOutsideNames(usedNames, format); + } deconflictTopLevelVariables(usedNames, modules); DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependencies, interop, preserveModules); for (const module of modules) { module.scope.deconflict(format); } } -function addUsedGlobalNames(usedNames, modules, format) { - for (const module of modules) { - const moduleScope = module.scope; - for (const [name, variable] of moduleScope.accessedOutsideVariables) { - if (variable.included) { - usedNames.add(name); - } - } - const accessedGlobalVariables = moduleScope.accessedGlobalVariablesByFormat && - moduleScope.accessedGlobalVariablesByFormat.get(format); - if (accessedGlobalVariables) { - for (const name of accessedGlobalVariables) { - usedNames.add(name); - } - } - } -} function deconflictImportsEsm(usedNames, imports, _dependencies, interop) { for (const variable of imports) { const module = variable.module; const name = variable.name; let proposedName; @@ -14290,14 +10633,14 @@ mappings = decode(map.mappings); } else { mappings = map.mappings; } - return Object.assign({}, map, { mappings }); + return Object.assign(Object.assign({}, map), { mappings }); } -function renderChunk({ graph, chunk, renderChunk, code, sourcemapChain, options }) { +function renderChunk({ chunk, code, options, outputPluginDriver, renderChunk, sourcemapChain }) { const renderChunkReducer = (code, result, plugin) => { if (result == null) return code; if (typeof result === 'string') result = { @@ -14311,19 +10654,19 @@ } return result.code; }; let inTransformBundle = false; let inRenderChunk = true; - return graph.pluginDriver + return outputPluginDriver .hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer) .then(code => { inRenderChunk = false; - return graph.pluginDriver.hookReduceArg0('transformChunk', [code, options, chunk], renderChunkReducer); + return outputPluginDriver.hookReduceArg0('transformChunk', [code, options, chunk], renderChunkReducer); }) .then(code => { inTransformBundle = true; - return graph.pluginDriver.hookReduceArg0('transformBundle', [code, options, chunk], renderChunkReducer); + return outputPluginDriver.hookReduceArg0('transformBundle', [code, options, chunk], renderChunkReducer); }) .catch(err => { if (inRenderChunk) throw err; return error(err, { @@ -14357,10 +10700,11 @@ while (existingNames[(uniqueName = name + ++uniqueIndex + ext)]) ; return uniqueName; } +const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx']; function getGlobalName(module, globals, graph, hasExports) { let globalName; if (typeof globals === 'function') { globalName = globals(module.id); } @@ -14485,25 +10829,44 @@ facades.push(Chunk$1.generateFacade(this.graph, module, facadeName)); } } return facades; } - generateId(pattern, patternName, addons, options, existingNames) { + generateId(addons, options, existingNames, includeHash, outputPluginDriver) { if (this.fileName !== null) { return this.fileName; } + const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint + ? [options.entryFileNames || '[name].js', 'output.entryFileNames'] + : [options.chunkFileNames || '[name]-[hash].js', 'output.chunkFileNames']; return makeUnique(renderNamePattern(pattern, patternName, { format: () => (options.format === 'es' ? 'esm' : options.format), - hash: () => this.computeContentHashWithDependencies(addons, options), + hash: () => includeHash + ? this.computeContentHashWithDependencies(addons, options, existingNames, outputPluginDriver) + : '[hash]', name: () => this.getChunkName() }), existingNames); } - generateIdPreserveModules(preserveModulesRelativeDir, existingNames) { - const sanitizedId = sanitizeFileName(this.orderedModules[0].id); - return makeUnique(normalize(isAbsolute(this.orderedModules[0].id) - ? relative(preserveModulesRelativeDir, sanitizedId) - : '_virtual/' + basename(sanitizedId)), existingNames); + generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames) { + const id = this.orderedModules[0].id; + const sanitizedId = sanitizeFileName(id); + let path; + if (isAbsolute(id)) { + const extension = extname(id); + const name = renderNamePattern(options.entryFileNames || + (NON_ASSET_EXTENSIONS.includes(extension) ? '[name].js' : '[name][extname].js'), 'output.entryFileNames', { + ext: () => extension.substr(1), + extname: () => extension, + format: () => (options.format === 'es' ? 'esm' : options.format), + name: () => this.getChunkName() + }); + path = relative(preserveModulesRelativeDir, `${dirname(sanitizedId)}/${name}`); + } + else { + path = `_virtual/${basename(sanitizedId)}`; + } + return makeUnique(normalize(path), existingNames); } generateInternalExports(options) { if (this.facadeModule !== null) return; const mangle = options.format === 'system' || options.format === 'es' || options.compact; @@ -14550,17 +10913,17 @@ return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportNames).sort())); } getImportIds() { return this.dependencies.map(chunk => chunk.id).filter(Boolean); } - getRenderedHash() { + getRenderedHash(outputPluginDriver) { if (this.renderedHash) return this.renderedHash; if (!this.renderedSource) return ''; - const hash = _256(); - const hashAugmentation = this.calculateHashAugmentation(); + const hash = createHash(); + const hashAugmentation = this.calculateHashAugmentation(outputPluginDriver); hash.update(hashAugmentation); hash.update(this.renderedSource.toString()); hash.update(this.getExportNames() .map(exportName => { const variable = this.exportNames[exportName]; @@ -14770,35 +11133,29 @@ else { this.renderedSource = magicString.trim(); } this.renderedSourceLength = undefined; this.renderedHash = undefined; - if (this.getExportNames().length === 0 && this.getImportIds().length === 0 && this.isEmpty) { + if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.length === 0) { + const chunkName = this.getChunkName(); this.graph.warn({ + chunkName, code: 'EMPTY_BUNDLE', - message: 'Generated an empty bundle' + message: `Generated an empty chunk: "${chunkName}"` }); } this.setExternalRenderPaths(options, inputBase); this.renderedDeclarations = { dependencies: this.getChunkDependencyDeclarations(options), exports: this.exportMode === 'none' ? [] : this.getChunkExportDeclarations() }; timeEnd('render modules', 3); } - render(options, addons, outputChunk) { + render(options, addons, outputChunk, outputPluginDriver) { timeStart('render format', 3); - if (!this.renderedSource) - throw new Error('Internal error: Chunk render called before preRender'); const format = options.format; const finalise = finalisers[format]; - if (!finalise) { - error({ - code: 'INVALID_OPTION', - message: `Invalid format: ${format} - valid options are ${Object.keys(finalisers).join(', ')}.` - }); - } if (options.dynamicImportFunction && format !== 'es') { this.graph.warn({ code: 'INVALID_OPTION', message: '"output.dynamicImportFunction" is ignored for formats other than "esm".' }); @@ -14814,11 +11171,11 @@ if (dep instanceof Chunk$1) renderedDependency.namedExportsMode = dep.exportMode !== 'default'; renderedDependency.id = this.getRelativePath(depId); } this.finaliseDynamicImports(format); - this.finaliseImportMetas(format); + this.finaliseImportMetas(format, outputPluginDriver); const hasExports = this.renderedDeclarations.exports.length !== 0 || this.renderedDeclarations.dependencies.some(dep => (dep.reexports && dep.reexports.length !== 0)); let usesTopLevelAwait = false; const accessedGlobals = new Set(); for (const module of this.orderedModules) { @@ -14844,11 +11201,12 @@ dependencies: this.renderedDeclarations.dependencies, exports: this.renderedDeclarations.exports, hasExports, indentString: this.indentString, intro: addons.intro, - isEntryModuleFacade: this.facadeModule !== null && this.facadeModule.isEntryPoint, + isEntryModuleFacade: this.graph.preserveModules || + (this.facadeModule !== null && this.facadeModule.isEntryPoint), namedExportsMode: this.exportMode !== 'default', outro: addons.outro, usesTopLevelAwait, varOrConst: options.preferConst ? 'const' : 'var', warn: this.graph.warn.bind(this.graph) @@ -14862,12 +11220,12 @@ let map = null; const chunkSourcemapChain = []; return renderChunk({ chunk: this, code: prevCode, - graph: this.graph, options, + outputPluginDriver, renderChunk: outputChunk, sourcemapChain: chunkSourcemapChain }).then((code) => { if (options.sourcemap) { timeStart('sourcemap', 3); @@ -14943,11 +11301,11 @@ } else { this.name = sanitizeFileName(name || facadedModule.chunkName || getAliasName(facadedModule.id)); } } - calculateHashAugmentation() { + calculateHashAugmentation(outputPluginDriver) { const facadeModule = this.facadeModule; const getChunkName = this.getChunkName.bind(this); const preRenderedChunk = { dynamicImports: this.getDynamicImportIds(), exports: this.getExportNames(), @@ -14958,27 +11316,29 @@ modules: this.renderedModules, get name() { return getChunkName(); } }; - const hashAugmentation = this.graph.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [preRenderedChunk], (hashAugmentation, pluginHash) => { + return outputPluginDriver.hookReduceValueSync('augmentChunkHash', '', [preRenderedChunk], (hashAugmentation, pluginHash) => { if (pluginHash) { hashAugmentation += pluginHash; } return hashAugmentation; }); - return hashAugmentation; } - computeContentHashWithDependencies(addons, options) { - const hash = _256(); + computeContentHashWithDependencies(addons, options, existingNames, outputPluginDriver) { + const hash = createHash(); hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':')); hash.update(options.format); this.visitDependencies(dep => { - if (dep instanceof ExternalModule) + if (dep instanceof ExternalModule) { hash.update(':' + dep.renderPath); - else - hash.update(dep.getRenderedHash()); + } + else { + hash.update(dep.getRenderedHash(outputPluginDriver)); + hash.update(dep.generateId(addons, options, existingNames, false, outputPluginDriver)); + } }); return hash.digest('hex').substr(0, 8); } finaliseDynamicImports(format) { for (const [module, code] of this.renderedModuleSources) { @@ -14999,14 +11359,14 @@ : resolution, format); } } } } - finaliseImportMetas(format) { + finaliseImportMetas(format, outputPluginDriver) { for (const [module, code] of this.renderedModuleSources) { for (const importMeta of module.importMetas) { - importMeta.renderFinalMechanism(code, this.id, format, this.graph.pluginDriver); + importMeta.renderFinalMechanism(code, this.id, format, outputPluginDriver); } } } getChunkDependencyDeclarations(options) { const reexportDeclarations = new Map(); @@ -15244,24 +11604,25 @@ exportingModule.chunk.exports.add(exportedVariable); } } } if (module.getOrCreateNamespace().included) { - for (const reexportName of Object.keys(module.reexports)) { - const reexport = module.reexports[reexportName]; + for (const reexportName of Object.keys(module.reexportDescriptions)) { + const reexport = module.reexportDescriptions[reexportName]; const variable = reexport.module.getVariableForExportName(reexport.localName); if (variable.module.chunk !== this) { this.imports.add(variable); if (variable.module instanceof Module) { variable.module.chunk.exports.add(variable); } } } } + const context = createInclusionContext(); for (const { node, resolution } of module.dynamicImports) { if (node.included && resolution instanceof Module && resolution.chunk === this) - resolution.getOrCreateNamespace().include(); + resolution.getOrCreateNamespace().include(context); } } } /* @@ -15371,40 +11732,69 @@ } while (((lastChunk = chunk), (chunk = nextChunk), (nextChunk = execGroup[++execGroupIndex]), chunk)); } return chunks; } -const tt = acorn__default.tokTypes; const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; +const tt = acorn__default.tokTypes; +var acornExportNsFrom = function (Parser) { + return class extends Parser { + parseExport(node, exports) { + skipWhiteSpace.lastIndex = this.pos; + const skip = skipWhiteSpace.exec(this.input); + const next = this.input.charAt(this.pos + skip[0].length); + if (next !== "*") + return super.parseExport(node, exports); + this.next(); + const specifier = this.startNode(); + this.expect(tt.star); + if (this.eatContextual("as")) { + node.declaration = null; + specifier.exported = this.parseIdent(true); + this.checkExport(exports, specifier.exported.name, this.lastTokStart); + node.specifiers = [this.finishNode(specifier, "ExportNamespaceSpecifier")]; + } + this.expectContextual("from"); + if (this.type !== tt.string) + this.unexpected(); + node.source = this.parseExprAtom(); + this.semicolon(); + return this.finishNode(node, node.specifiers ? "ExportNamedDeclaration" : "ExportAllDeclaration"); + } + }; +}; + +const tt$1 = acorn__default.tokTypes; +const skipWhiteSpace$1 = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; const nextTokenIsDot = parser => { - skipWhiteSpace.lastIndex = parser.pos; - let skip = skipWhiteSpace.exec(parser.input); + skipWhiteSpace$1.lastIndex = parser.pos; + let skip = skipWhiteSpace$1.exec(parser.input); let next = parser.pos + skip[0].length; return parser.input.slice(next, next + 1) === "."; }; var acornImportMeta = function (Parser) { return class extends Parser { parseExprAtom(refDestructuringErrors) { - if (this.type !== tt._import || !nextTokenIsDot(this)) + if (this.type !== tt$1._import || !nextTokenIsDot(this)) return super.parseExprAtom(refDestructuringErrors); if (!this.options.allowImportExportEverywhere && !this.inModule) { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } let node = this.startNode(); node.meta = this.parseIdent(true); - this.expect(tt.dot); + this.expect(tt$1.dot); 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 (this.containsEsc) { this.raiseRecoverable(node.property.start, "\"meta\" in import.meta must not contain escape sequences"); } return this.finishNode(node, "MetaProperty"); } parseStatement(context, topLevel, exports) { - if (this.type !== tt._import || !nextTokenIsDot(this)) { + if (this.type !== tt$1._import || !nextTokenIsDot(this)) { return super.parseStatement(context, topLevel, exports); } let node = this.startNode(); let expr = this.parseExpression(); return this.parseExpressionStatement(node, expr); @@ -15434,275 +11824,28 @@ } return variable; } } -const getNewTrackedPaths = () => ({ - paths: Object.create(null), - tracked: false, - unknownPath: null -}); -class EntityPathTracker { - constructor() { - this.entityPaths = new Map(); +const ANONYMOUS_PLUGIN_PREFIX = 'at position '; +const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position '; +function throwPluginError(err, plugin, { hook, id } = {}) { + if (typeof err === 'string') + err = { message: err }; + if (err.code && err.code !== Errors.PLUGIN_ERROR) { + err.pluginCode = err.code; } - track(entity, path) { - let trackedPaths = this.entityPaths.get(entity); - if (!trackedPaths) { - trackedPaths = getNewTrackedPaths(); - this.entityPaths.set(entity, trackedPaths); - } - let pathIndex = 0, trackedSubPaths; - while (pathIndex < path.length) { - const key = path[pathIndex]; - if (typeof key === 'string') { - trackedSubPaths = trackedPaths.paths[key]; - if (!trackedSubPaths) { - trackedSubPaths = getNewTrackedPaths(); - trackedPaths.paths[key] = trackedSubPaths; - } - } - else { - trackedSubPaths = trackedPaths.unknownPath; - if (!trackedSubPaths) { - trackedSubPaths = getNewTrackedPaths(); - trackedPaths.unknownPath = trackedSubPaths; - } - } - trackedPaths = trackedSubPaths; - pathIndex++; - } - const found = trackedPaths.tracked; - trackedPaths.tracked = true; - return found; + err.code = Errors.PLUGIN_ERROR; + err.plugin = plugin; + if (hook) { + err.hook = hook; } -} - -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 = {})); - -function generateAssetFileName(name, source, output) { - const emittedName = name || 'asset'; - return makeUnique(renderNamePattern(output.assetFileNames, 'output.assetFileNames', { - hash() { - const hash = _256(); - hash.update(emittedName); - hash.update(':'); - hash.update(source); - return hash.digest('hex').substr(0, 8); - }, - ext: () => extname(emittedName).substr(1), - extname: () => extname(emittedName), - name: () => emittedName.substr(0, emittedName.length - extname(emittedName).length) - }), output.bundle); -} -function reserveFileNameInBundle(fileName, bundle) { - if (fileName in bundle) { - return error(errFileNameConflict(fileName)); + if (id) { + err.id = id; } - bundle[fileName] = FILE_PLACEHOLDER; + return error(err); } -const FILE_PLACEHOLDER = { - isPlaceholder: true -}; -function hasValidType(emittedFile) { - return (emittedFile && - (emittedFile.type === 'asset' || - emittedFile.type === 'chunk')); -} -function hasValidName(emittedFile) { - const validatedName = emittedFile.fileName || emittedFile.name; - return (!validatedName || (typeof validatedName === 'string' && isPlainPathFragment(validatedName))); -} -function getValidSource(source, emittedFile, fileReferenceId) { - if (typeof source !== 'string' && !Buffer.isBuffer(source)) { - const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId; - return error(errFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string of Buffer.`)); - } - return source; -} -function getAssetFileName(file, referenceId) { - if (typeof file.fileName !== 'string') { - return error(errAssetNotFinalisedForFileName(file.name || referenceId)); - } - return file.fileName; -} -function getChunkFileName(file) { - const fileName = file.fileName || (file.module && file.module.facadeChunk.id); - if (!fileName) - return error(errChunkNotGeneratedForFileName(file.fileName || file.name)); - return fileName; -} -class FileEmitter { - constructor(graph) { - this.filesByReferenceId = new Map(); - // tslint:disable member-ordering - this.buildFilesByReferenceId = this.filesByReferenceId; - this.output = null; - this.emitFile = (emittedFile) => { - if (!hasValidType(emittedFile)) { - return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && - emittedFile.type}".`)); - } - if (!hasValidName(emittedFile)) { - return error(errFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths and do not contain invalid characters, received "${emittedFile.fileName || - emittedFile.name}".`)); - } - if (emittedFile.type === 'chunk') { - return this.emitChunk(emittedFile); - } - else { - return this.emitAsset(emittedFile); - } - }; - this.getFileName = (fileReferenceId) => { - const emittedFile = this.filesByReferenceId.get(fileReferenceId); - if (!emittedFile) - return error(errFileReferenceIdNotFoundForFilename(fileReferenceId)); - if (emittedFile.type === 'chunk') { - return getChunkFileName(emittedFile); - } - else { - return getAssetFileName(emittedFile, fileReferenceId); - } - }; - this.setAssetSource = (referenceId, requestedSource) => { - const consumedFile = this.filesByReferenceId.get(referenceId); - if (!consumedFile) - return error(errAssetReferenceIdNotFoundForSetSource(referenceId)); - if (consumedFile.type !== 'asset') { - return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`)); - } - if (consumedFile.source !== undefined) { - return error(errAssetSourceAlreadySet(consumedFile.name || referenceId)); - } - const source = getValidSource(requestedSource, consumedFile, referenceId); - if (this.output) { - this.finalizeAsset(consumedFile, source, referenceId, this.output); - } - else { - consumedFile.source = source; - } - }; - this.graph = graph; - } - startOutput(outputBundle, assetFileNames) { - this.filesByReferenceId = new Map(this.buildFilesByReferenceId); - this.output = { - assetFileNames, - bundle: outputBundle - }; - for (const emittedFile of this.filesByReferenceId.values()) { - if (emittedFile.fileName) { - reserveFileNameInBundle(emittedFile.fileName, this.output.bundle); - } - } - for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) { - if (consumedFile.type === 'asset' && consumedFile.source !== undefined) { - this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.output); - } - } - } - assertAssetsFinalized() { - for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) { - if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string') - error(errNoAssetSourceSet(emittedFile.name || referenceId)); - } - } - emitAsset(emittedAsset) { - const source = typeof emittedAsset.source !== 'undefined' - ? getValidSource(emittedAsset.source, emittedAsset, null) - : undefined; - const consumedAsset = { - fileName: emittedAsset.fileName, - name: emittedAsset.name, - source, - type: 'asset' - }; - const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type); - if (this.output) { - if (emittedAsset.fileName) { - reserveFileNameInBundle(emittedAsset.fileName, this.output.bundle); - } - if (source !== undefined) { - this.finalizeAsset(consumedAsset, source, referenceId, this.output); - } - } - return referenceId; - } - emitChunk(emittedChunk) { - if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) { - error(errInvalidRollupPhaseForChunkEmission()); - } - if (typeof emittedChunk.id !== 'string') { - return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`)); - } - const consumedChunk = { - fileName: emittedChunk.fileName, - module: null, - name: emittedChunk.name || emittedChunk.id, - type: 'chunk' - }; - this.graph.moduleLoader - .addEntryModules([ - { - fileName: emittedChunk.fileName || null, - id: emittedChunk.id, - name: emittedChunk.name || null - } - ], false) - .then(({ newEntryModules: [module] }) => { - consumedChunk.module = module; - }) - .catch(() => { - // Avoid unhandled Promise rejection as the error will be thrown later - // once module loading has finished - }); - return this.assignReferenceId(consumedChunk, emittedChunk.id); - } - assignReferenceId(file, idBase) { - let referenceId; - do { - const hash = _256(); - if (referenceId) { - hash.update(referenceId); - } - else { - hash.update(idBase); - } - referenceId = hash.digest('hex').substr(0, 8); - } while (this.filesByReferenceId.has(referenceId)); - this.filesByReferenceId.set(referenceId, file); - return referenceId; - } - finalizeAsset(consumedFile, source, referenceId, output) { - const fileName = consumedFile.fileName || - this.findExistingAssetFileNameWithSource(output.bundle, source) || - generateAssetFileName(consumedFile.name, source, output); - // We must not modify the original assets to avoid interaction between outputs - const assetWithFileName = Object.assign({}, consumedFile, { source, fileName }); - this.filesByReferenceId.set(referenceId, assetWithFileName); - output.bundle[fileName] = { fileName, isAsset: true, source }; - } - findExistingAssetFileNameWithSource(bundle, source) { - for (const fileName of Object.keys(bundle)) { - const outputFile = bundle[fileName]; - if (outputFile.isAsset && - (Buffer.isBuffer(source) && Buffer.isBuffer(outputFile.source) - ? source.equals(outputFile.source) - : source === outputFile.source)) - return fileName; - } - return null; - } -} - -const ANONYMOUS_PLUGIN_PREFIX = 'at position '; const deprecatedHooks = [ { active: true, deprecated: 'ongenerate', replacement: 'generateBundle' }, { active: true, deprecated: 'onwrite', replacement: 'generateBundle/writeBundle' }, { active: true, deprecated: 'transformBundle', replacement: 'renderChunk' }, { active: true, deprecated: 'transformChunk', replacement: 'renderChunk' }, @@ -15718,296 +11861,11 @@ }, active); } } } } -function throwPluginError(err, plugin, { hook, id } = {}) { - if (typeof err === 'string') - err = { message: err }; - if (err.code && err.code !== Errors.PLUGIN_ERROR) { - err.pluginCode = err.code; - } - err.code = Errors.PLUGIN_ERROR; - err.plugin = plugin; - if (hook) { - err.hook = hook; - } - if (id) { - err.id = id; - } - return error(err); -} -function createPluginDriver(graph, options, pluginCache, watcher) { - warnDeprecatedHooks(options.plugins, graph); - function getDeprecatedHookHandler(handler, handlerName, newHandlerName, pluginName, acitveDeprecation) { - let deprecationWarningShown = false; - return ((...args) => { - if (!deprecationWarningShown) { - deprecationWarningShown = true; - graph.warnDeprecation({ - message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`, - plugin: pluginName - }, acitveDeprecation); - } - return handler(...args); - }); - } - const plugins = [ - ...options.plugins, - getRollupDefaultPlugin(options.preserveSymlinks) - ]; - const fileEmitter = new FileEmitter(graph); - const existingPluginKeys = new Set(); - const pluginContexts = plugins.map((plugin, pidx) => { - let cacheable = true; - if (typeof plugin.cacheKey !== 'string') { - if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) || existingPluginKeys.has(plugin.name)) { - cacheable = false; - } - else { - existingPluginKeys.add(plugin.name); - } - } - let cacheInstance; - if (!pluginCache) { - cacheInstance = noCache; - } - else if (cacheable) { - const cacheKey = plugin.cacheKey || plugin.name; - cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null))); - } - else { - cacheInstance = uncacheablePlugin(plugin.name); - } - const context = { - addWatchFile(id) { - if (graph.phase >= BuildPhase.GENERATE) - this.error(errInvalidRollupPhaseForAddWatchFile()); - graph.watchFiles[id] = true; - }, - cache: cacheInstance, - emitAsset: getDeprecatedHookHandler((name, source) => fileEmitter.emitFile({ type: 'asset', name, source }), 'emitAsset', 'emitFile', plugin.name, false), - emitChunk: getDeprecatedHookHandler((id, options) => fileEmitter.emitFile({ type: 'chunk', id, name: options && options.name }), 'emitChunk', 'emitFile', plugin.name, false), - emitFile: fileEmitter.emitFile, - error(err) { - return throwPluginError(err, plugin.name); - }, - getAssetFileName: getDeprecatedHookHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, false), - getChunkFileName: getDeprecatedHookHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, false), - getFileName: fileEmitter.getFileName, - getModuleInfo(moduleId) { - const foundModule = graph.moduleById.get(moduleId); - if (foundModule == null) { - throw new Error(`Unable to find module ${moduleId}`); - } - return { - hasModuleSideEffects: foundModule.moduleSideEffects, - id: foundModule.id, - importedIds: foundModule instanceof ExternalModule - ? [] - : foundModule.sources.map(id => foundModule.resolvedIds[id].id), - isEntry: foundModule instanceof Module && foundModule.isEntryPoint, - isExternal: foundModule instanceof ExternalModule - }; - }, - isExternal: getDeprecatedHookHandler((id, parentId, isResolved = false) => graph.moduleLoader.isExternal(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, false), - meta: { - rollupVersion: version - }, - get moduleIds() { - return graph.moduleById.keys(); - }, - parse: graph.contextParse, - resolve(source, importer, options) { - return graph.moduleLoader.resolveId(source, importer, options && options.skipSelf ? pidx : null); - }, - resolveId: getDeprecatedHookHandler((source, importer) => graph.moduleLoader - .resolveId(source, importer) - .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, false), - setAssetSource: fileEmitter.setAssetSource, - warn(warning) { - if (typeof warning === 'string') - warning = { message: warning }; - if (warning.code) - warning.pluginCode = warning.code; - warning.code = 'PLUGIN_WARNING'; - warning.plugin = plugin.name; - graph.warn(warning); - }, - watcher: watcher - ? (() => { - let deprecationWarningShown = false; - function deprecatedWatchListener(event, handler) { - if (!deprecationWarningShown) { - context.warn({ - code: 'PLUGIN_WATCHER_DEPRECATED', - message: `this.watcher usage is deprecated in plugins. Use the watchChange plugin hook and this.addWatchFile() instead.` - }); - deprecationWarningShown = true; - } - return watcher.on(event, handler); - } - return Object.assign({}, watcher, { addListener: deprecatedWatchListener, on: deprecatedWatchListener }); - })() - : undefined - }; - return context; - }); - function runHookSync(hookName, args, pluginIndex, permitValues = false, hookContext) { - const plugin = plugins[pluginIndex]; - let context = pluginContexts[pluginIndex]; - const hook = plugin[hookName]; - if (!hook) - return undefined; - if (hookContext) { - context = hookContext(context, plugin); - if (!context || context === pluginContexts[pluginIndex]) - throw new Error('Internal Rollup error: hookContext must return a new context object.'); - } - try { - // permit values allows values to be returned instead of a functional hook - if (typeof hook !== 'function') { - if (permitValues) - return hook; - error({ - code: 'INVALID_PLUGIN_HOOK', - message: `Error running plugin hook ${hookName} for ${plugin.name}, expected a function hook.` - }); - } - return hook.apply(context, args); - } - catch (err) { - return throwPluginError(err, plugin.name, { hook: hookName }); - } - } - function runHook(hookName, args, pluginIndex, permitValues = false, hookContext) { - const plugin = plugins[pluginIndex]; - let context = pluginContexts[pluginIndex]; - const hook = plugin[hookName]; - if (!hook) - return undefined; - if (hookContext) { - context = hookContext(context, plugin); - if (!context || context === pluginContexts[pluginIndex]) - throw new Error('Internal Rollup error: hookContext must return a new context object.'); - } - return Promise.resolve() - .then(() => { - // permit values allows values to be returned instead of a functional hook - if (typeof hook !== 'function') { - if (permitValues) - return hook; - error({ - code: 'INVALID_PLUGIN_HOOK', - message: `Error running plugin hook ${hookName} for ${plugin.name}, expected a function hook.` - }); - } - return hook.apply(context, args); - }) - .catch(err => throwPluginError(err, plugin.name, { hook: hookName })); - } - const pluginDriver = { - emitFile: fileEmitter.emitFile, - finaliseAssets() { - fileEmitter.assertAssetsFinalized(); - }, - getFileName: fileEmitter.getFileName, - // chains, ignores returns - hookSeq(name, args, hookContext) { - let promise = Promise.resolve(); - for (let i = 0; i < plugins.length; i++) - promise = promise.then(() => runHook(name, args, i, false, hookContext)); - return promise; - }, - // chains, ignores returns - hookSeqSync(name, args, hookContext) { - for (let i = 0; i < plugins.length; i++) - runHookSync(name, args, i, false, hookContext); - }, - // chains, first non-null result stops and returns - hookFirst(name, args, hookContext, skip) { - let promise = Promise.resolve(); - for (let i = 0; i < plugins.length; i++) { - if (skip === i) - continue; - promise = promise.then((result) => { - if (result != null) - return result; - return runHook(name, args, i, false, hookContext); - }); - } - return promise; - }, - // chains synchronously, first non-null result stops and returns - hookFirstSync(name, args, hookContext) { - for (let i = 0; i < plugins.length; i++) { - const result = runHookSync(name, args, i, false, hookContext); - if (result != null) - return result; - } - return null; - }, - // parallel, ignores returns - hookParallel(name, args, hookContext) { - const promises = []; - for (let i = 0; i < plugins.length; i++) { - const hookPromise = runHook(name, args, i, false, hookContext); - if (!hookPromise) - continue; - promises.push(hookPromise); - } - return Promise.all(promises).then(() => { }); - }, - // chains, reduces returns of type R, to type T, handling the reduced value as the first hook argument - hookReduceArg0(name, [arg0, ...args], reduce, hookContext) { - let promise = Promise.resolve(arg0); - for (let i = 0; i < plugins.length; i++) { - promise = promise.then(arg0 => { - const hookPromise = runHook(name, [arg0, ...args], i, false, hookContext); - if (!hookPromise) - return arg0; - return hookPromise.then((result) => reduce.call(pluginContexts[i], arg0, result, plugins[i])); - }); - } - return promise; - }, - // chains synchronously, reduces returns of type R, to type T, handling the reduced value as the first hook argument - hookReduceArg0Sync(name, [arg0, ...args], reduce, hookContext) { - for (let i = 0; i < plugins.length; i++) { - const result = runHookSync(name, [arg0, ...args], i, false, hookContext); - arg0 = reduce.call(pluginContexts[i], arg0, result, plugins[i]); - } - return arg0; - }, - // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values. - hookReduceValue(name, initial, args, reduce, hookContext) { - let promise = Promise.resolve(initial); - for (let i = 0; i < plugins.length; i++) { - promise = promise.then(value => { - const hookPromise = runHook(name, args, i, true, hookContext); - if (!hookPromise) - return value; - return hookPromise.then((result) => reduce.call(pluginContexts[i], value, result, plugins[i])); - }); - } - return promise; - }, - // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values. - hookReduceValueSync(name, initial, args, reduce, hookContext) { - let acc = initial; - for (let i = 0; i < plugins.length; i++) { - const result = runHookSync(name, args, i, true, hookContext); - acc = reduce.call(pluginContexts[i], acc, result, plugins[i]); - } - return acc; - }, - startOutput(outputBundle, assetFileNames) { - fileEmitter.startOutput(outputBundle, assetFileNames); - } - }; - return pluginDriver; -} + function createPluginCache(cache) { return { has(id) { const item = cache[id]; if (!item) @@ -16028,33 +11886,35 @@ delete(id) { return delete cache[id]; } }; } -function trackPluginCache(pluginCache) { - const result = { used: false, cache: undefined }; - result.cache = { - has(id) { - result.used = true; - return pluginCache.has(id); +function getTrackedPluginCache(pluginCache) { + const trackedCache = { + cache: { + has(id) { + trackedCache.used = true; + return pluginCache.has(id); + }, + get(id) { + trackedCache.used = true; + return pluginCache.get(id); + }, + set(id, value) { + trackedCache.used = true; + return pluginCache.set(id, value); + }, + delete(id) { + trackedCache.used = true; + return pluginCache.delete(id); + } }, - get(id) { - result.used = true; - return pluginCache.get(id); - }, - set(id, value) { - result.used = true; - return pluginCache.set(id, value); - }, - delete(id) { - result.used = true; - return pluginCache.delete(id); - } + used: false }; - return result; + return trackedCache; } -const noCache = { +const NO_CACHE = { has() { return false; }, get() { return undefined; @@ -16063,38 +11923,38 @@ delete() { return false; } }; function uncacheablePluginError(pluginName) { - if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX)) - error({ + if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) || + pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) { + return error({ code: 'ANONYMOUS_PLUGIN_CACHE', message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.' }); - else - error({ - code: 'DUPLICATE_PLUGIN_NAME', - message: `The plugin name ${pluginName} 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).` - }); -} -const uncacheablePlugin = pluginName => ({ - has() { - uncacheablePluginError(pluginName); - return false; - }, - get() { - uncacheablePluginError(pluginName); - return undefined; - }, - set() { - uncacheablePluginError(pluginName); - }, - delete() { - uncacheablePluginError(pluginName); - return false; } -}); + return error({ + code: 'DUPLICATE_PLUGIN_NAME', + message: `The plugin name ${pluginName} 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 getCacheForUncacheablePlugin(pluginName) { + return { + has() { + return uncacheablePluginError(pluginName); + }, + get() { + return uncacheablePluginError(pluginName); + }, + set() { + return uncacheablePluginError(pluginName); + }, + delete() { + return uncacheablePluginError(pluginName); + } + }; +} function transform(graph, source, module) { const id = module.id; const sourcemapChain = []; let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map); @@ -16102,10 +11962,11 @@ let ast = source.ast; const transformDependencies = []; const emittedFiles = []; let customTransformCache = false; let moduleSideEffects = null; + let syntheticNamedExports = null; let trackedPluginCache; let curPlugin; const curSource = source.code; function transformReducer(code, result, plugin) { // track which plugins use the custom this.cache to opt-out of transform caching @@ -16143,10 +12004,13 @@ result.map = JSON.parse(result.map); } if (typeof result.moduleSideEffects === 'boolean') { moduleSideEffects = result.moduleSideEffects; } + if (typeof result.syntheticNamedExports === 'boolean') { + syntheticNamedExports = result.syntheticNamedExports; + } } else { return code; } // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning @@ -16162,12 +12026,12 @@ .hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => { curPlugin = plugin; if (curPlugin.cacheKey) customTransformCache = true; else - trackedPluginCache = trackPluginCache(pluginContext.cache); - return Object.assign({}, pluginContext, { cache: trackedPluginCache ? trackedPluginCache.cache : pluginContext.cache, warn(warning, pos) { + trackedPluginCache = getTrackedPluginCache(pluginContext.cache); + return Object.assign(Object.assign({}, pluginContext), { cache: trackedPluginCache ? trackedPluginCache.cache : pluginContext.cache, warn(warning, pos) { if (typeof warning === 'string') warning = { message: warning }; if (pos) augmentCodeLocation(warning, pos, curSource, id); warning.id = id; @@ -16223,11 +12087,11 @@ } if (originalSourcemap !== combinedMap) { originalSourcemap = combinedMap; sourcemapChain.length = 0; } - return new SourceMap(Object.assign({}, combinedMap, { file: null, sourcesContent: combinedMap.sourcesContent })); + return new SourceMap(Object.assign(Object.assign({}, combinedMap), { file: null, sourcesContent: combinedMap.sourcesContent })); } }); }) .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id })) .then(code => { if (!customTransformCache && setAssetSourceErr) @@ -16238,10 +12102,11 @@ customTransformCache, moduleSideEffects, originalCode, originalSourcemap, sourcemapChain, + syntheticNamedExports, transformDependencies }; }); } @@ -16294,11 +12159,11 @@ } const id = resolveIdResult && typeof resolveIdResult === 'object' ? resolveIdResult.id : resolveIdResult; if (typeof id === 'string') { - return this.fetchModule(id, undefined, true, isEntry); + return this.fetchModule(id, undefined, true, false, isEntry); } return error(errUnresolvedEntry(unresolvedId)); }); this.graph = graph; this.modulesById = modulesById; @@ -16391,35 +12256,39 @@ }); }; return getCombinedPromise().then(() => loadNewModulesPromise); } fetchAllDependencies(module) { - const fetchDynamicImportsPromise = Promise.all(module.getDynamicImportExpressions().map((specifier, index) => this.resolveDynamicImport(module, specifier, module.id).then(resolvedId => { - if (resolvedId === null) - return; - const dynamicImport = module.dynamicImports[index]; - if (typeof resolvedId === 'string') { - dynamicImport.resolution = resolvedId; - return; - } - return this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId).then(module => { - dynamicImport.resolution = module; - }); - }))); - fetchDynamicImportsPromise.catch(() => { }); - return Promise.all(module.sources.map(source => this.resolveAndFetchDependency(module, source))).then(() => fetchDynamicImportsPromise); + return Promise.all([ + ...Array.from(module.sources).map((source) => __awaiter(this, void 0, void 0, function* () { + return this.fetchResolvedDependency(source, module.id, (module.resolvedIds[source] = + module.resolvedIds[source] || + this.handleResolveId(yield this.resolveId(source, module.id), source, module.id))); + })), + ...module.getDynamicImportExpressions().map((specifier, index) => this.resolveDynamicImport(module, specifier, module.id).then(resolvedId => { + if (resolvedId === null) + return; + const dynamicImport = module.dynamicImports[index]; + if (typeof resolvedId === 'string') { + dynamicImport.resolution = resolvedId; + return; + } + return this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId).then(module => { + dynamicImport.resolution = module; + }); + })) + ]); } - fetchModule(id, importer, moduleSideEffects, isEntry) { + fetchModule(id, importer, moduleSideEffects, syntheticNamedExports, isEntry) { const existingModule = this.modulesById.get(id); - if (existingModule) { - if (existingModule instanceof ExternalModule) - throw new Error(`Cannot fetch external module ${id}`); + if (existingModule instanceof Module) { existingModule.isEntryPoint = existingModule.isEntryPoint || isEntry; return Promise.resolve(existingModule); } - const module = new Module(this.graph, id, moduleSideEffects, isEntry); + const module = new Module(this.graph, id, moduleSideEffects, syntheticNamedExports, isEntry); this.modulesById.set(id, module); + this.graph.watchFiles[id] = true; const manualChunkAlias = this.getManualChunk(id); if (typeof manualChunkAlias === 'string') { this.addModuleToManualChunk(manualChunkAlias, module); } timeStart('load modules', 3); @@ -16453,10 +12322,13 @@ return cachedModule; } if (typeof sourceDescription.moduleSideEffects === 'boolean') { module.moduleSideEffects = sourceDescription.moduleSideEffects; } + if (typeof sourceDescription.syntheticNamedExports === 'boolean') { + module.syntheticNamedExports = sourceDescription.syntheticNamedExports; + } return transform(this.graph, sourceDescription, module); }) .then((source) => { module.setSource(source); this.modulesById.set(id, module); @@ -16464,24 +12336,24 @@ for (const name in module.exports) { if (name !== 'default') { module.exportsAll[name] = module.id; } } - module.exportAllSources.forEach(source => { + for (const source of module.exportAllSources) { const id = module.resolvedIds[source].id; const exportAllModule = this.modulesById.get(id); if (exportAllModule instanceof ExternalModule) - return; + continue; for (const name in exportAllModule.exportsAll) { if (name in module.exportsAll) { this.graph.warn(errNamespaceConflict(name, module, exportAllModule)); } else { module.exportsAll[name] = exportAllModule.exportsAll[name]; } } - }); + } return module; }); }); } fetchResolvedDependency(source, importer, resolvedId) { @@ -16494,40 +12366,50 @@ return error(errInternalIdCannotBeExternal(source, importer)); } return Promise.resolve(externalModule); } else { - return this.fetchModule(resolvedId.id, importer, resolvedId.moduleSideEffects, false); + return this.fetchModule(resolvedId.id, importer, resolvedId.moduleSideEffects, resolvedId.syntheticNamedExports, false); } } - handleMissingImports(resolvedId, source, importer) { + handleResolveId(resolvedId, source, importer) { if (resolvedId === null) { if (isRelative(source)) { error(errUnresolvedImport(source, importer)); } this.graph.warn(errUnresolvedImportTreatedAsExternal(source, importer)); return { external: true, id: source, - moduleSideEffects: this.hasModuleSideEffects(source, true) + moduleSideEffects: this.hasModuleSideEffects(source, true), + syntheticNamedExports: false }; } + else { + if (resolvedId.external && resolvedId.syntheticNamedExports) { + this.graph.warn(errExternalSyntheticExports(source, importer)); + } + } return resolvedId; } normalizeResolveIdResult(resolveIdResult, importer, source) { let id = ''; let external = false; let moduleSideEffects = null; + let syntheticNamedExports = false; if (resolveIdResult) { if (typeof resolveIdResult === 'object') { id = resolveIdResult.id; if (resolveIdResult.external) { external = true; } if (typeof resolveIdResult.moduleSideEffects === 'boolean') { moduleSideEffects = resolveIdResult.moduleSideEffects; } + if (typeof resolveIdResult.syntheticNamedExports === 'boolean') { + syntheticNamedExports = resolveIdResult.syntheticNamedExports; + } } else { if (this.isExternal(resolveIdResult, importer, true)) { external = true; } @@ -16544,20 +12426,14 @@ return { external, id, moduleSideEffects: typeof moduleSideEffects === 'boolean' ? moduleSideEffects - : this.hasModuleSideEffects(id, external) + : this.hasModuleSideEffects(id, external), + syntheticNamedExports }; } - resolveAndFetchDependency(module, source) { - return __awaiter(this, void 0, void 0, function* () { - return this.fetchResolvedDependency(source, module.id, (module.resolvedIds[source] = - module.resolvedIds[source] || - this.handleMissingImports(yield this.resolveId(source, module.id), source, module.id))); - }); - } resolveDynamicImport(module, specifier, importer) { return __awaiter(this, void 0, void 0, function* () { // TODO we only should expose the acorn AST here const resolution = yield this.pluginDriver.hookFirst('resolveDynamicImport', [ specifier, @@ -16573,17 +12449,24 @@ return Object.assign({ external: false, moduleSideEffects: true }, resolution); } if (resolution == null) { return (module.resolvedIds[specifier] = module.resolvedIds[specifier] || - this.handleMissingImports(yield this.resolveId(specifier, module.id), specifier, module.id)); + this.handleResolveId(yield this.resolveId(specifier, module.id), specifier, module.id)); } - return this.handleMissingImports(this.normalizeResolveIdResult(resolution, importer, specifier), specifier, importer); + return this.handleResolveId(this.normalizeResolveIdResult(resolution, importer, specifier), specifier, importer); }); } } +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 CHAR_CODE_A = 97; const CHAR_CODE_0 = 48; function intToHex(num) { if (num < 10) return String.fromCharCode(CHAR_CODE_0 + num); @@ -16670,10 +12553,520 @@ modulesVisitedForCurrentEntry = new Set(currentEntry.id); addCurrentEntryColourToModule(currentEntry); } } +const createHash$1 = () => createHash$2('sha256'); + +function generateAssetFileName(name, source, output) { + const emittedName = name || 'asset'; + return makeUnique(renderNamePattern(output.assetFileNames, 'output.assetFileNames', { + hash() { + const hash = createHash$1(); + hash.update(emittedName); + hash.update(':'); + hash.update(source); + return hash.digest('hex').substr(0, 8); + }, + ext: () => extname(emittedName).substr(1), + extname: () => extname(emittedName), + name: () => emittedName.substr(0, emittedName.length - extname(emittedName).length) + }), output.bundle); +} +function reserveFileNameInBundle(fileName, bundle, graph) { + if (fileName in bundle) { + graph.warn(errFileNameConflict(fileName)); + } + bundle[fileName] = FILE_PLACEHOLDER; +} +const FILE_PLACEHOLDER = { + type: 'placeholder' +}; +function hasValidType(emittedFile) { + return (emittedFile && + (emittedFile.type === 'asset' || + emittedFile.type === 'chunk')); +} +function hasValidName(emittedFile) { + const validatedName = emittedFile.fileName || emittedFile.name; + return (!validatedName || (typeof validatedName === 'string' && isPlainPathFragment(validatedName))); +} +function getValidSource(source, emittedFile, fileReferenceId) { + if (typeof source !== 'string' && !Buffer.isBuffer(source)) { + const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId; + return error(errFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string of Buffer.`)); + } + return source; +} +function getAssetFileName(file, referenceId) { + if (typeof file.fileName !== 'string') { + return error(errAssetNotFinalisedForFileName(file.name || referenceId)); + } + return file.fileName; +} +function getChunkFileName(file) { + const fileName = file.fileName || (file.module && file.module.facadeChunk.id); + if (!fileName) + return error(errChunkNotGeneratedForFileName(file.fileName || file.name)); + return fileName; +} +class FileEmitter { + constructor(graph, baseFileEmitter) { + this.output = null; + this.assertAssetsFinalized = () => { + for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) { + if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string') + error(errNoAssetSourceSet(emittedFile.name || referenceId)); + } + }; + this.emitFile = (emittedFile) => { + if (!hasValidType(emittedFile)) { + return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && + emittedFile.type}".`)); + } + if (!hasValidName(emittedFile)) { + return error(errFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths and do not contain invalid characters, received "${emittedFile.fileName || + emittedFile.name}".`)); + } + if (emittedFile.type === 'chunk') { + return this.emitChunk(emittedFile); + } + else { + return this.emitAsset(emittedFile); + } + }; + this.getFileName = (fileReferenceId) => { + const emittedFile = this.filesByReferenceId.get(fileReferenceId); + if (!emittedFile) + return error(errFileReferenceIdNotFoundForFilename(fileReferenceId)); + if (emittedFile.type === 'chunk') { + return getChunkFileName(emittedFile); + } + else { + return getAssetFileName(emittedFile, fileReferenceId); + } + }; + this.setAssetSource = (referenceId, requestedSource) => { + const consumedFile = this.filesByReferenceId.get(referenceId); + if (!consumedFile) + return error(errAssetReferenceIdNotFoundForSetSource(referenceId)); + if (consumedFile.type !== 'asset') { + return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`)); + } + if (consumedFile.source !== undefined) { + return error(errAssetSourceAlreadySet(consumedFile.name || referenceId)); + } + const source = getValidSource(requestedSource, consumedFile, referenceId); + if (this.output) { + this.finalizeAsset(consumedFile, source, referenceId, this.output); + } + else { + consumedFile.source = source; + } + }; + this.setOutputBundle = (outputBundle, assetFileNames) => { + this.output = { + assetFileNames, + bundle: outputBundle + }; + for (const emittedFile of this.filesByReferenceId.values()) { + if (emittedFile.fileName) { + reserveFileNameInBundle(emittedFile.fileName, this.output.bundle, this.graph); + } + } + for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) { + if (consumedFile.type === 'asset' && consumedFile.source !== undefined) { + this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.output); + } + } + }; + this.graph = graph; + this.filesByReferenceId = baseFileEmitter + ? new Map(baseFileEmitter.filesByReferenceId) + : new Map(); + } + assignReferenceId(file, idBase) { + let referenceId; + do { + const hash = createHash$1(); + if (referenceId) { + hash.update(referenceId); + } + else { + hash.update(idBase); + } + referenceId = hash.digest('hex').substr(0, 8); + } while (this.filesByReferenceId.has(referenceId)); + this.filesByReferenceId.set(referenceId, file); + return referenceId; + } + emitAsset(emittedAsset) { + const source = typeof emittedAsset.source !== 'undefined' + ? getValidSource(emittedAsset.source, emittedAsset, null) + : undefined; + const consumedAsset = { + fileName: emittedAsset.fileName, + name: emittedAsset.name, + source, + type: 'asset' + }; + const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type); + if (this.output) { + if (emittedAsset.fileName) { + reserveFileNameInBundle(emittedAsset.fileName, this.output.bundle, this.graph); + } + if (source !== undefined) { + this.finalizeAsset(consumedAsset, source, referenceId, this.output); + } + } + return referenceId; + } + emitChunk(emittedChunk) { + if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) { + error(errInvalidRollupPhaseForChunkEmission()); + } + if (typeof emittedChunk.id !== 'string') { + return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`)); + } + const consumedChunk = { + fileName: emittedChunk.fileName, + module: null, + name: emittedChunk.name || emittedChunk.id, + type: 'chunk' + }; + this.graph.moduleLoader + .addEntryModules([ + { + fileName: emittedChunk.fileName || null, + id: emittedChunk.id, + name: emittedChunk.name || null + } + ], false) + .then(({ newEntryModules: [module] }) => { + consumedChunk.module = module; + }) + .catch(() => { + // Avoid unhandled Promise rejection as the error will be thrown later + // once module loading has finished + }); + return this.assignReferenceId(consumedChunk, emittedChunk.id); + } + finalizeAsset(consumedFile, source, referenceId, output) { + const fileName = consumedFile.fileName || + this.findExistingAssetFileNameWithSource(output.bundle, source) || + generateAssetFileName(consumedFile.name, source, output); + // We must not modify the original assets to avoid interaction between outputs + const assetWithFileName = Object.assign(Object.assign({}, consumedFile), { source, fileName }); + this.filesByReferenceId.set(referenceId, assetWithFileName); + const graph = this.graph; + output.bundle[fileName] = { + fileName, + get isAsset() { + graph.warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', false); + return true; + }, + source, + type: 'asset' + }; + } + findExistingAssetFileNameWithSource(bundle, source) { + for (const fileName of Object.keys(bundle)) { + const outputFile = bundle[fileName]; + if (outputFile.type === 'asset' && + (Buffer.isBuffer(source) && Buffer.isBuffer(outputFile.source) + ? source.equals(outputFile.source) + : source === outputFile.source)) + return fileName; + } + return null; + } +} + +function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, graph) { + let deprecationWarningShown = false; + return ((...args) => { + if (!deprecationWarningShown) { + deprecationWarningShown = true; + graph.warnDeprecation({ + message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`, + plugin: pluginName + }, activeDeprecation); + } + return handler(...args); + }); +} +function getPluginContexts(pluginCache, graph, fileEmitter, watcher) { + const existingPluginNames = new Set(); + return (plugin, pidx) => { + let cacheable = true; + if (typeof plugin.cacheKey !== 'string') { + if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) || + plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) || + existingPluginNames.has(plugin.name)) { + cacheable = false; + } + else { + existingPluginNames.add(plugin.name); + } + } + let cacheInstance; + if (!pluginCache) { + cacheInstance = NO_CACHE; + } + else if (cacheable) { + const cacheKey = plugin.cacheKey || plugin.name; + cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null))); + } + else { + cacheInstance = getCacheForUncacheablePlugin(plugin.name); + } + const context = { + addWatchFile(id) { + if (graph.phase >= BuildPhase.GENERATE) + this.error(errInvalidRollupPhaseForAddWatchFile()); + graph.watchFiles[id] = true; + }, + cache: cacheInstance, + emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ type: 'asset', name, source }), 'emitAsset', 'emitFile', plugin.name, false, graph), + emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ type: 'chunk', id, name: options && options.name }), 'emitChunk', 'emitFile', plugin.name, false, graph), + emitFile: fileEmitter.emitFile, + error(err) { + return throwPluginError(err, plugin.name); + }, + getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, false, graph), + getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, false, graph), + getFileName: fileEmitter.getFileName, + getModuleInfo(moduleId) { + const foundModule = graph.moduleById.get(moduleId); + if (foundModule == null) { + throw new Error(`Unable to find module ${moduleId}`); + } + return { + hasModuleSideEffects: foundModule.moduleSideEffects, + id: foundModule.id, + importedIds: foundModule instanceof ExternalModule + ? [] + : Array.from(foundModule.sources).map(id => foundModule.resolvedIds[id].id), + isEntry: foundModule instanceof Module && foundModule.isEntryPoint, + isExternal: foundModule instanceof ExternalModule + }; + }, + isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => graph.moduleLoader.isExternal(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, false, graph), + meta: { + rollupVersion: version + }, + get moduleIds() { + return graph.moduleById.keys(); + }, + parse: graph.contextParse, + resolve(source, importer, options) { + return graph.moduleLoader.resolveId(source, importer, options && options.skipSelf ? pidx : null); + }, + resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader + .resolveId(source, importer) + .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, false, graph), + setAssetSource: fileEmitter.setAssetSource, + warn(warning) { + if (typeof warning === 'string') + warning = { message: warning }; + if (warning.code) + warning.pluginCode = warning.code; + warning.code = 'PLUGIN_WARNING'; + warning.plugin = plugin.name; + graph.warn(warning); + }, + watcher: watcher + ? (() => { + let deprecationWarningShown = false; + function deprecatedWatchListener(event, handler) { + if (!deprecationWarningShown) { + context.warn({ + code: 'PLUGIN_WATCHER_DEPRECATED', + message: `this.watcher usage is deprecated in plugins. Use the watchChange plugin hook and this.addWatchFile() instead.` + }); + deprecationWarningShown = true; + } + return watcher.on(event, handler); + } + return Object.assign(Object.assign({}, watcher), { addListener: deprecatedWatchListener, on: deprecatedWatchListener }); + })() + : undefined + }; + return context; + }; +} + +class PluginDriver { + constructor(graph, userPlugins, pluginCache, preserveSymlinks, watcher, basePluginDriver) { + this.previousHooks = new Set(['options']); + warnDeprecatedHooks(userPlugins, graph); + this.graph = graph; + this.pluginCache = pluginCache; + this.preserveSymlinks = preserveSymlinks; + this.watcher = watcher; + this.fileEmitter = new FileEmitter(graph, basePluginDriver && basePluginDriver.fileEmitter); + this.emitFile = this.fileEmitter.emitFile; + this.getFileName = this.fileEmitter.getFileName; + this.finaliseAssets = this.fileEmitter.assertAssetsFinalized; + this.setOutputBundle = this.fileEmitter.setOutputBundle; + this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : [getRollupDefaultPlugin(preserveSymlinks)]); + this.pluginContexts = this.plugins.map(getPluginContexts(pluginCache, graph, this.fileEmitter, watcher)); + if (basePluginDriver) { + for (const plugin of userPlugins) { + for (const hook of basePluginDriver.previousHooks) { + if (hook in plugin) { + graph.warn(errInputHookInOutputPlugin(plugin.name, hook)); + } + } + } + } + } + createOutputPluginDriver(plugins) { + return new PluginDriver(this.graph, plugins, this.pluginCache, this.preserveSymlinks, this.watcher, this); + } + // chains, first non-null result stops and returns + hookFirst(hookName, args, replaceContext, skip) { + let promise = Promise.resolve(); + for (let i = 0; i < this.plugins.length; i++) { + if (skip === i) + continue; + promise = promise.then((result) => { + if (result != null) + return result; + return this.runHook(hookName, args, i, false, replaceContext); + }); + } + return promise; + } + // chains synchronously, first non-null result stops and returns + hookFirstSync(hookName, args, replaceContext) { + for (let i = 0; i < this.plugins.length; i++) { + const result = this.runHookSync(hookName, args, i, replaceContext); + if (result != null) + return result; + } + return null; + } + // parallel, ignores returns + hookParallel(hookName, args, replaceContext) { + const promises = []; + for (let i = 0; i < this.plugins.length; i++) { + const hookPromise = this.runHook(hookName, args, i, false, replaceContext); + if (!hookPromise) + continue; + promises.push(hookPromise); + } + return Promise.all(promises).then(() => { }); + } + // chains, reduces returns of type R, to type T, handling the reduced value as the first hook argument + hookReduceArg0(hookName, [arg0, ...args], reduce, replaceContext) { + let promise = Promise.resolve(arg0); + for (let i = 0; i < this.plugins.length; i++) { + promise = promise.then(arg0 => { + const hookPromise = this.runHook(hookName, [arg0, ...args], i, false, replaceContext); + if (!hookPromise) + return arg0; + return hookPromise.then((result) => reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i])); + }); + } + return promise; + } + // chains synchronously, reduces returns of type R, to type T, handling the reduced value as the first hook argument + hookReduceArg0Sync(hookName, [arg0, ...args], reduce, replaceContext) { + for (let i = 0; i < this.plugins.length; i++) { + const result = this.runHookSync(hookName, [arg0, ...args], i, replaceContext); + arg0 = reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]); + } + return arg0; + } + // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values. + hookReduceValue(hookName, initialValue, args, reduce, replaceContext) { + let promise = Promise.resolve(initialValue); + for (let i = 0; i < this.plugins.length; i++) { + promise = promise.then(value => { + const hookPromise = this.runHook(hookName, args, i, true, replaceContext); + if (!hookPromise) + return value; + return hookPromise.then((result) => reduce.call(this.pluginContexts[i], value, result, this.plugins[i])); + }); + } + return promise; + } + // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values. + hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) { + let acc = initialValue; + for (let i = 0; i < this.plugins.length; i++) { + const result = this.runHookSync(hookName, args, i, replaceContext); + acc = reduce.call(this.pluginContexts[i], acc, result, this.plugins[i]); + } + return acc; + } + // chains, ignores returns + hookSeq(hookName, args, replaceContext) { + return __awaiter(this, void 0, void 0, function* () { + let promise = Promise.resolve(); + for (let i = 0; i < this.plugins.length; i++) + promise = promise.then(() => this.runHook(hookName, args, i, false, replaceContext)); + return promise; + }); + } + // chains, ignores returns + hookSeqSync(hookName, args, replaceContext) { + for (let i = 0; i < this.plugins.length; i++) + this.runHookSync(hookName, args, i, replaceContext); + } + runHook(hookName, args, pluginIndex, permitValues, hookContext) { + this.previousHooks.add(hookName); + const plugin = this.plugins[pluginIndex]; + const hook = plugin[hookName]; + if (!hook) + return undefined; + let context = this.pluginContexts[pluginIndex]; + if (hookContext) { + context = hookContext(context, plugin); + } + return Promise.resolve() + .then(() => { + // permit values allows values to be returned instead of a functional hook + if (typeof hook !== 'function') { + if (permitValues) + return hook; + error({ + code: 'INVALID_PLUGIN_HOOK', + message: `Error running plugin hook ${hookName} for ${plugin.name}, expected a function hook.` + }); + } + return hook.apply(context, args); + }) + .catch(err => throwPluginError(err, plugin.name, { hook: hookName })); + } + runHookSync(hookName, args, pluginIndex, hookContext) { + this.previousHooks.add(hookName); + const plugin = this.plugins[pluginIndex]; + let context = this.pluginContexts[pluginIndex]; + const hook = plugin[hookName]; + if (!hook) + return undefined; + if (hookContext) { + context = hookContext(context, plugin); + } + try { + // permit values allows values to be returned instead of a functional hook + if (typeof hook !== 'function') { + error({ + code: 'INVALID_PLUGIN_HOOK', + message: `Error running plugin hook ${hookName} for ${plugin.name}, expected a function hook.` + }); + } + return hook.apply(context, args); + } + catch (err) { + return throwPluginError(err, plugin.name, { hook: hookName }); + } + } +} + function makeOnwarn() { const warned = Object.create(null); return (warning) => { const str = warning.toString(); if (str in warned) @@ -16702,11 +13095,11 @@ this.phase = BuildPhase.LOAD_AND_PARSE; this.watchFiles = Object.create(null); this.externalModules = []; this.modules = []; this.onwarn = options.onwarn || makeOnwarn(); - this.deoptimizationTracker = new EntityPathTracker(); + this.deoptimizationTracker = new PathTracker(); this.cachedModules = new Map(); if (options.cache) { if (options.cache.modules) for (const module of options.cache.modules) this.cachedModules.set(module.id, module); @@ -16722,30 +13115,33 @@ } this.preserveModules = options.preserveModules; this.strictDeprecations = options.strictDeprecations; this.cacheExpiry = options.experimentalCacheExpiry; if (options.treeshake !== false) { - this.treeshakingOptions = options.treeshake - ? { - annotations: options.treeshake.annotations !== false, - moduleSideEffects: options.treeshake.moduleSideEffects, - propertyReadSideEffects: options.treeshake.propertyReadSideEffects !== false, - pureExternalModules: options.treeshake.pureExternalModules, - tryCatchDeoptimization: options.treeshake.tryCatchDeoptimization !== false - } - : { - annotations: true, - moduleSideEffects: true, - propertyReadSideEffects: true, - tryCatchDeoptimization: true - }; + this.treeshakingOptions = + options.treeshake && options.treeshake !== true + ? { + annotations: options.treeshake.annotations !== false, + moduleSideEffects: options.treeshake.moduleSideEffects, + propertyReadSideEffects: options.treeshake.propertyReadSideEffects !== false, + pureExternalModules: options.treeshake.pureExternalModules, + tryCatchDeoptimization: options.treeshake.tryCatchDeoptimization !== false, + unknownGlobalSideEffects: options.treeshake.unknownGlobalSideEffects !== false + } + : { + annotations: true, + moduleSideEffects: true, + propertyReadSideEffects: true, + tryCatchDeoptimization: true, + unknownGlobalSideEffects: true + }; if (typeof this.treeshakingOptions.pureExternalModules !== 'undefined') { this.warnDeprecation(`The "treeshake.pureExternalModules" option is deprecated. The "treeshake.moduleSideEffects" option should be used instead. "treeshake.pureExternalModules: true" is equivalent to "treeshake.moduleSideEffects: 'no-external'"`, false); } } - this.contextParse = (code, options = {}) => this.acornParser.parse(code, Object.assign({}, defaultAcornOptions, options, this.acornOptions)); - this.pluginDriver = createPluginDriver(this, options, this.pluginCache, watcher); + this.contextParse = (code, options = {}) => this.acornParser.parse(code, Object.assign(Object.assign(Object.assign({}, defaultAcornOptions), options), this.acornOptions)); + this.pluginDriver = new PluginDriver(this, options.plugins, this.pluginCache, options.preserveSymlinks === true, watcher); if (watcher) { const handleChange = (id) => this.pluginDriver.hookSeqSync('watchChange', [id]); watcher.on('change', handleChange); watcher.once('restart', () => { watcher.removeListener('change', handleChange); @@ -16768,26 +13164,22 @@ else { this.getModuleContext = () => this.context; } this.acornOptions = options.acorn ? Object.assign({}, options.acorn) : {}; const acornPluginsToInject = []; - acornPluginsToInject.push(acornImportMeta); + acornPluginsToInject.push(acornImportMeta, acornExportNsFrom); if (options.experimentalTopLevelAwait) { this.acornOptions.allowAwaitOutsideFunction = true; } const acornInjectPlugins = options.acornInjectPlugins; acornPluginsToInject.push(...(Array.isArray(acornInjectPlugins) ? acornInjectPlugins : acornInjectPlugins ? [acornInjectPlugins] : [])); this.acornParser = Parser.extend(...acornPluginsToInject); - this.moduleLoader = new ModuleLoader(this, this.moduleById, this.pluginDriver, options.external, (typeof options.manualChunks === 'function' && options.manualChunks), (this.treeshakingOptions - ? this.treeshakingOptions.moduleSideEffects - : null), (this.treeshakingOptions - ? this.treeshakingOptions.pureExternalModules - : false)); + this.moduleLoader = new ModuleLoader(this, this.moduleById, this.pluginDriver, options.external, (typeof options.manualChunks === 'function' && options.manualChunks), (this.treeshakingOptions ? this.treeshakingOptions.moduleSideEffects : null), (this.treeshakingOptions ? this.treeshakingOptions.pureExternalModules : false)); } build(entryModules, manualChunks, inlineDynamicImports) { // Phase 1 – discovery. We load the entry module and find which // modules it imports, and import those, until we have all // of the entry module's dependencies @@ -16802,11 +13194,10 @@ throw new Error('You must supply options.input to rollup'); } for (const module of this.moduleById.values()) { if (module instanceof Module) { this.modules.push(module); - this.watchFiles[module.id] = true; } else { this.externalModules.push(module); } } @@ -16949,10 +13340,11 @@ } const { orderedModules, cyclePaths } = analyseModuleExecution(entryModules); for (const cyclePath of cyclePaths) { this.warn({ code: 'CIRCULAR_DEPENDENCY', + cycle: cyclePath, importer: cyclePath[0], message: `Circular dependency: ${cyclePath.join(' -> ')}` }); } this.modules = orderedModules; @@ -16989,17 +13381,16 @@ return ''; } } const concatSep = (out, next) => (next ? `${out}\n${next}` : out); const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out); -function createAddons(graph, options) { - const pluginDriver = graph.pluginDriver; +function createAddons(options, outputPluginDriver) { return Promise.all([ - pluginDriver.hookReduceValue('banner', evalIfFn(options.banner), [], concatSep), - pluginDriver.hookReduceValue('footer', evalIfFn(options.footer), [], concatSep), - pluginDriver.hookReduceValue('intro', evalIfFn(options.intro), [], concatDblSep), - pluginDriver.hookReduceValue('outro', evalIfFn(options.outro), [], concatDblSep) + outputPluginDriver.hookReduceValue('banner', evalIfFn(options.banner), [], concatSep), + outputPluginDriver.hookReduceValue('footer', evalIfFn(options.footer), [], concatSep), + outputPluginDriver.hookReduceValue('intro', evalIfFn(options.intro), [], concatDblSep), + outputPluginDriver.hookReduceValue('outro', evalIfFn(options.outro), [], concatDblSep) ]) .then(([banner, footer, intro, outro]) => { if (intro) intro += '\n\n'; if (outro) @@ -17017,39 +13408,29 @@ \tError Message: ${err.message}` }); }); } -function assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, bundle) { +function assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, bundle, outputPluginDriver) { const entryChunks = []; const otherChunks = []; for (const chunk of chunks) { (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint ? entryChunks : otherChunks).push(chunk); } // make sure entry chunk names take precedence with regard to deconflicting const chunksForNaming = entryChunks.concat(otherChunks); for (const chunk of chunksForNaming) { - const facadeModule = chunk.facadeModule; if (outputOptions.file) { chunk.id = basename(outputOptions.file); } else if (inputOptions.preserveModules) { - chunk.id = chunk.generateIdPreserveModules(inputBase, bundle); + chunk.id = chunk.generateIdPreserveModules(inputBase, outputOptions, bundle); } else { - let pattern, patternName; - if (facadeModule && facadeModule.isUserDefinedEntryPoint) { - pattern = outputOptions.entryFileNames || '[name].js'; - patternName = 'output.entryFileNames'; - } - else { - pattern = outputOptions.chunkFileNames || '[name]-[hash].js'; - patternName = 'output.chunkFileNames'; - } - chunk.id = chunk.generateId(pattern, patternName, addons, outputOptions, bundle); + chunk.id = chunk.generateId(addons, outputOptions, bundle, true, outputPluginDriver); } bundle[chunk.id] = FILE_PLACEHOLDER; } } @@ -17069,55 +13450,34 @@ }, files[0].split(/\/+|\\+/)); // Windows correctly handles paths with forward-slashes return commonSegments.length > 1 ? commonSegments.join('/') : '/'; } -function badExports(option, keys) { - error({ - code: 'INVALID_EXPORT_OPTION', - message: `'${option}' was specified for output.exports, but entry module has following exports: ${keys.join(', ')}` - }); -} -function getExportMode(chunk, { exports: exportMode, name, format }) { +function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId) { const exportKeys = chunk.getExportNames(); if (exportMode === 'default') { if (exportKeys.length !== 1 || exportKeys[0] !== 'default') { - badExports('default', exportKeys); + error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId)); } } else if (exportMode === 'none' && exportKeys.length) { - badExports('none', exportKeys); + error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId)); } if (!exportMode || exportMode === 'auto') { if (exportKeys.length === 0) { exportMode = 'none'; } else if (exportKeys.length === 1 && exportKeys[0] === 'default') { exportMode = 'default'; } else { - if (chunk.facadeModule !== null && - chunk.facadeModule.isEntryPoint && - format !== 'es' && - exportKeys.indexOf('default') !== -1) { - chunk.graph.warn({ - code: 'MIXED_EXPORTS', - message: `Using named and default exports together. Consumers of your bundle will have to use ${name || - 'bundle'}['default'] to access the default export, which may not be what you want. Use \`output.exports: 'named'\` to disable this warning`, - url: `https://rollupjs.org/guide/en/#output-exports` - }); + if (format !== 'es' && exportKeys.indexOf('default') !== -1) { + chunk.graph.warn(errMixedExport(facadeModuleId, name)); } exportMode = 'named'; } } - if (!/(?:default|named|none)/.test(exportMode)) { - error({ - code: 'INVALID_EXPORT_OPTION', - message: `output.exports must be 'default', 'named', 'none', 'auto', or left unspecified (defaults to 'auto')`, - url: `https://rollupjs.org/guide/en/#output-exports` - }); - } return exportMode; } const createGetOption = (config, command) => (name, defaultValue) => command[name] !== undefined ? command[name] @@ -17135,14 +13495,23 @@ }; const getObjectOption = (config, command, name) => { const commandOption = normalizeObjectOptionValue(command[name]); const configOption = normalizeObjectOptionValue(config[name]); if (commandOption !== undefined) { - return commandOption && configOption ? Object.assign({}, configOption, commandOption) : commandOption; + return commandOption && configOption ? Object.assign(Object.assign({}, configOption), commandOption) : commandOption; } return configOption; }; +function ensureArray(items) { + if (Array.isArray(items)) { + return items.filter(Boolean); + } + if (items) { + return [items]; + } + return []; +} const defaultOnWarn = warning => { if (typeof warning === 'string') { console.warn(warning); } else { @@ -17191,27 +13560,30 @@ const validInputOptions = Object.keys(inputOptions); addUnknownOptionErrors(unknownOptionErrors, Object.keys(config), validInputOptions, 'input option', /^output$/); const validOutputOptions = Object.keys(outputOptions[0]); addUnknownOptionErrors(unknownOptionErrors, outputOptions.reduce((allKeys, options) => allKeys.concat(Object.keys(options)), []), validOutputOptions, 'output option'); const validCliOutputOptions = validOutputOptions.filter(option => option !== 'sourcemapPathTransform'); - addUnknownOptionErrors(unknownOptionErrors, Object.keys(command), validInputOptions.concat(validCliOutputOptions, Object.keys(commandAliases), 'config', 'environment', 'silent'), 'CLI flag', /^_|output|(config.*)$/); + addUnknownOptionErrors(unknownOptionErrors, Object.keys(command), validInputOptions.concat(validCliOutputOptions, Object.keys(commandAliases), 'config', 'environment', 'silent', 'stdin'), 'CLI flag', /^_|output|(config.*)$/); return { inputOptions, optionError: unknownOptionErrors.length > 0 ? unknownOptionErrors.join('\n') : null, outputOptions }; } function addUnknownOptionErrors(errors, options, validOptions, optionType, ignoredKeys = /$./) { - const unknownOptions = options.filter(key => validOptions.indexOf(key) === -1 && !ignoredKeys.test(key)); + const validOptionSet = new Set(validOptions); + const unknownOptions = options.filter(key => !validOptionSet.has(key) && !ignoredKeys.test(key)); if (unknownOptions.length > 0) - errors.push(`Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${validOptions.sort().join(', ')}`); + errors.push(`Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${Array.from(validOptionSet) + .sort() + .join(', ')}`); } function getCommandOptions(rawCommandOptions) { const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string' ? rawCommandOptions.external.split(',') : []; - return Object.assign({}, rawCommandOptions, { external, globals: typeof rawCommandOptions.globals === 'string' + return Object.assign(Object.assign({}, rawCommandOptions), { external, globals: typeof rawCommandOptions.globals === 'string' ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => { const [id, variableName] = globalDefinition.split(':'); globals[id] = variableName; if (external.indexOf(id) === -1) { external.push(id); @@ -17225,22 +13597,22 @@ const inputOptions = { acorn: config.acorn, acornInjectPlugins: config.acornInjectPlugins, cache: getOption('cache'), chunkGroupingSize: getOption('chunkGroupingSize', 5000), - context: config.context, + context: getOption('context'), experimentalCacheExpiry: getOption('experimentalCacheExpiry', 10), experimentalOptimizeChunks: getOption('experimentalOptimizeChunks'), experimentalTopLevelAwait: getOption('experimentalTopLevelAwait'), external: getExternal(config, command), inlineDynamicImports: getOption('inlineDynamicImports', false), input: getOption('input', []), manualChunks: getOption('manualChunks'), moduleContext: config.moduleContext, onwarn: getOnWarn(config, defaultOnWarnHandler), perf: getOption('perf', false), - plugins: config.plugins, + plugins: ensureArray(config.plugins), preserveModules: getOption('preserveModules'), preserveSymlinks: getOption('preserveSymlinks'), shimMissingExports: getOption('shimMissingExports'), strictDeprecations: getOption('strictDeprecations', false), treeshake: getObjectOption(config, command, 'treeshake'), @@ -17254,19 +13626,20 @@ function getOutputOptions(config, command = {}) { const getOption = createGetOption(config, command); let format = getOption('format'); // Handle format aliases switch (format) { + case undefined: case 'esm': case 'module': format = 'es'; break; case 'commonjs': format = 'cjs'; } return { - amd: Object.assign({}, config.amd, command.amd), + amd: Object.assign(Object.assign({}, config.amd), command.amd), assetFileNames: getOption('assetFileNames'), banner: getOption('banner'), chunkFileNames: getOption('chunkFileNames'), compact: getOption('compact', false), dir: getOption('dir'), @@ -17276,21 +13649,22 @@ exports: getOption('exports'), extend: getOption('extend'), externalLiveBindings: getOption('externalLiveBindings', true), file: getOption('file'), footer: getOption('footer'), - format: format === 'esm' ? 'es' : format, + format, freeze: getOption('freeze', true), globals: getOption('globals'), indent: getOption('indent', true), interop: getOption('interop', true), intro: getOption('intro'), name: getOption('name'), namespaceToStringTag: getOption('namespaceToStringTag', false), noConflict: getOption('noConflict'), outro: getOption('outro'), paths: getOption('paths'), + plugins: ensureArray(config.plugins), preferConst: getOption('preferConst'), sourcemap: getOption('sourcemap'), sourcemapExcludeSources: getOption('sourcemapExcludeSources'), sourcemapFile: getOption('sourcemapFile'), sourcemapPathTransform: getOption('sourcemapPathTransform'), @@ -17309,10 +13683,13 @@ error({ message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "esm", "iife" or "umd".`, url: `https://rollupjs.org/guide/en/#output-format` }); } + if (options.exports && !['default', 'named', 'none', 'auto'].includes(options.exports)) { + error(errInvalidExportOptionValue(options.exports)); + } } function getAbsoluteEntryModulePaths(chunks) { const absoluteEntryModulePaths = []; for (const chunk of chunks) { for (const entryModule of chunk.entryModules) { @@ -17331,36 +13708,31 @@ function applyOptionHook(inputOptions, plugin) { if (plugin.options) return plugin.options.call({ meta: { rollupVersion: version } }, inputOptions) || inputOptions; return inputOptions; } -function ensureArray(items) { - if (Array.isArray(items)) { - return items.filter(Boolean); +function normalizePlugins(rawPlugins, anonymousPrefix) { + const plugins = ensureArray(rawPlugins); + for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) { + const plugin = plugins[pluginIndex]; + if (!plugin.name) { + plugin.name = `${anonymousPrefix}${pluginIndex + 1}`; + } } - if (items) { - return [items]; - } - return []; + return plugins; } function getInputOptions$1(rawInputOptions) { if (!rawInputOptions) { throw new Error('You must supply an options object to rollup'); } let { inputOptions, optionError } = mergeOptions({ config: rawInputOptions }); if (optionError) inputOptions.onwarn({ message: optionError, code: 'UNKNOWN_OPTION' }); - inputOptions = ensureArray(inputOptions.plugins).reduce(applyOptionHook, inputOptions); - inputOptions.plugins = ensureArray(inputOptions.plugins); - for (let pluginIndex = 0; pluginIndex < inputOptions.plugins.length; pluginIndex++) { - const plugin = inputOptions.plugins[pluginIndex]; - if (!plugin.name) { - plugin.name = `${ANONYMOUS_PLUGIN_PREFIX}${pluginIndex + 1}`; - } - } + inputOptions = inputOptions.plugins.reduce(applyOptionHook, inputOptions); + inputOptions.plugins = normalizePlugins(inputOptions.plugins, ANONYMOUS_PLUGIN_PREFIX); if (inputOptions.inlineDynamicImports) { if (inputOptions.preserveModules) error({ code: 'INVALID_OPTION', message: `"preserveModules" does not support the "inlineDynamicImports" option.` @@ -17415,11 +13787,12 @@ isEntry: facadeModule !== null && facadeModule.isEntryPoint, map: undefined, modules: chunk.renderedModules, get name() { return chunk.getChunkName(); - } + }, + type: 'chunk' }; } return outputBundle; } function rollup(rawInputOptions) { @@ -17437,97 +13810,118 @@ try { yield graph.pluginDriver.hookParallel('buildStart', [inputOptions]); chunks = yield graph.build(inputOptions.input, inputOptions.manualChunks, inputOptions.inlineDynamicImports); } catch (err) { + const watchFiles = Object.keys(graph.watchFiles); + if (watchFiles.length > 0) { + err.watchFiles = watchFiles; + } yield graph.pluginDriver.hookParallel('buildEnd', [err]); throw err; } yield graph.pluginDriver.hookParallel('buildEnd', []); timeEnd('BUILD', 1); // ensure we only do one optimization pass per build let optimized = false; - function getOutputOptions(rawOutputOptions) { - return normalizeOutputOptions(inputOptions, rawOutputOptions, chunks.length > 1, graph.pluginDriver); + function getOutputOptionsAndPluginDriver(rawOutputOptions) { + if (!rawOutputOptions) { + throw new Error('You must supply an options object'); + } + const outputPluginDriver = graph.pluginDriver.createOutputPluginDriver(normalizePlugins(rawOutputOptions.plugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX)); + return { + outputOptions: normalizeOutputOptions(inputOptions, rawOutputOptions, chunks.length > 1, outputPluginDriver), + outputPluginDriver + }; } - function generate(outputOptions, isWrite) { + function generate(outputOptions, isWrite, outputPluginDriver) { return __awaiter(this, void 0, void 0, function* () { timeStart('GENERATE', 1); const assetFileNames = outputOptions.assetFileNames || 'assets/[name]-[hash][extname]'; + const inputBase = commondir(getAbsoluteEntryModulePaths(chunks)); const outputBundleWithPlaceholders = Object.create(null); + outputPluginDriver.setOutputBundle(outputBundleWithPlaceholders, assetFileNames); let outputBundle; - const inputBase = commondir(getAbsoluteEntryModulePaths(chunks)); - graph.pluginDriver.startOutput(outputBundleWithPlaceholders, assetFileNames); try { - yield graph.pluginDriver.hookParallel('renderStart', []); - const addons = yield createAddons(graph, outputOptions); + yield outputPluginDriver.hookParallel('renderStart', [outputOptions, inputOptions]); + const addons = yield createAddons(outputOptions, outputPluginDriver); for (const chunk of chunks) { if (!inputOptions.preserveModules) chunk.generateInternalExports(outputOptions); - if (chunk.facadeModule && chunk.facadeModule.isEntryPoint) - chunk.exportMode = getExportMode(chunk, outputOptions); + if (inputOptions.preserveModules || (chunk.facadeModule && chunk.facadeModule.isEntryPoint)) + chunk.exportMode = getExportMode(chunk, outputOptions, chunk.facadeModule.id); } for (const chunk of chunks) { chunk.preRender(outputOptions, inputBase); } if (!optimized && inputOptions.experimentalOptimizeChunks) { optimizeChunks(chunks, outputOptions, inputOptions.chunkGroupingSize, inputBase); optimized = true; } - assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, outputBundleWithPlaceholders); + assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, outputBundleWithPlaceholders, outputPluginDriver); outputBundle = assignChunksToBundle(chunks, outputBundleWithPlaceholders); yield Promise.all(chunks.map(chunk => { const outputChunk = outputBundleWithPlaceholders[chunk.id]; - return chunk.render(outputOptions, addons, outputChunk).then(rendered => { + return chunk + .render(outputOptions, addons, outputChunk, outputPluginDriver) + .then(rendered => { outputChunk.code = rendered.code; outputChunk.map = rendered.map; - return graph.pluginDriver.hookParallel('ongenerate', [ + return outputPluginDriver.hookParallel('ongenerate', [ Object.assign({ bundle: outputChunk }, outputOptions), outputChunk ]); }); })); } catch (error) { - yield graph.pluginDriver.hookParallel('renderError', [error]); + yield outputPluginDriver.hookParallel('renderError', [error]); throw error; } - yield graph.pluginDriver.hookSeq('generateBundle', [outputOptions, outputBundle, isWrite]); - graph.pluginDriver.finaliseAssets(); + yield outputPluginDriver.hookSeq('generateBundle', [outputOptions, outputBundle, isWrite]); + for (const key of Object.keys(outputBundle)) { + const file = outputBundle[key]; + if (!file.type) { + graph.warnDeprecation('A plugin is directly adding properties to the bundle object in the "generateBundle" hook. This is deprecated and will be removed in a future Rollup version, please use "this.emitFile" instead.', false); + file.type = 'asset'; + } + } + outputPluginDriver.finaliseAssets(); timeEnd('GENERATE', 1); return outputBundle; }); } const cache = useCache ? graph.getCache() : undefined; const result = { cache: cache, generate: ((rawOutputOptions) => { - const promise = generate(getOutputOptions(rawOutputOptions), false).then(result => createOutput(result)); + const { outputOptions, outputPluginDriver } = getOutputOptionsAndPluginDriver(rawOutputOptions); + const promise = generate(outputOptions, false, outputPluginDriver).then(result => createOutput(result)); Object.defineProperty(promise, 'code', throwAsyncGenerateError); Object.defineProperty(promise, 'map', throwAsyncGenerateError); return promise; }), watchFiles: Object.keys(graph.watchFiles), write: ((rawOutputOptions) => { - const outputOptions = getOutputOptions(rawOutputOptions); + const { outputOptions, outputPluginDriver } = getOutputOptionsAndPluginDriver(rawOutputOptions); if (!outputOptions.dir && !outputOptions.file) { error({ code: 'MISSING_OPTION', message: 'You must specify "output.file" or "output.dir" for the build.' }); } - return generate(outputOptions, true).then((bundle) => __awaiter(this, void 0, void 0, function* () { - let chunkCnt = 0; + return generate(outputOptions, true, outputPluginDriver).then((bundle) => __awaiter(this, void 0, void 0, function* () { + let chunkCount = 0; for (const fileName of Object.keys(bundle)) { const file = bundle[fileName]; - if (file.isAsset) + if (file.type === 'asset') continue; - chunkCnt++; - if (chunkCnt > 1) + chunkCount++; + if (chunkCount > 1) break; } - if (chunkCnt > 1) { + if (chunkCount > 1) { if (outputOptions.sourcemapFile) error({ code: 'INVALID_OPTION', message: '"output.sourcemapFile" is only supported for single-file builds.' }); @@ -17539,12 +13933,12 @@ inputOptions.inlineDynamicImports === true ? '' : ' To inline dynamic imports, set the "inlineDynamicImports" option.') }); } - yield Promise.all(Object.keys(bundle).map(chunkId => writeOutputFile(graph, result, bundle[chunkId], outputOptions))); - yield graph.pluginDriver.hookParallel('writeBundle', [bundle]); + yield Promise.all(Object.keys(bundle).map(chunkId => writeOutputFile(result, bundle[chunkId], outputOptions, outputPluginDriver))); + yield outputPluginDriver.hookParallel('writeBundle', [bundle]); return createOutput(bundle); })); }) }; if (inputOptions.perf === true) @@ -17557,11 +13951,11 @@ SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK"; SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK"; SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET"; })(SortingFileType || (SortingFileType = {})); function getSortingFileType(file) { - if (file.isAsset) { + if (file.type === 'asset') { return SortingFileType.ASSET; } if (file.isEntry) { return SortingFileType.ENTRY_CHUNK; } @@ -17578,18 +13972,15 @@ return 0; return fileTypeA < fileTypeB ? -1 : 1; }) }; } -function isOutputAsset(file) { - return file.isAsset === true; -} -function writeOutputFile(graph, build, outputFile, outputOptions) { +function writeOutputFile(build, outputFile, outputOptions, outputPluginDriver) { const fileName = resolve(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName); let writeSourceMapPromise; let source; - if (isOutputAsset(outputFile)) { + if (outputFile.type === 'asset') { source = outputFile.source; } else { source = outputFile.code; if (outputOptions.sourcemap && outputFile.map) { @@ -17599,39 +13990,38 @@ } else { url = `${basename(outputFile.fileName)}.map`; writeSourceMapPromise = writeFile(`${fileName}.map`, outputFile.map.toString()); } - source += `//# ${SOURCEMAPPING_URL}=${url}\n`; + if (outputOptions.sourcemap !== 'hidden') { + source += `//# ${SOURCEMAPPING_URL}=${url}\n`; + } } } return writeFile(fileName, source) .then(() => writeSourceMapPromise) - .then(() => !isOutputAsset(outputFile) && - graph.pluginDriver.hookSeq('onwrite', [ + .then(() => outputFile.type === 'chunk' && + outputPluginDriver.hookSeq('onwrite', [ Object.assign({ bundle: build }, outputOptions), outputFile ])) .then(() => { }); } -function normalizeOutputOptions(inputOptions, rawOutputOptions, hasMultipleChunks, pluginDriver) { - if (!rawOutputOptions) { - throw new Error('You must supply an options object'); - } +function normalizeOutputOptions(inputOptions, rawOutputOptions, hasMultipleChunks, outputPluginDriver) { const mergedOptions = mergeOptions({ config: { - output: Object.assign({}, rawOutputOptions, rawOutputOptions.output, inputOptions.output) + output: Object.assign(Object.assign(Object.assign({}, rawOutputOptions), rawOutputOptions.output), inputOptions.output) } }); if (mergedOptions.optionError) throw new Error(mergedOptions.optionError); // now outputOptions is an array, but rollup.rollup API doesn't support arrays const mergedOutputOptions = mergedOptions.outputOptions[0]; const outputOptionsReducer = (outputOptions, result) => result || outputOptions; - const outputOptions = pluginDriver.hookReduceArg0Sync('outputOptions', [mergedOutputOptions], outputOptionsReducer, pluginContext => { + const outputOptions = outputPluginDriver.hookReduceArg0Sync('outputOptions', [mergedOutputOptions], outputOptionsReducer, pluginContext => { const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook()); - return Object.assign({}, pluginContext, { emitFile: emitError, setAssetSource: emitError }); + return Object.assign(Object.assign({}, pluginContext), { emitFile: emitError, setAssetSource: emitError }); }); checkOutputOptions(outputOptions); if (typeof outputOptions.file === 'string') { if (typeof outputOptions.dir === 'string') error({ @@ -18262,11 +14652,11 @@ if (node.value) { return node.value; } if (node.nodes && node.ranges > 0) { let args = utils$1.reduce(node.nodes); - let range = fillRange(...args, Object.assign({}, options, { wrap: false, toRegex: true })); + let range = fillRange(...args, Object.assign(Object.assign({}, options), { wrap: false, toRegex: true })); if (range.length !== 0) { return args.length > 1 && range.length > 1 ? `(${range})` : range; } } if (node.nodes) { @@ -18856,11 +15246,11 @@ START_ANCHOR }; /** * Windows glob regex */ -const WINDOWS_CHARS = Object.assign({}, POSIX_CHARS, { SLASH_LITERAL: `[${WIN_SLASH}]`, QMARK: WIN_NO_SLASH, STAR: `${WIN_NO_SLASH}*?`, DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, NO_DOT: `(?!${DOT_LITERAL})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH}]`, START_ANCHOR: `(?:^|[${WIN_SLASH}])`, END_ANCHOR: `(?:[${WIN_SLASH}]|$)` }); +const WINDOWS_CHARS = Object.assign(Object.assign({}, POSIX_CHARS), { SLASH_LITERAL: `[${WIN_SLASH}]`, QMARK: WIN_NO_SLASH, STAR: `${WIN_NO_SLASH}*?`, DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, NO_DOT: `(?!${DOT_LITERAL})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH}]`, START_ANCHOR: `(?:^|[${WIN_SLASH}])`, END_ANCHOR: `(?:[${WIN_SLASH}]|$)` }); /** * POSIX Bracket Regex */ const POSIX_REGEX_SOURCE = { alnum: 'a-zA-Z0-9', @@ -19178,15 +15568,10 @@ if (typeof options.expandRange === 'function') { return options.expandRange(...args, options); } args.sort(); let value = `[${args.join('-')}]`; - try { - } - catch (ex) { - return args.map(v => utils$2.escapeRegex(v)).join('..'); - } return value; }; const negate = state => { let count = 1; while (state.peek() === '!' && (state.peek(2) !== '(' || state.peek(3) === '?')) { @@ -19310,11 +15695,11 @@ tok.prev = prev; tokens.push(tok); prev = tok; }; const extglobOpen = (type, value) => { - let token = Object.assign({}, EXTGLOB_CHARS[value], { conditions: 1, inner: '' }); + let token = Object.assign(Object.assign({}, EXTGLOB_CHARS[value]), { conditions: 1, inner: '' }); token.prev = prev; token.parens = state.parens; token.output = state.output; let output = (opts.capture ? '(' : '') + token.open; push({ type, value, output: state.output ? '' : ONE_CHAR }); @@ -20002,11 +16387,11 @@ let regex = picomatch.makeRe(glob, options, false, true); let state = regex.state; delete regex.state; let isIgnored = () => false; if (opts.ignore) { - let ignoreOpts = Object.assign({}, options, { ignore: null, onMatch: null, onResult: null }); + let ignoreOpts = Object.assign(Object.assign({}, options), { ignore: null, onMatch: null, onResult: null }); isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); } const matcher = (input, returnObject = false) => { let { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); let result = { glob, state, regex, posix, input, output, match, isMatch }; @@ -20264,11 +16649,11 @@ if (options && options.onResult) { options.onResult(state); } }; for (let i = 0; i < patterns.length; i++) { - let isMatch = picomatch$1(String(patterns[i]), Object.assign({}, options, { onResult }), true); + let isMatch = picomatch$1(String(patterns[i]), Object.assign(Object.assign({}, options), { onResult }), true); let negated = isMatch.state.negated || isMatch.state.negatedExtglob; if (negated) negatives++; for (let item of list) { let matched = isMatch(item, true); @@ -20363,11 +16748,11 @@ let onResult = state => { if (options.onResult) options.onResult(state); items.push(state.output); }; - let matches = micromatch(list, patterns, Object.assign({}, options, { onResult })); + let matches = micromatch(list, patterns, Object.assign(Object.assign({}, options), { onResult })); for (let item of items) { if (!matches.includes(item)) { result.add(item); } } @@ -20405,11 +16790,11 @@ } if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { return true; } } - return micromatch.isMatch(str, pattern, Object.assign({}, options, { contains: true })); + return micromatch.isMatch(str, pattern, Object.assign(Object.assign({}, 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. @@ -20549,11 +16934,11 @@ * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`. * @api public */ micromatch.capture = (glob, input, options) => { let posix = utils$2.isWindows(options); - let regex = picomatch$1.makeRe(String(glob), Object.assign({}, options, { capture: true })); + let regex = picomatch$1.makeRe(String(glob), Object.assign(Object.assign({}, options), { capture: true })); let match = regex.exec(posix ? utils$2.toPosixSlashes(input) : input); if (match) { return match.slice(1).map(v => v === void 0 ? '' : v); } }; @@ -20637,11 +17022,11 @@ * Expand braces */ micromatch.braceExpand = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); - return micromatch.braces(pattern, Object.assign({}, options, { expand: true })); + return micromatch.braces(pattern, Object.assign(Object.assign({}, options), { expand: true })); }; /** * Expose micromatch */ var micromatch_1 = micromatch; @@ -20760,19 +17145,18 @@ if (err.code === 'ENOENT') { // can't watch files that don't exist (e.g. injected // by plugins somehow) return; } - else { - throw err; - } + throw err; } const handleWatchEvent = (event) => { if (event === 'rename' || event === 'unlink') { this.close(); group.delete(id); this.trigger(id); + return; } else { let stats; try { stats = statSync(id); @@ -20793,11 +17177,11 @@ this.fsWatcher = chokidarOptions ? chokidar$1.watch(id, chokidarOptions).on('all', handleWatchEvent) : watch$1(id, opts, handleWatchEvent); group.set(id, this); } - addTask(task, isTransformDependency = false) { + addTask(task, isTransformDependency) { if (isTransformDependency) this.transformDependencyTasks.add(task); else this.tasks.add(task); } @@ -20812,26 +17196,25 @@ group.delete(this.id); this.close(); } } trigger(id) { - this.tasks.forEach(task => { + for (const task of this.tasks) { task.invalidate(id, false); - }); - this.transformDependencyTasks.forEach(task => { + } + for (const task of this.transformDependencyTasks) { task.invalidate(id, true); - }); + } } } const DELAY = 200; class Watcher { constructor(configs) { this.buildTimeout = null; this.invalidatedIds = new Set(); this.rerun = false; - this.succeeded = false; this.emitter = new (class extends EventEmitter { constructor(close) { super(); this.close = close; // Allows more than 10 bundles to be watched without @@ -20844,13 +17227,13 @@ process.nextTick(() => this.run()); } close() { if (this.buildTimeout) clearTimeout(this.buildTimeout); - this.tasks.forEach(task => { + for (const task of this.tasks) { task.close(); - }); + } this.emitter.removeAllListeners(); } emit(event, value) { this.emitter.emit(event, value); } @@ -20864,11 +17247,13 @@ } if (this.buildTimeout) clearTimeout(this.buildTimeout); this.buildTimeout = setTimeout(() => { this.buildTimeout = null; - this.invalidatedIds.forEach(id => this.emit('change', id)); + for (const id of this.invalidatedIds) { + this.emit('change', id); + } this.invalidatedIds.clear(); this.emit('restart'); this.run(); }, DELAY); } @@ -20880,20 +17265,19 @@ let taskPromise = Promise.resolve(); for (const task of this.tasks) taskPromise = taskPromise.then(() => task.run()); return taskPromise .then(() => { - this.succeeded = true; this.running = false; this.emit('event', { code: 'END' }); }) .catch(error => { this.running = false; this.emit('event', { - code: this.succeeded ? 'ERROR' : 'FATAL', + code: 'ERROR', error }); }) .then(() => { if (this.rerun) { @@ -20903,13 +17287,13 @@ }); } } class Task { constructor(watcher, config) { + this.cache = { modules: [] }; this.watchFiles = []; this.invalidated = true; - this.cache = null; this.watcher = watcher; this.closed = false; this.watched = new Set(); const { inputOptions, outputOptions } = mergeOptions({ config @@ -20924,42 +17308,42 @@ const watchOptions = inputOptions.watch || {}; if ('useChokidar' in watchOptions) watchOptions.chokidar = watchOptions.useChokidar; let chokidarOptions = 'chokidar' in watchOptions ? watchOptions.chokidar : !!chokidar$1; if (chokidarOptions) { - chokidarOptions = Object.assign({}, (chokidarOptions === true ? {} : chokidarOptions), { disableGlobbing: true, ignoreInitial: true }); + chokidarOptions = Object.assign(Object.assign({}, (chokidarOptions === true ? {} : chokidarOptions)), { disableGlobbing: true, ignoreInitial: true }); } if (chokidarOptions && !chokidar$1) { throw new Error(`watch.chokidar was provided, but chokidar could not be found. Have you installed it?`); } this.chokidarOptions = chokidarOptions; this.chokidarOptionsHash = JSON.stringify(chokidarOptions); this.filter = createFilter(watchOptions.include, watchOptions.exclude); } close() { this.closed = true; - this.watched.forEach(id => { + for (const id of this.watched) { deleteTask(id, this, this.chokidarOptionsHash); - }); + } } invalidate(id, isTransformDependency) { this.invalidated = true; if (isTransformDependency) { - this.cache.modules.forEach(module => { - if (!module.transformDependencies || module.transformDependencies.indexOf(id) === -1) - return; + for (const module of this.cache.modules) { + if (module.transformDependencies.indexOf(id) === -1) + continue; // effective invalidation module.originalCode = null; - }); + } } this.watcher.invalidate(id); } run() { if (!this.invalidated) return; this.invalidated = false; - const options = Object.assign({}, this.inputOptions, { cache: this.cache }); + const options = Object.assign(Object.assign({}, this.inputOptions), { cache: this.cache }); const start = Date.now(); this.watcher.emit('event', { code: 'BUNDLE_START', input: this.inputOptions.input, output: this.outputFiles @@ -20967,30 +17351,11 @@ setWatcher(this.watcher.emitter); return rollup(options) .then(result => { if (this.closed) return undefined; - const previouslyWatched = this.watched; - const watched = (this.watched = new Set()); - this.cache = result.cache; - this.watchFiles = result.watchFiles; - for (const module of this.cache.modules) { - if (module.transformDependencies) { - module.transformDependencies.forEach(depId => { - watched.add(depId); - this.watchFile(depId, true); - }); - } - } - for (const id of this.watchFiles) { - watched.add(id); - this.watchFile(id); - } - for (const id of previouslyWatched) { - if (!watched.has(id)) - deleteTask(id, this, this.chokidarOptionsHash); - } + this.updateWatchedFiles(result); return Promise.all(this.outputs.map(output => result.write(output))).then(() => result); }) .then((result) => { this.watcher.emit('event', { code: 'BUNDLE_END', @@ -21001,31 +17366,39 @@ }); }) .catch((error) => { if (this.closed) return; - if (this.cache) { - // this is necessary to ensure that any 'renamed' files - // continue to be watched following an error - if (this.cache.modules) { - this.cache.modules.forEach(module => { - if (module.transformDependencies) { - module.transformDependencies.forEach(depId => { - this.watchFile(depId, true); - }); - } - }); - } - this.watchFiles.forEach(id => { + if (Array.isArray(error.watchFiles)) { + for (const id of error.watchFiles) { this.watchFile(id); - }); + } } throw error; }); } + updateWatchedFiles(result) { + const previouslyWatched = this.watched; + this.watched = new Set(); + this.watchFiles = result.watchFiles; + this.cache = result.cache; + for (const id of this.watchFiles) { + this.watchFile(id); + } + for (const module of this.cache.modules) { + for (const depId of module.transformDependencies) { + this.watchFile(depId, true); + } + } + for (const id of previouslyWatched) { + if (!this.watched.has(id)) + deleteTask(id, this, this.chokidarOptionsHash); + } + } watchFile(id, isTransformDependency = false) { if (!this.filter(id)) return; + this.watched.add(id); if (this.outputFiles.some(file => file === id)) { throw new Error('Cannot import the generated bundle'); } // this is necessary to ensure that any 'renamed' files // continue to be watched following an error