UNPKG

762 kBJavaScriptView Raw
1/*
2 @license
3 Rollup.js v1.19.0
4 Mon, 05 Aug 2019 17:57:00 GMT - commit 9af119d7bb9d012ec01dcd4663ea5ee99af1e75d
5
6
7 https://github.com/rollup/rollup
8
9 Released under the MIT License.
10*/
11'use strict';
12
13Object.defineProperty(exports, '__esModule', { value: true });
14
15var index = require('./shared/index.js');
16var util = require('util');
17var path = require('path');
18var fs = require('fs');
19var acorn = require('acorn');
20var events = require('events');
21require('module');
22
23/*! *****************************************************************************
24Copyright (c) Microsoft Corporation. All rights reserved.
25Licensed under the Apache License, Version 2.0 (the "License"); you may not use
26this file except in compliance with the License. You may obtain a copy of the
27License at http://www.apache.org/licenses/LICENSE-2.0
28
29THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
30KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
31WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
32MERCHANTABLITY OR NON-INFRINGEMENT.
33
34See the Apache Version 2.0 License for specific language governing permissions
35and limitations under the License.
36***************************************************************************** */
37function __awaiter(thisArg, _arguments, P, generator) {
38 return new (P || (P = Promise))(function (resolve, reject) {
39 function fulfilled(value) { try {
40 step(generator.next(value));
41 }
42 catch (e) {
43 reject(e);
44 } }
45 function rejected(value) { try {
46 step(generator["throw"](value));
47 }
48 catch (e) {
49 reject(e);
50 } }
51 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
52 step((generator = generator.apply(thisArg, _arguments || [])).next());
53 });
54}
55
56var minimalisticAssert = assert;
57function assert(val, msg) {
58 if (!val)
59 throw new Error(msg || 'Assertion failed');
60}
61assert.equal = function assertEqual(l, r, msg) {
62 if (l != r)
63 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
64};
65
66var inherits_browser = index.createCommonjsModule(function (module) {
67 if (typeof Object.create === 'function') {
68 // implementation from standard node.js 'util' module
69 module.exports = function inherits(ctor, superCtor) {
70 ctor.super_ = superCtor;
71 ctor.prototype = Object.create(superCtor.prototype, {
72 constructor: {
73 value: ctor,
74 enumerable: false,
75 writable: true,
76 configurable: true
77 }
78 });
79 };
80 }
81 else {
82 // old school shim for old browsers
83 module.exports = function inherits(ctor, superCtor) {
84 ctor.super_ = superCtor;
85 var TempCtor = function () { };
86 TempCtor.prototype = superCtor.prototype;
87 ctor.prototype = new TempCtor();
88 ctor.prototype.constructor = ctor;
89 };
90 }
91});
92
93var inherits = index.createCommonjsModule(function (module) {
94 try {
95 var util$1 = util;
96 if (typeof util$1.inherits !== 'function')
97 throw '';
98 module.exports = util$1.inherits;
99 }
100 catch (e) {
101 module.exports = inherits_browser;
102 }
103});
104
105var inherits_1 = inherits;
106function isSurrogatePair(msg, i) {
107 if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
108 return false;
109 }
110 if (i < 0 || i + 1 >= msg.length) {
111 return false;
112 }
113 return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
114}
115function toArray(msg, enc) {
116 if (Array.isArray(msg))
117 return msg.slice();
118 if (!msg)
119 return [];
120 var res = [];
121 if (typeof msg === 'string') {
122 if (!enc) {
123 // Inspired by stringToUtf8ByteArray() in closure-library by Google
124 // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
125 // Apache License 2.0
126 // https://github.com/google/closure-library/blob/master/LICENSE
127 var p = 0;
128 for (var i = 0; i < msg.length; i++) {
129 var c = msg.charCodeAt(i);
130 if (c < 128) {
131 res[p++] = c;
132 }
133 else if (c < 2048) {
134 res[p++] = (c >> 6) | 192;
135 res[p++] = (c & 63) | 128;
136 }
137 else if (isSurrogatePair(msg, i)) {
138 c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
139 res[p++] = (c >> 18) | 240;
140 res[p++] = ((c >> 12) & 63) | 128;
141 res[p++] = ((c >> 6) & 63) | 128;
142 res[p++] = (c & 63) | 128;
143 }
144 else {
145 res[p++] = (c >> 12) | 224;
146 res[p++] = ((c >> 6) & 63) | 128;
147 res[p++] = (c & 63) | 128;
148 }
149 }
150 }
151 else if (enc === 'hex') {
152 msg = msg.replace(/[^a-z0-9]+/ig, '');
153 if (msg.length % 2 !== 0)
154 msg = '0' + msg;
155 for (i = 0; i < msg.length; i += 2)
156 res.push(parseInt(msg[i] + msg[i + 1], 16));
157 }
158 }
159 else {
160 for (i = 0; i < msg.length; i++)
161 res[i] = msg[i] | 0;
162 }
163 return res;
164}
165var toArray_1 = toArray;
166function toHex(msg) {
167 var res = '';
168 for (var i = 0; i < msg.length; i++)
169 res += zero2(msg[i].toString(16));
170 return res;
171}
172var toHex_1 = toHex;
173function htonl(w) {
174 var res = (w >>> 24) |
175 ((w >>> 8) & 0xff00) |
176 ((w << 8) & 0xff0000) |
177 ((w & 0xff) << 24);
178 return res >>> 0;
179}
180var htonl_1 = htonl;
181function toHex32(msg, endian) {
182 var res = '';
183 for (var i = 0; i < msg.length; i++) {
184 var w = msg[i];
185 if (endian === 'little')
186 w = htonl(w);
187 res += zero8(w.toString(16));
188 }
189 return res;
190}
191var toHex32_1 = toHex32;
192function zero2(word) {
193 if (word.length === 1)
194 return '0' + word;
195 else
196 return word;
197}
198var zero2_1 = zero2;
199function zero8(word) {
200 if (word.length === 7)
201 return '0' + word;
202 else if (word.length === 6)
203 return '00' + word;
204 else if (word.length === 5)
205 return '000' + word;
206 else if (word.length === 4)
207 return '0000' + word;
208 else if (word.length === 3)
209 return '00000' + word;
210 else if (word.length === 2)
211 return '000000' + word;
212 else if (word.length === 1)
213 return '0000000' + word;
214 else
215 return word;
216}
217var zero8_1 = zero8;
218function join32(msg, start, end, endian) {
219 var len = end - start;
220 minimalisticAssert(len % 4 === 0);
221 var res = new Array(len / 4);
222 for (var i = 0, k = start; i < res.length; i++, k += 4) {
223 var w;
224 if (endian === 'big')
225 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
226 else
227 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
228 res[i] = w >>> 0;
229 }
230 return res;
231}
232var join32_1 = join32;
233function split32(msg, endian) {
234 var res = new Array(msg.length * 4);
235 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
236 var m = msg[i];
237 if (endian === 'big') {
238 res[k] = m >>> 24;
239 res[k + 1] = (m >>> 16) & 0xff;
240 res[k + 2] = (m >>> 8) & 0xff;
241 res[k + 3] = m & 0xff;
242 }
243 else {
244 res[k + 3] = m >>> 24;
245 res[k + 2] = (m >>> 16) & 0xff;
246 res[k + 1] = (m >>> 8) & 0xff;
247 res[k] = m & 0xff;
248 }
249 }
250 return res;
251}
252var split32_1 = split32;
253function rotr32(w, b) {
254 return (w >>> b) | (w << (32 - b));
255}
256var rotr32_1 = rotr32;
257function rotl32(w, b) {
258 return (w << b) | (w >>> (32 - b));
259}
260var rotl32_1 = rotl32;
261function sum32(a, b) {
262 return (a + b) >>> 0;
263}
264var sum32_1 = sum32;
265function sum32_3(a, b, c) {
266 return (a + b + c) >>> 0;
267}
268var sum32_3_1 = sum32_3;
269function sum32_4(a, b, c, d) {
270 return (a + b + c + d) >>> 0;
271}
272var sum32_4_1 = sum32_4;
273function sum32_5(a, b, c, d, e) {
274 return (a + b + c + d + e) >>> 0;
275}
276var sum32_5_1 = sum32_5;
277function sum64(buf, pos, ah, al) {
278 var bh = buf[pos];
279 var bl = buf[pos + 1];
280 var lo = (al + bl) >>> 0;
281 var hi = (lo < al ? 1 : 0) + ah + bh;
282 buf[pos] = hi >>> 0;
283 buf[pos + 1] = lo;
284}
285var sum64_1 = sum64;
286function sum64_hi(ah, al, bh, bl) {
287 var lo = (al + bl) >>> 0;
288 var hi = (lo < al ? 1 : 0) + ah + bh;
289 return hi >>> 0;
290}
291var sum64_hi_1 = sum64_hi;
292function sum64_lo(ah, al, bh, bl) {
293 var lo = al + bl;
294 return lo >>> 0;
295}
296var sum64_lo_1 = sum64_lo;
297function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
298 var carry = 0;
299 var lo = al;
300 lo = (lo + bl) >>> 0;
301 carry += lo < al ? 1 : 0;
302 lo = (lo + cl) >>> 0;
303 carry += lo < cl ? 1 : 0;
304 lo = (lo + dl) >>> 0;
305 carry += lo < dl ? 1 : 0;
306 var hi = ah + bh + ch + dh + carry;
307 return hi >>> 0;
308}
309var sum64_4_hi_1 = sum64_4_hi;
310function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
311 var lo = al + bl + cl + dl;
312 return lo >>> 0;
313}
314var sum64_4_lo_1 = sum64_4_lo;
315function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
316 var carry = 0;
317 var lo = al;
318 lo = (lo + bl) >>> 0;
319 carry += lo < al ? 1 : 0;
320 lo = (lo + cl) >>> 0;
321 carry += lo < cl ? 1 : 0;
322 lo = (lo + dl) >>> 0;
323 carry += lo < dl ? 1 : 0;
324 lo = (lo + el) >>> 0;
325 carry += lo < el ? 1 : 0;
326 var hi = ah + bh + ch + dh + eh + carry;
327 return hi >>> 0;
328}
329var sum64_5_hi_1 = sum64_5_hi;
330function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
331 var lo = al + bl + cl + dl + el;
332 return lo >>> 0;
333}
334var sum64_5_lo_1 = sum64_5_lo;
335function rotr64_hi(ah, al, num) {
336 var r = (al << (32 - num)) | (ah >>> num);
337 return r >>> 0;
338}
339var rotr64_hi_1 = rotr64_hi;
340function rotr64_lo(ah, al, num) {
341 var r = (ah << (32 - num)) | (al >>> num);
342 return r >>> 0;
343}
344var rotr64_lo_1 = rotr64_lo;
345function shr64_hi(ah, al, num) {
346 return ah >>> num;
347}
348var shr64_hi_1 = shr64_hi;
349function shr64_lo(ah, al, num) {
350 var r = (ah << (32 - num)) | (al >>> num);
351 return r >>> 0;
352}
353var shr64_lo_1 = shr64_lo;
354var utils = {
355 inherits: inherits_1,
356 toArray: toArray_1,
357 toHex: toHex_1,
358 htonl: htonl_1,
359 toHex32: toHex32_1,
360 zero2: zero2_1,
361 zero8: zero8_1,
362 join32: join32_1,
363 split32: split32_1,
364 rotr32: rotr32_1,
365 rotl32: rotl32_1,
366 sum32: sum32_1,
367 sum32_3: sum32_3_1,
368 sum32_4: sum32_4_1,
369 sum32_5: sum32_5_1,
370 sum64: sum64_1,
371 sum64_hi: sum64_hi_1,
372 sum64_lo: sum64_lo_1,
373 sum64_4_hi: sum64_4_hi_1,
374 sum64_4_lo: sum64_4_lo_1,
375 sum64_5_hi: sum64_5_hi_1,
376 sum64_5_lo: sum64_5_lo_1,
377 rotr64_hi: rotr64_hi_1,
378 rotr64_lo: rotr64_lo_1,
379 shr64_hi: shr64_hi_1,
380 shr64_lo: shr64_lo_1
381};
382
383function BlockHash() {
384 this.pending = null;
385 this.pendingTotal = 0;
386 this.blockSize = this.constructor.blockSize;
387 this.outSize = this.constructor.outSize;
388 this.hmacStrength = this.constructor.hmacStrength;
389 this.padLength = this.constructor.padLength / 8;
390 this.endian = 'big';
391 this._delta8 = this.blockSize / 8;
392 this._delta32 = this.blockSize / 32;
393}
394var BlockHash_1 = BlockHash;
395BlockHash.prototype.update = function update(msg, enc) {
396 // Convert message to array, pad it, and join into 32bit blocks
397 msg = utils.toArray(msg, enc);
398 if (!this.pending)
399 this.pending = msg;
400 else
401 this.pending = this.pending.concat(msg);
402 this.pendingTotal += msg.length;
403 // Enough data, try updating
404 if (this.pending.length >= this._delta8) {
405 msg = this.pending;
406 // Process pending data in blocks
407 var r = msg.length % this._delta8;
408 this.pending = msg.slice(msg.length - r, msg.length);
409 if (this.pending.length === 0)
410 this.pending = null;
411 msg = utils.join32(msg, 0, msg.length - r, this.endian);
412 for (var i = 0; i < msg.length; i += this._delta32)
413 this._update(msg, i, i + this._delta32);
414 }
415 return this;
416};
417BlockHash.prototype.digest = function digest(enc) {
418 this.update(this._pad());
419 minimalisticAssert(this.pending === null);
420 return this._digest(enc);
421};
422BlockHash.prototype._pad = function pad() {
423 var len = this.pendingTotal;
424 var bytes = this._delta8;
425 var k = bytes - ((len + this.padLength) % bytes);
426 var res = new Array(k + this.padLength);
427 res[0] = 0x80;
428 for (var i = 1; i < k; i++)
429 res[i] = 0;
430 // Append length
431 len <<= 3;
432 if (this.endian === 'big') {
433 for (var t = 8; t < this.padLength; t++)
434 res[i++] = 0;
435 res[i++] = 0;
436 res[i++] = 0;
437 res[i++] = 0;
438 res[i++] = 0;
439 res[i++] = (len >>> 24) & 0xff;
440 res[i++] = (len >>> 16) & 0xff;
441 res[i++] = (len >>> 8) & 0xff;
442 res[i++] = len & 0xff;
443 }
444 else {
445 res[i++] = len & 0xff;
446 res[i++] = (len >>> 8) & 0xff;
447 res[i++] = (len >>> 16) & 0xff;
448 res[i++] = (len >>> 24) & 0xff;
449 res[i++] = 0;
450 res[i++] = 0;
451 res[i++] = 0;
452 res[i++] = 0;
453 for (t = 8; t < this.padLength; t++)
454 res[i++] = 0;
455 }
456 return res;
457};
458var common = {
459 BlockHash: BlockHash_1
460};
461
462var rotr32$1 = utils.rotr32;
463function ft_1(s, x, y, z) {
464 if (s === 0)
465 return ch32(x, y, z);
466 if (s === 1 || s === 3)
467 return p32(x, y, z);
468 if (s === 2)
469 return maj32(x, y, z);
470}
471var ft_1_1 = ft_1;
472function ch32(x, y, z) {
473 return (x & y) ^ ((~x) & z);
474}
475var ch32_1 = ch32;
476function maj32(x, y, z) {
477 return (x & y) ^ (x & z) ^ (y & z);
478}
479var maj32_1 = maj32;
480function p32(x, y, z) {
481 return x ^ y ^ z;
482}
483var p32_1 = p32;
484function s0_256(x) {
485 return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22);
486}
487var s0_256_1 = s0_256;
488function s1_256(x) {
489 return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25);
490}
491var s1_256_1 = s1_256;
492function g0_256(x) {
493 return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3);
494}
495var g0_256_1 = g0_256;
496function g1_256(x) {
497 return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10);
498}
499var g1_256_1 = g1_256;
500var common$1 = {
501 ft_1: ft_1_1,
502 ch32: ch32_1,
503 maj32: maj32_1,
504 p32: p32_1,
505 s0_256: s0_256_1,
506 s1_256: s1_256_1,
507 g0_256: g0_256_1,
508 g1_256: g1_256_1
509};
510
511var sum32$1 = utils.sum32;
512var sum32_4$1 = utils.sum32_4;
513var sum32_5$1 = utils.sum32_5;
514var ch32$1 = common$1.ch32;
515var maj32$1 = common$1.maj32;
516var s0_256$1 = common$1.s0_256;
517var s1_256$1 = common$1.s1_256;
518var g0_256$1 = common$1.g0_256;
519var g1_256$1 = common$1.g1_256;
520var BlockHash$1 = common.BlockHash;
521var sha256_K = [
522 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
523 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
524 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
525 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
526 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
527 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
528 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
529 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
530 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
531 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
532 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
533 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
534 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
535 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
536 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
537 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
538];
539function SHA256() {
540 if (!(this instanceof SHA256))
541 return new SHA256();
542 BlockHash$1.call(this);
543 this.h = [
544 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
545 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
546 ];
547 this.k = sha256_K;
548 this.W = new Array(64);
549}
550utils.inherits(SHA256, BlockHash$1);
551var _256 = SHA256;
552SHA256.blockSize = 512;
553SHA256.outSize = 256;
554SHA256.hmacStrength = 192;
555SHA256.padLength = 64;
556SHA256.prototype._update = function _update(msg, start) {
557 var W = this.W;
558 for (var i = 0; i < 16; i++)
559 W[i] = msg[start + i];
560 for (; i < W.length; i++)
561 W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]);
562 var a = this.h[0];
563 var b = this.h[1];
564 var c = this.h[2];
565 var d = this.h[3];
566 var e = this.h[4];
567 var f = this.h[5];
568 var g = this.h[6];
569 var h = this.h[7];
570 minimalisticAssert(this.k.length === W.length);
571 for (i = 0; i < W.length; i++) {
572 var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]);
573 var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c));
574 h = g;
575 g = f;
576 f = e;
577 e = sum32$1(d, T1);
578 d = c;
579 c = b;
580 b = a;
581 a = sum32$1(T1, T2);
582 }
583 this.h[0] = sum32$1(this.h[0], a);
584 this.h[1] = sum32$1(this.h[1], b);
585 this.h[2] = sum32$1(this.h[2], c);
586 this.h[3] = sum32$1(this.h[3], d);
587 this.h[4] = sum32$1(this.h[4], e);
588 this.h[5] = sum32$1(this.h[5], f);
589 this.h[6] = sum32$1(this.h[6], g);
590 this.h[7] = sum32$1(this.h[7], h);
591};
592SHA256.prototype._digest = function digest(enc) {
593 if (enc === 'hex')
594 return utils.toHex32(this.h, 'big');
595 else
596 return utils.split32(this.h, 'big');
597};
598
599var charToInteger = {};
600var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
601for (var i = 0; i < chars.length; i++) {
602 charToInteger[chars.charCodeAt(i)] = i;
603}
604function decode(mappings) {
605 var generatedCodeColumn = 0; // first field
606 var sourceFileIndex = 0; // second field
607 var sourceCodeLine = 0; // third field
608 var sourceCodeColumn = 0; // fourth field
609 var nameIndex = 0; // fifth field
610 var decoded = [];
611 var line = [];
612 var segment = [];
613 for (var i = 0, j = 0, shift = 0, value = 0, len = mappings.length; i < len; i++) {
614 var c = mappings.charCodeAt(i);
615 if (c === 44) { // ","
616 if (segment.length)
617 line.push(segment);
618 segment = [];
619 j = 0;
620 }
621 else if (c === 59) { // ";"
622 if (segment.length)
623 line.push(segment);
624 segment = [];
625 j = 0;
626 decoded.push(line);
627 line = [];
628 generatedCodeColumn = 0;
629 }
630 else {
631 var integer = charToInteger[c];
632 if (integer === undefined) {
633 throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
634 }
635 var hasContinuationBit = integer & 32;
636 integer &= 31;
637 value += integer << shift;
638 if (hasContinuationBit) {
639 shift += 5;
640 }
641 else {
642 var shouldNegate = value & 1;
643 value >>>= 1;
644 if (shouldNegate) {
645 value = -value;
646 if (value === 0)
647 value = -0x80000000;
648 }
649 if (j == 0) {
650 generatedCodeColumn += value;
651 segment.push(generatedCodeColumn);
652 }
653 else if (j === 1) {
654 sourceFileIndex += value;
655 segment.push(sourceFileIndex);
656 }
657 else if (j === 2) {
658 sourceCodeLine += value;
659 segment.push(sourceCodeLine);
660 }
661 else if (j === 3) {
662 sourceCodeColumn += value;
663 segment.push(sourceCodeColumn);
664 }
665 else if (j === 4) {
666 nameIndex += value;
667 segment.push(nameIndex);
668 }
669 j++;
670 value = shift = 0; // reset
671 }
672 }
673 }
674 if (segment.length)
675 line.push(segment);
676 decoded.push(line);
677 return decoded;
678}
679function encode(decoded) {
680 var sourceFileIndex = 0; // second field
681 var sourceCodeLine = 0; // third field
682 var sourceCodeColumn = 0; // fourth field
683 var nameIndex = 0; // fifth field
684 var mappings = '';
685 for (var i = 0; i < decoded.length; i++) {
686 var line = decoded[i];
687 if (i > 0)
688 mappings += ';';
689 if (line.length === 0)
690 continue;
691 var generatedCodeColumn = 0; // first field
692 var lineMappings = [];
693 for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
694 var segment = line_1[_i];
695 var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
696 generatedCodeColumn = segment[0];
697 if (segment.length > 1) {
698 segmentMappings +=
699 encodeInteger(segment[1] - sourceFileIndex) +
700 encodeInteger(segment[2] - sourceCodeLine) +
701 encodeInteger(segment[3] - sourceCodeColumn);
702 sourceFileIndex = segment[1];
703 sourceCodeLine = segment[2];
704 sourceCodeColumn = segment[3];
705 }
706 if (segment.length === 5) {
707 segmentMappings += encodeInteger(segment[4] - nameIndex);
708 nameIndex = segment[4];
709 }
710 lineMappings.push(segmentMappings);
711 }
712 mappings += lineMappings.join(',');
713 }
714 return mappings;
715}
716function encodeInteger(num) {
717 var result = '';
718 num = num < 0 ? (-num << 1) | 1 : num << 1;
719 do {
720 var clamped = num & 31;
721 num >>>= 5;
722 if (num > 0) {
723 clamped |= 32;
724 }
725 result += chars[clamped];
726 } while (num > 0);
727 return result;
728}
729
730var Chunk = function Chunk(start, end, content) {
731 this.start = start;
732 this.end = end;
733 this.original = content;
734 this.intro = '';
735 this.outro = '';
736 this.content = content;
737 this.storeName = false;
738 this.edited = false;
739 // we make these non-enumerable, for sanity while debugging
740 Object.defineProperties(this, {
741 previous: { writable: true, value: null },
742 next: { writable: true, value: null }
743 });
744};
745Chunk.prototype.appendLeft = function appendLeft(content) {
746 this.outro += content;
747};
748Chunk.prototype.appendRight = function appendRight(content) {
749 this.intro = this.intro + content;
750};
751Chunk.prototype.clone = function clone() {
752 var chunk = new Chunk(this.start, this.end, this.original);
753 chunk.intro = this.intro;
754 chunk.outro = this.outro;
755 chunk.content = this.content;
756 chunk.storeName = this.storeName;
757 chunk.edited = this.edited;
758 return chunk;
759};
760Chunk.prototype.contains = function contains(index) {
761 return this.start < index && index < this.end;
762};
763Chunk.prototype.eachNext = function eachNext(fn) {
764 var chunk = this;
765 while (chunk) {
766 fn(chunk);
767 chunk = chunk.next;
768 }
769};
770Chunk.prototype.eachPrevious = function eachPrevious(fn) {
771 var chunk = this;
772 while (chunk) {
773 fn(chunk);
774 chunk = chunk.previous;
775 }
776};
777Chunk.prototype.edit = function edit(content, storeName, contentOnly) {
778 this.content = content;
779 if (!contentOnly) {
780 this.intro = '';
781 this.outro = '';
782 }
783 this.storeName = storeName;
784 this.edited = true;
785 return this;
786};
787Chunk.prototype.prependLeft = function prependLeft(content) {
788 this.outro = content + this.outro;
789};
790Chunk.prototype.prependRight = function prependRight(content) {
791 this.intro = content + this.intro;
792};
793Chunk.prototype.split = function split(index) {
794 var sliceIndex = index - this.start;
795 var originalBefore = this.original.slice(0, sliceIndex);
796 var originalAfter = this.original.slice(sliceIndex);
797 this.original = originalBefore;
798 var newChunk = new Chunk(index, this.end, originalAfter);
799 newChunk.outro = this.outro;
800 this.outro = '';
801 this.end = index;
802 if (this.edited) {
803 // TODO is this block necessary?...
804 newChunk.edit('', false);
805 this.content = '';
806 }
807 else {
808 this.content = originalBefore;
809 }
810 newChunk.next = this.next;
811 if (newChunk.next) {
812 newChunk.next.previous = newChunk;
813 }
814 newChunk.previous = this;
815 this.next = newChunk;
816 return newChunk;
817};
818Chunk.prototype.toString = function toString() {
819 return this.intro + this.content + this.outro;
820};
821Chunk.prototype.trimEnd = function trimEnd(rx) {
822 this.outro = this.outro.replace(rx, '');
823 if (this.outro.length) {
824 return true;
825 }
826 var trimmed = this.content.replace(rx, '');
827 if (trimmed.length) {
828 if (trimmed !== this.content) {
829 this.split(this.start + trimmed.length).edit('', undefined, true);
830 }
831 return true;
832 }
833 else {
834 this.edit('', undefined, true);
835 this.intro = this.intro.replace(rx, '');
836 if (this.intro.length) {
837 return true;
838 }
839 }
840};
841Chunk.prototype.trimStart = function trimStart(rx) {
842 this.intro = this.intro.replace(rx, '');
843 if (this.intro.length) {
844 return true;
845 }
846 var trimmed = this.content.replace(rx, '');
847 if (trimmed.length) {
848 if (trimmed !== this.content) {
849 this.split(this.end - trimmed.length);
850 this.edit('', undefined, true);
851 }
852 return true;
853 }
854 else {
855 this.edit('', undefined, true);
856 this.outro = this.outro.replace(rx, '');
857 if (this.outro.length) {
858 return true;
859 }
860 }
861};
862var btoa = function () {
863 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
864};
865if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
866 btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
867}
868else if (typeof Buffer === 'function') {
869 btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
870}
871var SourceMap = function SourceMap(properties) {
872 this.version = 3;
873 this.file = properties.file;
874 this.sources = properties.sources;
875 this.sourcesContent = properties.sourcesContent;
876 this.names = properties.names;
877 this.mappings = encode(properties.mappings);
878};
879SourceMap.prototype.toString = function toString() {
880 return JSON.stringify(this);
881};
882SourceMap.prototype.toUrl = function toUrl() {
883 return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
884};
885function guessIndent(code) {
886 var lines = code.split('\n');
887 var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
888 var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
889 if (tabbed.length === 0 && spaced.length === 0) {
890 return null;
891 }
892 // More lines tabbed than spaced? Assume tabs, and
893 // default to tabs in the case of a tie (or nothing
894 // to go on)
895 if (tabbed.length >= spaced.length) {
896 return '\t';
897 }
898 // Otherwise, we need to guess the multiple
899 var min = spaced.reduce(function (previous, current) {
900 var numSpaces = /^ +/.exec(current)[0].length;
901 return Math.min(numSpaces, previous);
902 }, Infinity);
903 return new Array(min + 1).join(' ');
904}
905function getRelativePath(from, to) {
906 var fromParts = from.split(/[/\\]/);
907 var toParts = to.split(/[/\\]/);
908 fromParts.pop(); // get dirname
909 while (fromParts[0] === toParts[0]) {
910 fromParts.shift();
911 toParts.shift();
912 }
913 if (fromParts.length) {
914 var i = fromParts.length;
915 while (i--) {
916 fromParts[i] = '..';
917 }
918 }
919 return fromParts.concat(toParts).join('/');
920}
921var toString = Object.prototype.toString;
922function isObject(thing) {
923 return toString.call(thing) === '[object Object]';
924}
925function getLocator(source) {
926 var originalLines = source.split('\n');
927 var lineOffsets = [];
928 for (var i = 0, pos = 0; i < originalLines.length; i++) {
929 lineOffsets.push(pos);
930 pos += originalLines[i].length + 1;
931 }
932 return function locate(index) {
933 var i = 0;
934 var j = lineOffsets.length;
935 while (i < j) {
936 var m = (i + j) >> 1;
937 if (index < lineOffsets[m]) {
938 j = m;
939 }
940 else {
941 i = m + 1;
942 }
943 }
944 var line = i - 1;
945 var column = index - lineOffsets[line];
946 return { line: line, column: column };
947 };
948}
949var Mappings = function Mappings(hires) {
950 this.hires = hires;
951 this.generatedCodeLine = 0;
952 this.generatedCodeColumn = 0;
953 this.raw = [];
954 this.rawSegments = this.raw[this.generatedCodeLine] = [];
955 this.pending = null;
956};
957Mappings.prototype.addEdit = function addEdit(sourceIndex, content, loc, nameIndex) {
958 if (content.length) {
959 var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
960 if (nameIndex >= 0) {
961 segment.push(nameIndex);
962 }
963 this.rawSegments.push(segment);
964 }
965 else if (this.pending) {
966 this.rawSegments.push(this.pending);
967 }
968 this.advance(content);
969 this.pending = null;
970};
971Mappings.prototype.addUneditedChunk = function addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
972 var originalCharIndex = chunk.start;
973 var first = true;
974 while (originalCharIndex < chunk.end) {
975 if (this.hires || first || sourcemapLocations[originalCharIndex]) {
976 this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
977 }
978 if (original[originalCharIndex] === '\n') {
979 loc.line += 1;
980 loc.column = 0;
981 this.generatedCodeLine += 1;
982 this.raw[this.generatedCodeLine] = this.rawSegments = [];
983 this.generatedCodeColumn = 0;
984 }
985 else {
986 loc.column += 1;
987 this.generatedCodeColumn += 1;
988 }
989 originalCharIndex += 1;
990 first = false;
991 }
992 this.pending = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
993};
994Mappings.prototype.advance = function advance(str) {
995 if (!str) {
996 return;
997 }
998 var lines = str.split('\n');
999 if (lines.length > 1) {
1000 for (var i = 0; i < lines.length - 1; i++) {
1001 this.generatedCodeLine++;
1002 this.raw[this.generatedCodeLine] = this.rawSegments = [];
1003 }
1004 this.generatedCodeColumn = 0;
1005 }
1006 this.generatedCodeColumn += lines[lines.length - 1].length;
1007};
1008var n = '\n';
1009var warned = {
1010 insertLeft: false,
1011 insertRight: false,
1012 storeName: false
1013};
1014var MagicString = function MagicString(string, options) {
1015 if (options === void 0)
1016 options = {};
1017 var chunk = new Chunk(0, string.length, string);
1018 Object.defineProperties(this, {
1019 original: { writable: true, value: string },
1020 outro: { writable: true, value: '' },
1021 intro: { writable: true, value: '' },
1022 firstChunk: { writable: true, value: chunk },
1023 lastChunk: { writable: true, value: chunk },
1024 lastSearchedChunk: { writable: true, value: chunk },
1025 byStart: { writable: true, value: {} },
1026 byEnd: { writable: true, value: {} },
1027 filename: { writable: true, value: options.filename },
1028 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
1029 sourcemapLocations: { writable: true, value: {} },
1030 storedNames: { writable: true, value: {} },
1031 indentStr: { writable: true, value: guessIndent(string) }
1032 });
1033 this.byStart[0] = chunk;
1034 this.byEnd[string.length] = chunk;
1035};
1036MagicString.prototype.addSourcemapLocation = function addSourcemapLocation(char) {
1037 this.sourcemapLocations[char] = true;
1038};
1039MagicString.prototype.append = function append(content) {
1040 if (typeof content !== 'string') {
1041 throw new TypeError('outro content must be a string');
1042 }
1043 this.outro += content;
1044 return this;
1045};
1046MagicString.prototype.appendLeft = function appendLeft(index, content) {
1047 if (typeof content !== 'string') {
1048 throw new TypeError('inserted content must be a string');
1049 }
1050 this._split(index);
1051 var chunk = this.byEnd[index];
1052 if (chunk) {
1053 chunk.appendLeft(content);
1054 }
1055 else {
1056 this.intro += content;
1057 }
1058 return this;
1059};
1060MagicString.prototype.appendRight = function appendRight(index, content) {
1061 if (typeof content !== 'string') {
1062 throw new TypeError('inserted content must be a string');
1063 }
1064 this._split(index);
1065 var chunk = this.byStart[index];
1066 if (chunk) {
1067 chunk.appendRight(content);
1068 }
1069 else {
1070 this.outro += content;
1071 }
1072 return this;
1073};
1074MagicString.prototype.clone = function clone() {
1075 var cloned = new MagicString(this.original, { filename: this.filename });
1076 var originalChunk = this.firstChunk;
1077 var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
1078 while (originalChunk) {
1079 cloned.byStart[clonedChunk.start] = clonedChunk;
1080 cloned.byEnd[clonedChunk.end] = clonedChunk;
1081 var nextOriginalChunk = originalChunk.next;
1082 var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
1083 if (nextClonedChunk) {
1084 clonedChunk.next = nextClonedChunk;
1085 nextClonedChunk.previous = clonedChunk;
1086 clonedChunk = nextClonedChunk;
1087 }
1088 originalChunk = nextOriginalChunk;
1089 }
1090 cloned.lastChunk = clonedChunk;
1091 if (this.indentExclusionRanges) {
1092 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
1093 }
1094 Object.keys(this.sourcemapLocations).forEach(function (loc) {
1095 cloned.sourcemapLocations[loc] = true;
1096 });
1097 return cloned;
1098};
1099MagicString.prototype.generateDecodedMap = function generateDecodedMap(options) {
1100 var this$1 = this;
1101 options = options || {};
1102 var sourceIndex = 0;
1103 var names = Object.keys(this.storedNames);
1104 var mappings = new Mappings(options.hires);
1105 var locate = getLocator(this.original);
1106 if (this.intro) {
1107 mappings.advance(this.intro);
1108 }
1109 this.firstChunk.eachNext(function (chunk) {
1110 var loc = locate(chunk.start);
1111 if (chunk.intro.length) {
1112 mappings.advance(chunk.intro);
1113 }
1114 if (chunk.edited) {
1115 mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
1116 }
1117 else {
1118 mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
1119 }
1120 if (chunk.outro.length) {
1121 mappings.advance(chunk.outro);
1122 }
1123 });
1124 return {
1125 file: options.file ? options.file.split(/[/\\]/).pop() : null,
1126 sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
1127 sourcesContent: options.includeContent ? [this.original] : [null],
1128 names: names,
1129 mappings: mappings.raw
1130 };
1131};
1132MagicString.prototype.generateMap = function generateMap(options) {
1133 return new SourceMap(this.generateDecodedMap(options));
1134};
1135MagicString.prototype.getIndentString = function getIndentString() {
1136 return this.indentStr === null ? '\t' : this.indentStr;
1137};
1138MagicString.prototype.indent = function indent(indentStr, options) {
1139 var pattern = /^[^\r\n]/gm;
1140 if (isObject(indentStr)) {
1141 options = indentStr;
1142 indentStr = undefined;
1143 }
1144 indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
1145 if (indentStr === '') {
1146 return this;
1147 } // noop
1148 options = options || {};
1149 // Process exclusion ranges
1150 var isExcluded = {};
1151 if (options.exclude) {
1152 var exclusions = typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
1153 exclusions.forEach(function (exclusion) {
1154 for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
1155 isExcluded[i] = true;
1156 }
1157 });
1158 }
1159 var shouldIndentNextCharacter = options.indentStart !== false;
1160 var replacer = function (match) {
1161 if (shouldIndentNextCharacter) {
1162 return ("" + indentStr + match);
1163 }
1164 shouldIndentNextCharacter = true;
1165 return match;
1166 };
1167 this.intro = this.intro.replace(pattern, replacer);
1168 var charIndex = 0;
1169 var chunk = this.firstChunk;
1170 while (chunk) {
1171 var end = chunk.end;
1172 if (chunk.edited) {
1173 if (!isExcluded[charIndex]) {
1174 chunk.content = chunk.content.replace(pattern, replacer);
1175 if (chunk.content.length) {
1176 shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
1177 }
1178 }
1179 }
1180 else {
1181 charIndex = chunk.start;
1182 while (charIndex < end) {
1183 if (!isExcluded[charIndex]) {
1184 var char = this.original[charIndex];
1185 if (char === '\n') {
1186 shouldIndentNextCharacter = true;
1187 }
1188 else if (char !== '\r' && shouldIndentNextCharacter) {
1189 shouldIndentNextCharacter = false;
1190 if (charIndex === chunk.start) {
1191 chunk.prependRight(indentStr);
1192 }
1193 else {
1194 this._splitChunk(chunk, charIndex);
1195 chunk = chunk.next;
1196 chunk.prependRight(indentStr);
1197 }
1198 }
1199 }
1200 charIndex += 1;
1201 }
1202 }
1203 charIndex = chunk.end;
1204 chunk = chunk.next;
1205 }
1206 this.outro = this.outro.replace(pattern, replacer);
1207 return this;
1208};
1209MagicString.prototype.insert = function insert() {
1210 throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
1211};
1212MagicString.prototype.insertLeft = function insertLeft(index, content) {
1213 if (!warned.insertLeft) {
1214 console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
1215 warned.insertLeft = true;
1216 }
1217 return this.appendLeft(index, content);
1218};
1219MagicString.prototype.insertRight = function insertRight(index, content) {
1220 if (!warned.insertRight) {
1221 console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
1222 warned.insertRight = true;
1223 }
1224 return this.prependRight(index, content);
1225};
1226MagicString.prototype.move = function move(start, end, index) {
1227 if (index >= start && index <= end) {
1228 throw new Error('Cannot move a selection inside itself');
1229 }
1230 this._split(start);
1231 this._split(end);
1232 this._split(index);
1233 var first = this.byStart[start];
1234 var last = this.byEnd[end];
1235 var oldLeft = first.previous;
1236 var oldRight = last.next;
1237 var newRight = this.byStart[index];
1238 if (!newRight && last === this.lastChunk) {
1239 return this;
1240 }
1241 var newLeft = newRight ? newRight.previous : this.lastChunk;
1242 if (oldLeft) {
1243 oldLeft.next = oldRight;
1244 }
1245 if (oldRight) {
1246 oldRight.previous = oldLeft;
1247 }
1248 if (newLeft) {
1249 newLeft.next = first;
1250 }
1251 if (newRight) {
1252 newRight.previous = last;
1253 }
1254 if (!first.previous) {
1255 this.firstChunk = last.next;
1256 }
1257 if (!last.next) {
1258 this.lastChunk = first.previous;
1259 this.lastChunk.next = null;
1260 }
1261 first.previous = newLeft;
1262 last.next = newRight || null;
1263 if (!newLeft) {
1264 this.firstChunk = first;
1265 }
1266 if (!newRight) {
1267 this.lastChunk = last;
1268 }
1269 return this;
1270};
1271MagicString.prototype.overwrite = function overwrite(start, end, content, options) {
1272 if (typeof content !== 'string') {
1273 throw new TypeError('replacement content must be a string');
1274 }
1275 while (start < 0) {
1276 start += this.original.length;
1277 }
1278 while (end < 0) {
1279 end += this.original.length;
1280 }
1281 if (end > this.original.length) {
1282 throw new Error('end is out of bounds');
1283 }
1284 if (start === end) {
1285 throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead');
1286 }
1287 this._split(start);
1288 this._split(end);
1289 if (options === true) {
1290 if (!warned.storeName) {
1291 console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console
1292 warned.storeName = true;
1293 }
1294 options = { storeName: true };
1295 }
1296 var storeName = options !== undefined ? options.storeName : false;
1297 var contentOnly = options !== undefined ? options.contentOnly : false;
1298 if (storeName) {
1299 var original = this.original.slice(start, end);
1300 this.storedNames[original] = true;
1301 }
1302 var first = this.byStart[start];
1303 var last = this.byEnd[end];
1304 if (first) {
1305 if (end > first.end && first.next !== this.byStart[first.end]) {
1306 throw new Error('Cannot overwrite across a split point');
1307 }
1308 first.edit(content, storeName, contentOnly);
1309 if (first !== last) {
1310 var chunk = first.next;
1311 while (chunk !== last) {
1312 chunk.edit('', false);
1313 chunk = chunk.next;
1314 }
1315 chunk.edit('', false);
1316 }
1317 }
1318 else {
1319 // must be inserting at the end
1320 var newChunk = new Chunk(start, end, '').edit(content, storeName);
1321 // TODO last chunk in the array may not be the last chunk, if it's moved...
1322 last.next = newChunk;
1323 newChunk.previous = last;
1324 }
1325 return this;
1326};
1327MagicString.prototype.prepend = function prepend(content) {
1328 if (typeof content !== 'string') {
1329 throw new TypeError('outro content must be a string');
1330 }
1331 this.intro = content + this.intro;
1332 return this;
1333};
1334MagicString.prototype.prependLeft = function prependLeft(index, content) {
1335 if (typeof content !== 'string') {
1336 throw new TypeError('inserted content must be a string');
1337 }
1338 this._split(index);
1339 var chunk = this.byEnd[index];
1340 if (chunk) {
1341 chunk.prependLeft(content);
1342 }
1343 else {
1344 this.intro = content + this.intro;
1345 }
1346 return this;
1347};
1348MagicString.prototype.prependRight = function prependRight(index, content) {
1349 if (typeof content !== 'string') {
1350 throw new TypeError('inserted content must be a string');
1351 }
1352 this._split(index);
1353 var chunk = this.byStart[index];
1354 if (chunk) {
1355 chunk.prependRight(content);
1356 }
1357 else {
1358 this.outro = content + this.outro;
1359 }
1360 return this;
1361};
1362MagicString.prototype.remove = function remove(start, end) {
1363 while (start < 0) {
1364 start += this.original.length;
1365 }
1366 while (end < 0) {
1367 end += this.original.length;
1368 }
1369 if (start === end) {
1370 return this;
1371 }
1372 if (start < 0 || end > this.original.length) {
1373 throw new Error('Character is out of bounds');
1374 }
1375 if (start > end) {
1376 throw new Error('end must be greater than start');
1377 }
1378 this._split(start);
1379 this._split(end);
1380 var chunk = this.byStart[start];
1381 while (chunk) {
1382 chunk.intro = '';
1383 chunk.outro = '';
1384 chunk.edit('');
1385 chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1386 }
1387 return this;
1388};
1389MagicString.prototype.lastChar = function lastChar() {
1390 if (this.outro.length) {
1391 return this.outro[this.outro.length - 1];
1392 }
1393 var chunk = this.lastChunk;
1394 do {
1395 if (chunk.outro.length) {
1396 return chunk.outro[chunk.outro.length - 1];
1397 }
1398 if (chunk.content.length) {
1399 return chunk.content[chunk.content.length - 1];
1400 }
1401 if (chunk.intro.length) {
1402 return chunk.intro[chunk.intro.length - 1];
1403 }
1404 } while (chunk = chunk.previous);
1405 if (this.intro.length) {
1406 return this.intro[this.intro.length - 1];
1407 }
1408 return '';
1409};
1410MagicString.prototype.lastLine = function lastLine() {
1411 var lineIndex = this.outro.lastIndexOf(n);
1412 if (lineIndex !== -1) {
1413 return this.outro.substr(lineIndex + 1);
1414 }
1415 var lineStr = this.outro;
1416 var chunk = this.lastChunk;
1417 do {
1418 if (chunk.outro.length > 0) {
1419 lineIndex = chunk.outro.lastIndexOf(n);
1420 if (lineIndex !== -1) {
1421 return chunk.outro.substr(lineIndex + 1) + lineStr;
1422 }
1423 lineStr = chunk.outro + lineStr;
1424 }
1425 if (chunk.content.length > 0) {
1426 lineIndex = chunk.content.lastIndexOf(n);
1427 if (lineIndex !== -1) {
1428 return chunk.content.substr(lineIndex + 1) + lineStr;
1429 }
1430 lineStr = chunk.content + lineStr;
1431 }
1432 if (chunk.intro.length > 0) {
1433 lineIndex = chunk.intro.lastIndexOf(n);
1434 if (lineIndex !== -1) {
1435 return chunk.intro.substr(lineIndex + 1) + lineStr;
1436 }
1437 lineStr = chunk.intro + lineStr;
1438 }
1439 } while (chunk = chunk.previous);
1440 lineIndex = this.intro.lastIndexOf(n);
1441 if (lineIndex !== -1) {
1442 return this.intro.substr(lineIndex + 1) + lineStr;
1443 }
1444 return this.intro + lineStr;
1445};
1446MagicString.prototype.slice = function slice(start, end) {
1447 if (start === void 0)
1448 start = 0;
1449 if (end === void 0)
1450 end = this.original.length;
1451 while (start < 0) {
1452 start += this.original.length;
1453 }
1454 while (end < 0) {
1455 end += this.original.length;
1456 }
1457 var result = '';
1458 // find start chunk
1459 var chunk = this.firstChunk;
1460 while (chunk && (chunk.start > start || chunk.end <= start)) {
1461 // found end chunk before start
1462 if (chunk.start < end && chunk.end >= end) {
1463 return result;
1464 }
1465 chunk = chunk.next;
1466 }
1467 if (chunk && chunk.edited && chunk.start !== start) {
1468 throw new Error(("Cannot use replaced character " + start + " as slice start anchor."));
1469 }
1470 var startChunk = chunk;
1471 while (chunk) {
1472 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1473 result += chunk.intro;
1474 }
1475 var containsEnd = chunk.start < end && chunk.end >= end;
1476 if (containsEnd && chunk.edited && chunk.end !== end) {
1477 throw new Error(("Cannot use replaced character " + end + " as slice end anchor."));
1478 }
1479 var sliceStart = startChunk === chunk ? start - chunk.start : 0;
1480 var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1481 result += chunk.content.slice(sliceStart, sliceEnd);
1482 if (chunk.outro && (!containsEnd || chunk.end === end)) {
1483 result += chunk.outro;
1484 }
1485 if (containsEnd) {
1486 break;
1487 }
1488 chunk = chunk.next;
1489 }
1490 return result;
1491};
1492// TODO deprecate this? not really very useful
1493MagicString.prototype.snip = function snip(start, end) {
1494 var clone = this.clone();
1495 clone.remove(0, start);
1496 clone.remove(end, clone.original.length);
1497 return clone;
1498};
1499MagicString.prototype._split = function _split(index) {
1500 if (this.byStart[index] || this.byEnd[index]) {
1501 return;
1502 }
1503 var chunk = this.lastSearchedChunk;
1504 var searchForward = index > chunk.end;
1505 while (chunk) {
1506 if (chunk.contains(index)) {
1507 return this._splitChunk(chunk, index);
1508 }
1509 chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1510 }
1511};
1512MagicString.prototype._splitChunk = function _splitChunk(chunk, index) {
1513 if (chunk.edited && chunk.content.length) {
1514 // zero-length edited chunks are a special case (overlapping replacements)
1515 var loc = getLocator(this.original)(index);
1516 throw new Error(("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")"));
1517 }
1518 var newChunk = chunk.split(index);
1519 this.byEnd[index] = chunk;
1520 this.byStart[index] = newChunk;
1521 this.byEnd[newChunk.end] = newChunk;
1522 if (chunk === this.lastChunk) {
1523 this.lastChunk = newChunk;
1524 }
1525 this.lastSearchedChunk = chunk;
1526 return true;
1527};
1528MagicString.prototype.toString = function toString() {
1529 var str = this.intro;
1530 var chunk = this.firstChunk;
1531 while (chunk) {
1532 str += chunk.toString();
1533 chunk = chunk.next;
1534 }
1535 return str + this.outro;
1536};
1537MagicString.prototype.isEmpty = function isEmpty() {
1538 var chunk = this.firstChunk;
1539 do {
1540 if (chunk.intro.length && chunk.intro.trim() ||
1541 chunk.content.length && chunk.content.trim() ||
1542 chunk.outro.length && chunk.outro.trim()) {
1543 return false;
1544 }
1545 } while (chunk = chunk.next);
1546 return true;
1547};
1548MagicString.prototype.length = function length() {
1549 var chunk = this.firstChunk;
1550 var length = 0;
1551 do {
1552 length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1553 } while (chunk = chunk.next);
1554 return length;
1555};
1556MagicString.prototype.trimLines = function trimLines() {
1557 return this.trim('[\\r\\n]');
1558};
1559MagicString.prototype.trim = function trim(charType) {
1560 return this.trimStart(charType).trimEnd(charType);
1561};
1562MagicString.prototype.trimEndAborted = function trimEndAborted(charType) {
1563 var rx = new RegExp((charType || '\\s') + '+$');
1564 this.outro = this.outro.replace(rx, '');
1565 if (this.outro.length) {
1566 return true;
1567 }
1568 var chunk = this.lastChunk;
1569 do {
1570 var end = chunk.end;
1571 var aborted = chunk.trimEnd(rx);
1572 // if chunk was trimmed, we have a new lastChunk
1573 if (chunk.end !== end) {
1574 if (this.lastChunk === chunk) {
1575 this.lastChunk = chunk.next;
1576 }
1577 this.byEnd[chunk.end] = chunk;
1578 this.byStart[chunk.next.start] = chunk.next;
1579 this.byEnd[chunk.next.end] = chunk.next;
1580 }
1581 if (aborted) {
1582 return true;
1583 }
1584 chunk = chunk.previous;
1585 } while (chunk);
1586 return false;
1587};
1588MagicString.prototype.trimEnd = function trimEnd(charType) {
1589 this.trimEndAborted(charType);
1590 return this;
1591};
1592MagicString.prototype.trimStartAborted = function trimStartAborted(charType) {
1593 var rx = new RegExp('^' + (charType || '\\s') + '+');
1594 this.intro = this.intro.replace(rx, '');
1595 if (this.intro.length) {
1596 return true;
1597 }
1598 var chunk = this.firstChunk;
1599 do {
1600 var end = chunk.end;
1601 var aborted = chunk.trimStart(rx);
1602 if (chunk.end !== end) {
1603 // special case...
1604 if (chunk === this.lastChunk) {
1605 this.lastChunk = chunk.next;
1606 }
1607 this.byEnd[chunk.end] = chunk;
1608 this.byStart[chunk.next.start] = chunk.next;
1609 this.byEnd[chunk.next.end] = chunk.next;
1610 }
1611 if (aborted) {
1612 return true;
1613 }
1614 chunk = chunk.next;
1615 } while (chunk);
1616 return false;
1617};
1618MagicString.prototype.trimStart = function trimStart(charType) {
1619 this.trimStartAborted(charType);
1620 return this;
1621};
1622var hasOwnProp = Object.prototype.hasOwnProperty;
1623var Bundle = function Bundle(options) {
1624 if (options === void 0)
1625 options = {};
1626 this.intro = options.intro || '';
1627 this.separator = options.separator !== undefined ? options.separator : '\n';
1628 this.sources = [];
1629 this.uniqueSources = [];
1630 this.uniqueSourceIndexByFilename = {};
1631};
1632Bundle.prototype.addSource = function addSource(source) {
1633 if (source instanceof MagicString) {
1634 return this.addSource({
1635 content: source,
1636 filename: source.filename,
1637 separator: this.separator
1638 });
1639 }
1640 if (!isObject(source) || !source.content) {
1641 throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
1642 }
1643 ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
1644 if (!hasOwnProp.call(source, option)) {
1645 source[option] = source.content[option];
1646 }
1647 });
1648 if (source.separator === undefined) {
1649 // TODO there's a bunch of this sort of thing, needs cleaning up
1650 source.separator = this.separator;
1651 }
1652 if (source.filename) {
1653 if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
1654 this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
1655 this.uniqueSources.push({ filename: source.filename, content: source.content.original });
1656 }
1657 else {
1658 var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
1659 if (source.content.original !== uniqueSource.content) {
1660 throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
1661 }
1662 }
1663 }
1664 this.sources.push(source);
1665 return this;
1666};
1667Bundle.prototype.append = function append(str, options) {
1668 this.addSource({
1669 content: new MagicString(str),
1670 separator: (options && options.separator) || ''
1671 });
1672 return this;
1673};
1674Bundle.prototype.clone = function clone() {
1675 var bundle = new Bundle({
1676 intro: this.intro,
1677 separator: this.separator
1678 });
1679 this.sources.forEach(function (source) {
1680 bundle.addSource({
1681 filename: source.filename,
1682 content: source.content.clone(),
1683 separator: source.separator
1684 });
1685 });
1686 return bundle;
1687};
1688Bundle.prototype.generateDecodedMap = function generateDecodedMap(options) {
1689 var this$1 = this;
1690 if (options === void 0)
1691 options = {};
1692 var names = [];
1693 this.sources.forEach(function (source) {
1694 Object.keys(source.content.storedNames).forEach(function (name) {
1695 if (!~names.indexOf(name)) {
1696 names.push(name);
1697 }
1698 });
1699 });
1700 var mappings = new Mappings(options.hires);
1701 if (this.intro) {
1702 mappings.advance(this.intro);
1703 }
1704 this.sources.forEach(function (source, i) {
1705 if (i > 0) {
1706 mappings.advance(this$1.separator);
1707 }
1708 var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[source.filename] : -1;
1709 var magicString = source.content;
1710 var locate = getLocator(magicString.original);
1711 if (magicString.intro) {
1712 mappings.advance(magicString.intro);
1713 }
1714 magicString.firstChunk.eachNext(function (chunk) {
1715 var loc = locate(chunk.start);
1716 if (chunk.intro.length) {
1717 mappings.advance(chunk.intro);
1718 }
1719 if (source.filename) {
1720 if (chunk.edited) {
1721 mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
1722 }
1723 else {
1724 mappings.addUneditedChunk(sourceIndex, chunk, magicString.original, loc, magicString.sourcemapLocations);
1725 }
1726 }
1727 else {
1728 mappings.advance(chunk.content);
1729 }
1730 if (chunk.outro.length) {
1731 mappings.advance(chunk.outro);
1732 }
1733 });
1734 if (magicString.outro) {
1735 mappings.advance(magicString.outro);
1736 }
1737 });
1738 return {
1739 file: options.file ? options.file.split(/[/\\]/).pop() : null,
1740 sources: this.uniqueSources.map(function (source) {
1741 return options.file ? getRelativePath(options.file, source.filename) : source.filename;
1742 }),
1743 sourcesContent: this.uniqueSources.map(function (source) {
1744 return options.includeContent ? source.content : null;
1745 }),
1746 names: names,
1747 mappings: mappings.raw
1748 };
1749};
1750Bundle.prototype.generateMap = function generateMap(options) {
1751 return new SourceMap(this.generateDecodedMap(options));
1752};
1753Bundle.prototype.getIndentString = function getIndentString() {
1754 var indentStringCounts = {};
1755 this.sources.forEach(function (source) {
1756 var indentStr = source.content.indentStr;
1757 if (indentStr === null) {
1758 return;
1759 }
1760 if (!indentStringCounts[indentStr]) {
1761 indentStringCounts[indentStr] = 0;
1762 }
1763 indentStringCounts[indentStr] += 1;
1764 });
1765 return (Object.keys(indentStringCounts).sort(function (a, b) {
1766 return indentStringCounts[a] - indentStringCounts[b];
1767 })[0] || '\t');
1768};
1769Bundle.prototype.indent = function indent(indentStr) {
1770 var this$1 = this;
1771 if (!arguments.length) {
1772 indentStr = this.getIndentString();
1773 }
1774 if (indentStr === '') {
1775 return this;
1776 } // noop
1777 var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
1778 this.sources.forEach(function (source, i) {
1779 var separator = source.separator !== undefined ? source.separator : this$1.separator;
1780 var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
1781 source.content.indent(indentStr, {
1782 exclude: source.indentExclusionRanges,
1783 indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
1784 });
1785 trailingNewline = source.content.lastChar() === '\n';
1786 });
1787 if (this.intro) {
1788 this.intro =
1789 indentStr +
1790 this.intro.replace(/^[^\n]/gm, function (match, index) {
1791 return index > 0 ? indentStr + match : match;
1792 });
1793 }
1794 return this;
1795};
1796Bundle.prototype.prepend = function prepend(str) {
1797 this.intro = str + this.intro;
1798 return this;
1799};
1800Bundle.prototype.toString = function toString() {
1801 var this$1 = this;
1802 var body = this.sources
1803 .map(function (source, i) {
1804 var separator = source.separator !== undefined ? source.separator : this$1.separator;
1805 var str = (i > 0 ? separator : '') + source.content.toString();
1806 return str;
1807 })
1808 .join('');
1809 return this.intro + body;
1810};
1811Bundle.prototype.isEmpty = function isEmpty() {
1812 if (this.intro.length && this.intro.trim()) {
1813 return false;
1814 }
1815 if (this.sources.some(function (source) { return !source.content.isEmpty(); })) {
1816 return false;
1817 }
1818 return true;
1819};
1820Bundle.prototype.length = function length() {
1821 return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
1822};
1823Bundle.prototype.trimLines = function trimLines() {
1824 return this.trim('[\\r\\n]');
1825};
1826Bundle.prototype.trim = function trim(charType) {
1827 return this.trimStart(charType).trimEnd(charType);
1828};
1829Bundle.prototype.trimStart = function trimStart(charType) {
1830 var rx = new RegExp('^' + (charType || '\\s') + '+');
1831 this.intro = this.intro.replace(rx, '');
1832 if (!this.intro) {
1833 var source;
1834 var i = 0;
1835 do {
1836 source = this.sources[i++];
1837 if (!source) {
1838 break;
1839 }
1840 } while (!source.content.trimStartAborted(charType));
1841 }
1842 return this;
1843};
1844Bundle.prototype.trimEnd = function trimEnd(charType) {
1845 var rx = new RegExp((charType || '\\s') + '+$');
1846 var source;
1847 var i = this.sources.length - 1;
1848 do {
1849 source = this.sources[i--];
1850 if (!source) {
1851 this.intro = this.intro.replace(rx, '');
1852 break;
1853 }
1854 } while (!source.content.trimEndAborted(charType));
1855 return this;
1856};
1857
1858function relative(from, to) {
1859 const fromParts = from.split(/[/\\]/).filter(Boolean);
1860 const toParts = to.split(/[/\\]/).filter(Boolean);
1861 if (fromParts[0] === '.')
1862 fromParts.shift();
1863 if (toParts[0] === '.')
1864 toParts.shift();
1865 while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
1866 fromParts.shift();
1867 toParts.shift();
1868 }
1869 while (toParts[0] === '..' && fromParts.length > 0) {
1870 toParts.shift();
1871 fromParts.pop();
1872 }
1873 while (fromParts.pop()) {
1874 toParts.unshift('..');
1875 }
1876 return toParts.join('/');
1877}
1878
1879const BLANK = Object.create(null);
1880
1881const BlockStatement = 'BlockStatement';
1882const CallExpression = 'CallExpression';
1883const ExportAllDeclaration = 'ExportAllDeclaration';
1884const ExpressionStatement = 'ExpressionStatement';
1885const FunctionExpression = 'FunctionExpression';
1886const Identifier = 'Identifier';
1887const ImportDefaultSpecifier = 'ImportDefaultSpecifier';
1888const ImportNamespaceSpecifier = 'ImportNamespaceSpecifier';
1889const Program = 'Program';
1890const Property = 'Property';
1891const ReturnStatement = 'ReturnStatement';
1892const VariableDeclaration = 'VariableDeclaration';
1893
1894function treeshakeNode(node, code, start, end) {
1895 code.remove(start, end);
1896 if (node.annotations) {
1897 for (const annotation of node.annotations) {
1898 if (annotation.start < start) {
1899 code.remove(annotation.start, annotation.end);
1900 }
1901 else {
1902 return;
1903 }
1904 }
1905 }
1906}
1907function removeAnnotations(node, code) {
1908 if (!node.annotations && node.parent.type === ExpressionStatement) {
1909 node = node.parent;
1910 }
1911 if (node.annotations) {
1912 for (const annotation of node.annotations) {
1913 code.remove(annotation.start, annotation.end);
1914 }
1915 }
1916}
1917
1918const NO_SEMICOLON = { isNoStatement: true };
1919function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
1920 let searchPos, charCodeAfterSlash;
1921 searchPos = code.indexOf(searchString, start);
1922 while (true) {
1923 start = code.indexOf('/', start);
1924 if (start === -1 || start > searchPos)
1925 return searchPos;
1926 charCodeAfterSlash = code.charCodeAt(++start);
1927 ++start;
1928 if (charCodeAfterSlash === 47 /*"/"*/) {
1929 start = code.indexOf('\n', start) + 1;
1930 if (start === 0)
1931 return -1;
1932 if (start > searchPos) {
1933 searchPos = code.indexOf(searchString, start);
1934 }
1935 }
1936 else if (charCodeAfterSlash === 42 /*"*"*/) {
1937 start = code.indexOf('*/', start) + 2;
1938 if (start > searchPos) {
1939 searchPos = code.indexOf(searchString, start);
1940 }
1941 }
1942 }
1943}
1944function findFirstLineBreakOutsideComment(code, start = 0) {
1945 let lineBreakPos, charCodeAfterSlash;
1946 lineBreakPos = code.indexOf('\n', start);
1947 while (true) {
1948 start = code.indexOf('/', start);
1949 if (start === -1 || start > lineBreakPos)
1950 return lineBreakPos;
1951 charCodeAfterSlash = code.charCodeAt(++start);
1952 if (charCodeAfterSlash === 47 /*"/"*/)
1953 return lineBreakPos;
1954 ++start;
1955 if (charCodeAfterSlash === 42 /*"*"*/) {
1956 start = code.indexOf('*/', start) + 2;
1957 if (start > lineBreakPos) {
1958 lineBreakPos = code.indexOf('\n', start);
1959 }
1960 }
1961 }
1962}
1963function renderStatementList(statements, code, start, end, options) {
1964 if (statements.length === 0)
1965 return;
1966 let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
1967 let nextNode = statements[0];
1968 let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
1969 if (nextNodeNeedsBoundaries) {
1970 nextNodeStart =
1971 start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start)) + 1;
1972 }
1973 for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
1974 currentNode = nextNode;
1975 currentNodeStart = nextNodeStart;
1976 currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
1977 nextNode = statements[nextIndex];
1978 nextNodeNeedsBoundaries =
1979 nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
1980 if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
1981 nextNodeStart =
1982 currentNode.end +
1983 findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start)) +
1984 1;
1985 if (currentNode.included) {
1986 currentNodeNeedsBoundaries
1987 ? currentNode.render(code, options, {
1988 end: nextNodeStart,
1989 start: currentNodeStart
1990 })
1991 : currentNode.render(code, options);
1992 }
1993 else {
1994 treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
1995 }
1996 }
1997 else {
1998 currentNode.render(code, options);
1999 }
2000 }
2001}
2002// This assumes that the first character is not part of the first node
2003function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
2004 const splitUpNodes = [];
2005 let node, nextNode, nextNodeStart, contentEnd, char;
2006 let separator = start - 1;
2007 for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
2008 nextNode = nodes[nextIndex];
2009 if (node !== undefined) {
2010 separator =
2011 node.end +
2012 findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
2013 }
2014 nextNodeStart = contentEnd =
2015 separator +
2016 2 +
2017 findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start));
2018 while (((char = code.original.charCodeAt(nextNodeStart)),
2019 char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
2020 nextNodeStart++;
2021 if (node !== undefined) {
2022 splitUpNodes.push({
2023 contentEnd,
2024 end: nextNodeStart,
2025 node,
2026 separator,
2027 start
2028 });
2029 }
2030 node = nextNode;
2031 start = nextNodeStart;
2032 }
2033 splitUpNodes.push({
2034 contentEnd: end,
2035 end,
2036 node: node,
2037 separator: null,
2038 start
2039 });
2040 return splitUpNodes;
2041}
2042
2043const chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
2044const base = 64;
2045function toBase64(num) {
2046 let outStr = '';
2047 do {
2048 const curDigit = num % base;
2049 num = Math.floor(num / base);
2050 outStr = chars$1[curDigit] + outStr;
2051 } while (num !== 0);
2052 return outStr;
2053}
2054
2055// Verified on IE 6/7 that these keywords can't be used for object properties without escaping:
2056// break case catch class const continue debugger default delete do
2057// else enum export extends false finally for function if import
2058// in instanceof new null return super switch this throw true
2059// try typeof var void while with
2060const RESERVED_NAMES = Object.assign(Object.create(null), {
2061 await: true,
2062 break: true,
2063 case: true,
2064 catch: true,
2065 class: true,
2066 const: true,
2067 continue: true,
2068 debugger: true,
2069 default: true,
2070 delete: true,
2071 do: true,
2072 else: true,
2073 enum: true,
2074 eval: true,
2075 export: true,
2076 extends: true,
2077 false: true,
2078 finally: true,
2079 for: true,
2080 function: true,
2081 if: true,
2082 implements: true,
2083 import: true,
2084 in: true,
2085 instanceof: true,
2086 interface: true,
2087 let: true,
2088 new: true,
2089 null: true,
2090 package: true,
2091 private: true,
2092 protected: true,
2093 public: true,
2094 return: true,
2095 static: true,
2096 super: true,
2097 switch: true,
2098 this: true,
2099 throw: true,
2100 true: true,
2101 try: true,
2102 typeof: true,
2103 undefined: true,
2104 var: true,
2105 void: true,
2106 while: true,
2107 with: true,
2108 yield: true
2109});
2110
2111function getSafeName(baseName, usedNames) {
2112 let safeName = baseName;
2113 let count = 1;
2114 while (usedNames.has(safeName) || RESERVED_NAMES[safeName]) {
2115 safeName = `${baseName}$${toBase64(count++)}`;
2116 }
2117 usedNames.add(safeName);
2118 return safeName;
2119}
2120
2121class CallOptions {
2122 static create(callOptions) {
2123 return new this(callOptions);
2124 }
2125 constructor({ withNew = false, args = [], callIdentifier = undefined } = {}) {
2126 this.withNew = withNew;
2127 this.args = args;
2128 this.callIdentifier = callIdentifier;
2129 }
2130 equals(callOptions) {
2131 return callOptions && this.callIdentifier === callOptions.callIdentifier;
2132 }
2133}
2134
2135const UNKNOWN_KEY = { UNKNOWN_KEY: true };
2136const EMPTY_PATH = [];
2137const UNKNOWN_PATH = [UNKNOWN_KEY];
2138function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
2139 return Object.create(inheritedDescriptions, memberDescriptions);
2140}
2141const UNKNOWN_VALUE = { UNKNOWN_VALUE: true };
2142const UNKNOWN_EXPRESSION = {
2143 deoptimizePath: () => { },
2144 getLiteralValueAtPath: () => UNKNOWN_VALUE,
2145 getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
2146 hasEffectsWhenAccessedAtPath: path => path.length > 0,
2147 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2148 hasEffectsWhenCalledAtPath: () => true,
2149 include: () => { },
2150 includeCallArguments(args) {
2151 for (const arg of args) {
2152 arg.include(false);
2153 }
2154 },
2155 included: true,
2156 toString: () => '[[UNKNOWN]]'
2157};
2158const UNDEFINED_EXPRESSION = {
2159 deoptimizePath: () => { },
2160 getLiteralValueAtPath: () => undefined,
2161 getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
2162 hasEffectsWhenAccessedAtPath: path => path.length > 0,
2163 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2164 hasEffectsWhenCalledAtPath: () => true,
2165 include: () => { },
2166 includeCallArguments() { },
2167 included: true,
2168 toString: () => 'undefined'
2169};
2170const returnsUnknown = {
2171 value: {
2172 callsArgs: null,
2173 mutatesSelf: false,
2174 returns: null,
2175 returnsPrimitive: UNKNOWN_EXPRESSION
2176 }
2177};
2178const mutatesSelfReturnsUnknown = {
2179 value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: null, mutatesSelf: true }
2180};
2181const callsArgReturnsUnknown = {
2182 value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: [0], mutatesSelf: false }
2183};
2184class UnknownArrayExpression {
2185 constructor() {
2186 this.included = false;
2187 }
2188 deoptimizePath() { }
2189 getLiteralValueAtPath() {
2190 return UNKNOWN_VALUE;
2191 }
2192 getReturnExpressionWhenCalledAtPath(path) {
2193 if (path.length === 1) {
2194 return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
2195 }
2196 return UNKNOWN_EXPRESSION;
2197 }
2198 hasEffectsWhenAccessedAtPath(path) {
2199 return path.length > 1;
2200 }
2201 hasEffectsWhenAssignedAtPath(path) {
2202 return path.length > 1;
2203 }
2204 hasEffectsWhenCalledAtPath(path, callOptions, options) {
2205 if (path.length === 1) {
2206 return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, options);
2207 }
2208 return true;
2209 }
2210 include() {
2211 this.included = true;
2212 }
2213 includeCallArguments(args) {
2214 for (const arg of args) {
2215 arg.include(false);
2216 }
2217 }
2218 toString() {
2219 return '[[UNKNOWN ARRAY]]';
2220 }
2221}
2222const returnsArray = {
2223 value: {
2224 callsArgs: null,
2225 mutatesSelf: false,
2226 returns: UnknownArrayExpression,
2227 returnsPrimitive: null
2228 }
2229};
2230const mutatesSelfReturnsArray = {
2231 value: {
2232 callsArgs: null,
2233 mutatesSelf: true,
2234 returns: UnknownArrayExpression,
2235 returnsPrimitive: null
2236 }
2237};
2238const callsArgReturnsArray = {
2239 value: {
2240 callsArgs: [0],
2241 mutatesSelf: false,
2242 returns: UnknownArrayExpression,
2243 returnsPrimitive: null
2244 }
2245};
2246const callsArgMutatesSelfReturnsArray = {
2247 value: {
2248 callsArgs: [0],
2249 mutatesSelf: true,
2250 returns: UnknownArrayExpression,
2251 returnsPrimitive: null
2252 }
2253};
2254const UNKNOWN_LITERAL_BOOLEAN = {
2255 deoptimizePath: () => { },
2256 getLiteralValueAtPath: () => UNKNOWN_VALUE,
2257 getReturnExpressionWhenCalledAtPath: path => {
2258 if (path.length === 1) {
2259 return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
2260 }
2261 return UNKNOWN_EXPRESSION;
2262 },
2263 hasEffectsWhenAccessedAtPath: path => path.length > 1,
2264 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2265 hasEffectsWhenCalledAtPath: path => {
2266 if (path.length === 1) {
2267 const subPath = path[0];
2268 return typeof subPath !== 'string' || !literalBooleanMembers[subPath];
2269 }
2270 return true;
2271 },
2272 include: () => { },
2273 includeCallArguments(args) {
2274 for (const arg of args) {
2275 arg.include(false);
2276 }
2277 },
2278 included: true,
2279 toString: () => '[[UNKNOWN BOOLEAN]]'
2280};
2281const returnsBoolean = {
2282 value: {
2283 callsArgs: null,
2284 mutatesSelf: false,
2285 returns: null,
2286 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
2287 }
2288};
2289const callsArgReturnsBoolean = {
2290 value: {
2291 callsArgs: [0],
2292 mutatesSelf: false,
2293 returns: null,
2294 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
2295 }
2296};
2297const UNKNOWN_LITERAL_NUMBER = {
2298 deoptimizePath: () => { },
2299 getLiteralValueAtPath: () => UNKNOWN_VALUE,
2300 getReturnExpressionWhenCalledAtPath: path => {
2301 if (path.length === 1) {
2302 return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
2303 }
2304 return UNKNOWN_EXPRESSION;
2305 },
2306 hasEffectsWhenAccessedAtPath: path => path.length > 1,
2307 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2308 hasEffectsWhenCalledAtPath: path => {
2309 if (path.length === 1) {
2310 const subPath = path[0];
2311 return typeof subPath !== 'string' || !literalNumberMembers[subPath];
2312 }
2313 return true;
2314 },
2315 include: () => { },
2316 includeCallArguments(args) {
2317 for (const arg of args) {
2318 arg.include(false);
2319 }
2320 },
2321 included: true,
2322 toString: () => '[[UNKNOWN NUMBER]]'
2323};
2324const returnsNumber = {
2325 value: {
2326 callsArgs: null,
2327 mutatesSelf: false,
2328 returns: null,
2329 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2330 }
2331};
2332const mutatesSelfReturnsNumber = {
2333 value: {
2334 callsArgs: null,
2335 mutatesSelf: true,
2336 returns: null,
2337 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2338 }
2339};
2340const callsArgReturnsNumber = {
2341 value: {
2342 callsArgs: [0],
2343 mutatesSelf: false,
2344 returns: null,
2345 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2346 }
2347};
2348const UNKNOWN_LITERAL_STRING = {
2349 deoptimizePath: () => { },
2350 getLiteralValueAtPath: () => UNKNOWN_VALUE,
2351 getReturnExpressionWhenCalledAtPath: path => {
2352 if (path.length === 1) {
2353 return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
2354 }
2355 return UNKNOWN_EXPRESSION;
2356 },
2357 hasEffectsWhenAccessedAtPath: path => path.length > 1,
2358 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2359 hasEffectsWhenCalledAtPath: (path, callOptions, options) => {
2360 if (path.length === 1) {
2361 return hasMemberEffectWhenCalled(literalStringMembers, path[0], true, callOptions, options);
2362 }
2363 return true;
2364 },
2365 include: () => { },
2366 includeCallArguments(args) {
2367 for (const arg of args) {
2368 arg.include(false);
2369 }
2370 },
2371 included: true,
2372 toString: () => '[[UNKNOWN STRING]]'
2373};
2374const returnsString = {
2375 value: {
2376 callsArgs: null,
2377 mutatesSelf: false,
2378 returns: null,
2379 returnsPrimitive: UNKNOWN_LITERAL_STRING
2380 }
2381};
2382class UnknownObjectExpression {
2383 constructor() {
2384 this.included = false;
2385 }
2386 deoptimizePath() { }
2387 getLiteralValueAtPath() {
2388 return UNKNOWN_VALUE;
2389 }
2390 getReturnExpressionWhenCalledAtPath(path) {
2391 if (path.length === 1) {
2392 return getMemberReturnExpressionWhenCalled(objectMembers, path[0]);
2393 }
2394 return UNKNOWN_EXPRESSION;
2395 }
2396 hasEffectsWhenAccessedAtPath(path) {
2397 return path.length > 1;
2398 }
2399 hasEffectsWhenAssignedAtPath(path) {
2400 return path.length > 1;
2401 }
2402 hasEffectsWhenCalledAtPath(path, callOptions, options) {
2403 if (path.length === 1) {
2404 return hasMemberEffectWhenCalled(objectMembers, path[0], this.included, callOptions, options);
2405 }
2406 return true;
2407 }
2408 include() {
2409 this.included = true;
2410 }
2411 includeCallArguments(args) {
2412 for (const arg of args) {
2413 arg.include(false);
2414 }
2415 }
2416 toString() {
2417 return '[[UNKNOWN OBJECT]]';
2418 }
2419}
2420const objectMembers = assembleMemberDescriptions({
2421 hasOwnProperty: returnsBoolean,
2422 isPrototypeOf: returnsBoolean,
2423 propertyIsEnumerable: returnsBoolean,
2424 toLocaleString: returnsString,
2425 toString: returnsString,
2426 valueOf: returnsUnknown
2427});
2428const arrayMembers = assembleMemberDescriptions({
2429 concat: returnsArray,
2430 copyWithin: mutatesSelfReturnsArray,
2431 every: callsArgReturnsBoolean,
2432 fill: mutatesSelfReturnsArray,
2433 filter: callsArgReturnsArray,
2434 find: callsArgReturnsUnknown,
2435 findIndex: callsArgReturnsNumber,
2436 forEach: callsArgReturnsUnknown,
2437 includes: returnsBoolean,
2438 indexOf: returnsNumber,
2439 join: returnsString,
2440 lastIndexOf: returnsNumber,
2441 map: callsArgReturnsArray,
2442 pop: mutatesSelfReturnsUnknown,
2443 push: mutatesSelfReturnsNumber,
2444 reduce: callsArgReturnsUnknown,
2445 reduceRight: callsArgReturnsUnknown,
2446 reverse: mutatesSelfReturnsArray,
2447 shift: mutatesSelfReturnsUnknown,
2448 slice: returnsArray,
2449 some: callsArgReturnsBoolean,
2450 sort: callsArgMutatesSelfReturnsArray,
2451 splice: mutatesSelfReturnsArray,
2452 unshift: mutatesSelfReturnsNumber
2453}, objectMembers);
2454const literalBooleanMembers = assembleMemberDescriptions({
2455 valueOf: returnsBoolean
2456}, objectMembers);
2457const literalNumberMembers = assembleMemberDescriptions({
2458 toExponential: returnsString,
2459 toFixed: returnsString,
2460 toLocaleString: returnsString,
2461 toPrecision: returnsString,
2462 valueOf: returnsNumber
2463}, objectMembers);
2464const literalStringMembers = assembleMemberDescriptions({
2465 charAt: returnsString,
2466 charCodeAt: returnsNumber,
2467 codePointAt: returnsNumber,
2468 concat: returnsString,
2469 endsWith: returnsBoolean,
2470 includes: returnsBoolean,
2471 indexOf: returnsNumber,
2472 lastIndexOf: returnsNumber,
2473 localeCompare: returnsNumber,
2474 match: returnsBoolean,
2475 normalize: returnsString,
2476 padEnd: returnsString,
2477 padStart: returnsString,
2478 repeat: returnsString,
2479 replace: {
2480 value: {
2481 callsArgs: [1],
2482 mutatesSelf: false,
2483 returns: null,
2484 returnsPrimitive: UNKNOWN_LITERAL_STRING
2485 }
2486 },
2487 search: returnsNumber,
2488 slice: returnsString,
2489 split: returnsArray,
2490 startsWith: returnsBoolean,
2491 substr: returnsString,
2492 substring: returnsString,
2493 toLocaleLowerCase: returnsString,
2494 toLocaleUpperCase: returnsString,
2495 toLowerCase: returnsString,
2496 toUpperCase: returnsString,
2497 trim: returnsString,
2498 valueOf: returnsString
2499}, objectMembers);
2500function getLiteralMembersForValue(value) {
2501 switch (typeof value) {
2502 case 'boolean':
2503 return literalBooleanMembers;
2504 case 'number':
2505 return literalNumberMembers;
2506 case 'string':
2507 return literalStringMembers;
2508 default:
2509 return Object.create(null);
2510 }
2511}
2512function hasMemberEffectWhenCalled(members, memberName, parentIncluded, callOptions, options) {
2513 if (typeof memberName !== 'string' || !members[memberName])
2514 return true;
2515 if (members[memberName].mutatesSelf && parentIncluded)
2516 return true;
2517 if (!members[memberName].callsArgs)
2518 return false;
2519 for (const argIndex of members[memberName].callsArgs) {
2520 if (callOptions.args[argIndex] &&
2521 callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, CallOptions.create({
2522 args: [],
2523 callIdentifier: {},
2524 withNew: false
2525 }), options.getHasEffectsWhenCalledOptions()))
2526 return true;
2527 }
2528 return false;
2529}
2530function getMemberReturnExpressionWhenCalled(members, memberName) {
2531 if (typeof memberName !== 'string' || !members[memberName])
2532 return UNKNOWN_EXPRESSION;
2533 return members[memberName].returnsPrimitive !== null
2534 ? members[memberName].returnsPrimitive
2535 : new members[memberName].returns();
2536}
2537
2538class Variable {
2539 constructor(name) {
2540 this.alwaysRendered = false;
2541 this.exportName = null;
2542 this.included = false;
2543 this.isId = false;
2544 this.isReassigned = false;
2545 this.renderBaseName = null;
2546 this.renderName = null;
2547 this.safeExportName = null;
2548 this.name = name;
2549 }
2550 /**
2551 * Binds identifiers that reference this variable to this variable.
2552 * Necessary to be able to change variable names.
2553 */
2554 addReference(_identifier) { }
2555 deoptimizePath(_path) { }
2556 getBaseVariableName() {
2557 return this.renderBaseName || this.renderName || this.name;
2558 }
2559 getLiteralValueAtPath(_path, _recursionTracker, _origin) {
2560 return UNKNOWN_VALUE;
2561 }
2562 getName() {
2563 const name = this.renderName || this.name;
2564 return this.renderBaseName ? `${this.renderBaseName}.${name}` : name;
2565 }
2566 getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
2567 return UNKNOWN_EXPRESSION;
2568 }
2569 hasEffectsWhenAccessedAtPath(path, _options) {
2570 return path.length > 0;
2571 }
2572 hasEffectsWhenAssignedAtPath(_path, _options) {
2573 return true;
2574 }
2575 hasEffectsWhenCalledAtPath(_path, _callOptions, _options) {
2576 return true;
2577 }
2578 /**
2579 * Marks this variable as being part of the bundle, which is usually the case when one of
2580 * its identifiers becomes part of the bundle. Returns true if it has not been included
2581 * previously.
2582 * Once a variable is included, it should take care all its declarations are included.
2583 */
2584 include() {
2585 this.included = true;
2586 }
2587 includeCallArguments(args) {
2588 for (const arg of args) {
2589 arg.include(false);
2590 }
2591 }
2592 markCalledFromTryStatement() { }
2593 setRenderNames(baseName, name) {
2594 this.renderBaseName = baseName;
2595 this.renderName = name;
2596 }
2597 setSafeName(name) {
2598 this.renderName = name;
2599 }
2600 toString() {
2601 return this.name;
2602 }
2603}
2604
2605class ExternalVariable extends Variable {
2606 constructor(module, name) {
2607 super(name);
2608 this.module = module;
2609 this.isNamespace = name === '*';
2610 this.referenced = false;
2611 }
2612 addReference(identifier) {
2613 this.referenced = true;
2614 if (this.name === 'default' || this.name === '*') {
2615 this.module.suggestName(identifier.name);
2616 }
2617 }
2618 include() {
2619 if (!this.included) {
2620 this.included = true;
2621 this.module.used = true;
2622 }
2623 }
2624}
2625
2626const 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(' ');
2627const 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(' ');
2628const blacklisted = Object.create(null);
2629reservedWords.concat(builtins).forEach(word => (blacklisted[word] = true));
2630const illegalCharacters = /[^$_a-zA-Z0-9]/g;
2631const startsWithDigit = (str) => /\d/.test(str[0]);
2632function isLegal(str) {
2633 if (startsWithDigit(str) || blacklisted[str]) {
2634 return false;
2635 }
2636 return !illegalCharacters.test(str);
2637}
2638function makeLegal(str) {
2639 str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
2640 if (startsWithDigit(str) || blacklisted[str])
2641 str = `_${str}`;
2642 return str || '_';
2643}
2644
2645class ExternalModule {
2646 constructor(graph, id, moduleSideEffects) {
2647 this.exportsNames = false;
2648 this.exportsNamespace = false;
2649 this.mostCommonSuggestion = 0;
2650 this.reexported = false;
2651 this.renderPath = undefined;
2652 this.renormalizeRenderPath = false;
2653 this.used = false;
2654 this.graph = graph;
2655 this.id = id;
2656 this.execIndex = Infinity;
2657 this.moduleSideEffects = moduleSideEffects;
2658 const parts = id.split(/[\\/]/);
2659 this.variableName = makeLegal(parts.pop());
2660 this.nameSuggestions = Object.create(null);
2661 this.declarations = Object.create(null);
2662 this.exportedVariables = new Map();
2663 }
2664 getVariableForExportName(name, _isExportAllSearch) {
2665 if (name === '*') {
2666 this.exportsNamespace = true;
2667 }
2668 else if (name !== 'default') {
2669 this.exportsNames = true;
2670 }
2671 let declaration = this.declarations[name];
2672 if (declaration)
2673 return declaration;
2674 this.declarations[name] = declaration = new ExternalVariable(this, name);
2675 this.exportedVariables.set(declaration, name);
2676 return declaration;
2677 }
2678 setRenderPath(options, inputBase) {
2679 this.renderPath = '';
2680 if (options.paths) {
2681 this.renderPath =
2682 typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
2683 }
2684 if (!this.renderPath) {
2685 if (!index.isAbsolute(this.id)) {
2686 this.renderPath = this.id;
2687 }
2688 else {
2689 this.renderPath = index.normalize(path.relative(inputBase, this.id));
2690 this.renormalizeRenderPath = true;
2691 }
2692 }
2693 return this.renderPath;
2694 }
2695 suggestName(name) {
2696 if (!this.nameSuggestions[name])
2697 this.nameSuggestions[name] = 0;
2698 this.nameSuggestions[name] += 1;
2699 if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
2700 this.mostCommonSuggestion = this.nameSuggestions[name];
2701 this.variableName = name;
2702 }
2703 }
2704 warnUnusedImports() {
2705 const unused = Object.keys(this.declarations).filter(name => {
2706 if (name === '*')
2707 return false;
2708 const declaration = this.declarations[name];
2709 return !declaration.included && !this.reexported && !declaration.referenced;
2710 });
2711 if (unused.length === 0)
2712 return;
2713 const names = unused.length === 1
2714 ? `'${unused[0]}' is`
2715 : `${unused
2716 .slice(0, -1)
2717 .map(name => `'${name}'`)
2718 .join(', ')} and '${unused.slice(-1)}' are`;
2719 this.graph.warn({
2720 code: 'UNUSED_EXTERNAL_IMPORT',
2721 message: `${names} imported from external module '${this.id}' but never used`,
2722 names: unused,
2723 source: this.id
2724 });
2725 }
2726}
2727
2728function markModuleAndImpureDependenciesAsExecuted(baseModule) {
2729 baseModule.isExecuted = true;
2730 const modules = [baseModule];
2731 const visitedModules = new Set();
2732 for (const module of modules) {
2733 for (const dependency of module.dependencies) {
2734 if (!(dependency instanceof ExternalModule) &&
2735 !dependency.isExecuted &&
2736 dependency.moduleSideEffects &&
2737 !visitedModules.has(dependency.id)) {
2738 dependency.isExecuted = true;
2739 visitedModules.add(dependency.id);
2740 modules.push(dependency);
2741 }
2742 }
2743 }
2744}
2745
2746// To avoid infinite recursions
2747const MAX_PATH_DEPTH = 7;
2748class LocalVariable extends Variable {
2749 constructor(name, declarator, init, context) {
2750 super(name);
2751 this.additionalInitializers = null;
2752 this.calledFromTryStatement = false;
2753 this.expressionsToBeDeoptimized = [];
2754 this.declarations = declarator ? [declarator] : [];
2755 this.init = init;
2756 this.deoptimizationTracker = context.deoptimizationTracker;
2757 this.module = context.module;
2758 }
2759 addDeclaration(identifier, init) {
2760 this.declarations.push(identifier);
2761 if (this.additionalInitializers === null) {
2762 this.additionalInitializers = this.init === null ? [] : [this.init];
2763 this.init = UNKNOWN_EXPRESSION;
2764 this.isReassigned = true;
2765 }
2766 if (init !== null) {
2767 this.additionalInitializers.push(init);
2768 }
2769 }
2770 consolidateInitializers() {
2771 if (this.additionalInitializers !== null) {
2772 for (const initializer of this.additionalInitializers) {
2773 initializer.deoptimizePath(UNKNOWN_PATH);
2774 }
2775 this.additionalInitializers = null;
2776 }
2777 }
2778 deoptimizePath(path) {
2779 if (path.length > MAX_PATH_DEPTH)
2780 return;
2781 if (!(this.isReassigned || this.deoptimizationTracker.track(this, path))) {
2782 if (path.length === 0) {
2783 if (!this.isReassigned) {
2784 this.isReassigned = true;
2785 for (const expression of this.expressionsToBeDeoptimized) {
2786 expression.deoptimizeCache();
2787 }
2788 if (this.init) {
2789 this.init.deoptimizePath(UNKNOWN_PATH);
2790 }
2791 }
2792 }
2793 else if (this.init) {
2794 this.init.deoptimizePath(path);
2795 }
2796 }
2797 }
2798 getLiteralValueAtPath(path, recursionTracker, origin) {
2799 if (this.isReassigned ||
2800 !this.init ||
2801 path.length > MAX_PATH_DEPTH ||
2802 recursionTracker.isTracked(this.init, path)) {
2803 return UNKNOWN_VALUE;
2804 }
2805 this.expressionsToBeDeoptimized.push(origin);
2806 return this.init.getLiteralValueAtPath(path, recursionTracker.track(this.init, path), origin);
2807 }
2808 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
2809 if (this.isReassigned ||
2810 !this.init ||
2811 path.length > MAX_PATH_DEPTH ||
2812 recursionTracker.isTracked(this.init, path)) {
2813 return UNKNOWN_EXPRESSION;
2814 }
2815 this.expressionsToBeDeoptimized.push(origin);
2816 return this.init.getReturnExpressionWhenCalledAtPath(path, recursionTracker.track(this.init, path), origin);
2817 }
2818 hasEffectsWhenAccessedAtPath(path, options) {
2819 if (path.length === 0)
2820 return false;
2821 return (this.isReassigned ||
2822 path.length > MAX_PATH_DEPTH ||
2823 (this.init &&
2824 !options.hasNodeBeenAccessedAtPath(path, this.init) &&
2825 this.init.hasEffectsWhenAccessedAtPath(path, options.addAccessedNodeAtPath(path, this.init))));
2826 }
2827 hasEffectsWhenAssignedAtPath(path, options) {
2828 if (this.included || path.length > MAX_PATH_DEPTH)
2829 return true;
2830 if (path.length === 0)
2831 return false;
2832 return (this.isReassigned ||
2833 (this.init &&
2834 !options.hasNodeBeenAssignedAtPath(path, this.init) &&
2835 this.init.hasEffectsWhenAssignedAtPath(path, options.addAssignedNodeAtPath(path, this.init))));
2836 }
2837 hasEffectsWhenCalledAtPath(path, callOptions, options) {
2838 if (path.length > MAX_PATH_DEPTH)
2839 return true;
2840 return (this.isReassigned ||
2841 (this.init &&
2842 !options.hasNodeBeenCalledAtPathWithOptions(path, this.init, callOptions) &&
2843 this.init.hasEffectsWhenCalledAtPath(path, callOptions, options.addCalledNodeAtPathWithOptions(path, this.init, callOptions))));
2844 }
2845 include() {
2846 if (!this.included) {
2847 this.included = true;
2848 if (!this.module.isExecuted) {
2849 markModuleAndImpureDependenciesAsExecuted(this.module);
2850 }
2851 for (const declaration of this.declarations) {
2852 // If node is a default export, it can save a tree-shaking run to include the full declaration now
2853 if (!declaration.included)
2854 declaration.include(false);
2855 let node = declaration.parent;
2856 while (!node.included) {
2857 // We do not want to properly include parents in case they are part of a dead branch
2858 // in which case .include() might pull in more dead code
2859 node.included = true;
2860 if (node.type === Program)
2861 break;
2862 node = node.parent;
2863 }
2864 }
2865 }
2866 }
2867 includeCallArguments(args) {
2868 if (this.isReassigned) {
2869 for (const arg of args) {
2870 arg.include(false);
2871 }
2872 }
2873 else if (this.init) {
2874 this.init.includeCallArguments(args);
2875 }
2876 }
2877 markCalledFromTryStatement() {
2878 this.calledFromTryStatement = true;
2879 }
2880}
2881
2882class Scope {
2883 constructor() {
2884 this.children = [];
2885 this.variables = new Map();
2886 }
2887 addDeclaration(identifier, context, init = null, _isHoisted) {
2888 const name = identifier.name;
2889 let variable = this.variables.get(name);
2890 if (variable) {
2891 variable.addDeclaration(identifier, init);
2892 }
2893 else {
2894 variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
2895 this.variables.set(name, variable);
2896 }
2897 return variable;
2898 }
2899 contains(name) {
2900 return this.variables.has(name);
2901 }
2902 findVariable(_name) {
2903 throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
2904 }
2905}
2906
2907class ChildScope extends Scope {
2908 constructor(parent) {
2909 super();
2910 this.accessedOutsideVariables = new Map();
2911 this.parent = parent;
2912 parent.children.push(this);
2913 }
2914 addAccessedGlobalsByFormat(globalsByFormat) {
2915 let accessedGlobalVariablesByFormat = this.accessedGlobalVariablesByFormat;
2916 if (!accessedGlobalVariablesByFormat) {
2917 accessedGlobalVariablesByFormat = this.accessedGlobalVariablesByFormat = new Map();
2918 }
2919 for (const format of Object.keys(globalsByFormat)) {
2920 let accessedGlobalVariables = accessedGlobalVariablesByFormat.get(format);
2921 if (!accessedGlobalVariables) {
2922 accessedGlobalVariables = new Set();
2923 accessedGlobalVariablesByFormat.set(format, accessedGlobalVariables);
2924 }
2925 for (const name of globalsByFormat[format]) {
2926 accessedGlobalVariables.add(name);
2927 }
2928 }
2929 if (this.parent instanceof ChildScope) {
2930 this.parent.addAccessedGlobalsByFormat(globalsByFormat);
2931 }
2932 }
2933 addNamespaceMemberAccess(name, variable) {
2934 this.accessedOutsideVariables.set(name, variable);
2935 if (this.parent instanceof ChildScope) {
2936 this.parent.addNamespaceMemberAccess(name, variable);
2937 }
2938 }
2939 addReturnExpression(expression) {
2940 this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
2941 }
2942 contains(name) {
2943 return this.variables.has(name) || this.parent.contains(name);
2944 }
2945 deconflict(format) {
2946 const usedNames = new Set();
2947 for (const variable of this.accessedOutsideVariables.values()) {
2948 if (variable.included) {
2949 usedNames.add(variable.getBaseVariableName());
2950 if (variable.exportName && format === 'system') {
2951 usedNames.add('exports');
2952 }
2953 }
2954 }
2955 const accessedGlobalVariables = this.accessedGlobalVariablesByFormat && this.accessedGlobalVariablesByFormat.get(format);
2956 if (accessedGlobalVariables) {
2957 for (const name of accessedGlobalVariables) {
2958 usedNames.add(name);
2959 }
2960 }
2961 for (const [name, variable] of this.variables) {
2962 if (variable.included || variable.alwaysRendered) {
2963 variable.setSafeName(getSafeName(name, usedNames));
2964 }
2965 }
2966 for (const scope of this.children) {
2967 scope.deconflict(format);
2968 }
2969 }
2970 findLexicalBoundary() {
2971 return this.parent instanceof ChildScope ? this.parent.findLexicalBoundary() : this;
2972 }
2973 findVariable(name) {
2974 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
2975 if (knownVariable) {
2976 return knownVariable;
2977 }
2978 const variable = this.parent.findVariable(name);
2979 this.accessedOutsideVariables.set(name, variable);
2980 return variable;
2981 }
2982}
2983
2984function getLocator$1(source, options) {
2985 if (options === void 0) {
2986 options = {};
2987 }
2988 var offsetLine = options.offsetLine || 0;
2989 var offsetColumn = options.offsetColumn || 0;
2990 var originalLines = source.split('\n');
2991 var start = 0;
2992 var lineRanges = originalLines.map(function (line, i) {
2993 var end = start + line.length + 1;
2994 var range = { start: start, end: end, line: i };
2995 start = end;
2996 return range;
2997 });
2998 var i = 0;
2999 function rangeContains(range, index) {
3000 return range.start <= index && index < range.end;
3001 }
3002 function getLocation(range, index) {
3003 return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
3004 }
3005 function locate(search, startIndex) {
3006 if (typeof search === 'string') {
3007 search = source.indexOf(search, startIndex || 0);
3008 }
3009 var range = lineRanges[i];
3010 var d = search >= range.end ? 1 : -1;
3011 while (range) {
3012 if (rangeContains(range, search))
3013 return getLocation(range, search);
3014 i += d;
3015 range = lineRanges[i];
3016 }
3017 }
3018 return locate;
3019}
3020function locate(source, search, options) {
3021 if (typeof options === 'number') {
3022 throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
3023 }
3024 return getLocator$1(source, options)(search, options && options.startIndex);
3025}
3026
3027/**
3028 * Copyright (c) 2014-present, Facebook, Inc.
3029 *
3030 * This source code is licensed under the MIT license found in the
3031 * LICENSE file in the root directory of this source tree.
3032 */
3033// Used for setting prototype methods that IE8 chokes on.
3034var DELETE = 'delete';
3035// Constants describing the size of trie nodes.
3036var SHIFT = 5; // Resulted in best performance after ______?
3037var SIZE = 1 << SHIFT;
3038var MASK = SIZE - 1;
3039// A consistent shared value representing "not set" which equals nothing other
3040// than itself, and nothing that could be provided externally.
3041var NOT_SET = {};
3042// Boolean references, Rough equivalent of `bool &`.
3043function MakeRef() {
3044 return { value: false };
3045}
3046function SetRef(ref) {
3047 if (ref) {
3048 ref.value = true;
3049 }
3050}
3051// A function which returns a value representing an "owner" for transient writes
3052// to tries. The return value will only ever equal itself, and will not equal
3053// the return of any subsequent call of this function.
3054function OwnerID() { }
3055function ensureSize(iter) {
3056 if (iter.size === undefined) {
3057 iter.size = iter.__iterate(returnTrue);
3058 }
3059 return iter.size;
3060}
3061function wrapIndex(iter, index) {
3062 // This implements "is array index" which the ECMAString spec defines as:
3063 //
3064 // A String property name P is an array index if and only if
3065 // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal
3066 // to 2^32−1.
3067 //
3068 // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects
3069 if (typeof index !== 'number') {
3070 var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32
3071 if ('' + uint32Index !== index || uint32Index === 4294967295) {
3072 return NaN;
3073 }
3074 index = uint32Index;
3075 }
3076 return index < 0 ? ensureSize(iter) + index : index;
3077}
3078function returnTrue() {
3079 return true;
3080}
3081function wholeSlice(begin, end, size) {
3082 return (((begin === 0 && !isNeg(begin)) ||
3083 (size !== undefined && begin <= -size)) &&
3084 (end === undefined || (size !== undefined && end >= size)));
3085}
3086function resolveBegin(begin, size) {
3087 return resolveIndex(begin, size, 0);
3088}
3089function resolveEnd(end, size) {
3090 return resolveIndex(end, size, size);
3091}
3092function resolveIndex(index, size, defaultIndex) {
3093 // Sanitize indices using this shorthand for ToInt32(argument)
3094 // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
3095 return index === undefined
3096 ? defaultIndex
3097 : isNeg(index)
3098 ? size === Infinity
3099 ? size
3100 : Math.max(0, size + index) | 0
3101 : size === undefined || size === index
3102 ? index
3103 : Math.min(size, index) | 0;
3104}
3105function isNeg(value) {
3106 // Account for -0 which is negative, but not less than 0.
3107 return value < 0 || (value === 0 && 1 / value === -Infinity);
3108}
3109// Note: value is unchanged to not break immutable-devtools.
3110var IS_COLLECTION_SYMBOL = '@@__IMMUTABLE_ITERABLE__@@';
3111function isCollection(maybeCollection) {
3112 return Boolean(maybeCollection && maybeCollection[IS_COLLECTION_SYMBOL]);
3113}
3114var IS_KEYED_SYMBOL = '@@__IMMUTABLE_KEYED__@@';
3115function isKeyed(maybeKeyed) {
3116 return Boolean(maybeKeyed && maybeKeyed[IS_KEYED_SYMBOL]);
3117}
3118var IS_INDEXED_SYMBOL = '@@__IMMUTABLE_INDEXED__@@';
3119function isIndexed(maybeIndexed) {
3120 return Boolean(maybeIndexed && maybeIndexed[IS_INDEXED_SYMBOL]);
3121}
3122function isAssociative(maybeAssociative) {
3123 return isKeyed(maybeAssociative) || isIndexed(maybeAssociative);
3124}
3125var Collection = function Collection(value) {
3126 return isCollection(value) ? value : Seq(value);
3127};
3128var KeyedCollection = /*@__PURE__*/ (function (Collection) {
3129 function KeyedCollection(value) {
3130 return isKeyed(value) ? value : KeyedSeq(value);
3131 }
3132 if (Collection)
3133 KeyedCollection.__proto__ = Collection;
3134 KeyedCollection.prototype = Object.create(Collection && Collection.prototype);
3135 KeyedCollection.prototype.constructor = KeyedCollection;
3136 return KeyedCollection;
3137}(Collection));
3138var IndexedCollection = /*@__PURE__*/ (function (Collection) {
3139 function IndexedCollection(value) {
3140 return isIndexed(value) ? value : IndexedSeq(value);
3141 }
3142 if (Collection)
3143 IndexedCollection.__proto__ = Collection;
3144 IndexedCollection.prototype = Object.create(Collection && Collection.prototype);
3145 IndexedCollection.prototype.constructor = IndexedCollection;
3146 return IndexedCollection;
3147}(Collection));
3148var SetCollection = /*@__PURE__*/ (function (Collection) {
3149 function SetCollection(value) {
3150 return isCollection(value) && !isAssociative(value) ? value : SetSeq(value);
3151 }
3152 if (Collection)
3153 SetCollection.__proto__ = Collection;
3154 SetCollection.prototype = Object.create(Collection && Collection.prototype);
3155 SetCollection.prototype.constructor = SetCollection;
3156 return SetCollection;
3157}(Collection));
3158Collection.Keyed = KeyedCollection;
3159Collection.Indexed = IndexedCollection;
3160Collection.Set = SetCollection;
3161var IS_SEQ_SYMBOL = '@@__IMMUTABLE_SEQ__@@';
3162function isSeq(maybeSeq) {
3163 return Boolean(maybeSeq && maybeSeq[IS_SEQ_SYMBOL]);
3164}
3165var IS_RECORD_SYMBOL = '@@__IMMUTABLE_RECORD__@@';
3166function isRecord(maybeRecord) {
3167 return Boolean(maybeRecord && maybeRecord[IS_RECORD_SYMBOL]);
3168}
3169function isImmutable(maybeImmutable) {
3170 return isCollection(maybeImmutable) || isRecord(maybeImmutable);
3171}
3172var IS_ORDERED_SYMBOL = '@@__IMMUTABLE_ORDERED__@@';
3173function isOrdered(maybeOrdered) {
3174 return Boolean(maybeOrdered && maybeOrdered[IS_ORDERED_SYMBOL]);
3175}
3176var ITERATE_KEYS = 0;
3177var ITERATE_VALUES = 1;
3178var ITERATE_ENTRIES = 2;
3179var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
3180var FAUX_ITERATOR_SYMBOL = '@@iterator';
3181var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL;
3182var Iterator = function Iterator(next) {
3183 this.next = next;
3184};
3185Iterator.prototype.toString = function toString() {
3186 return '[Iterator]';
3187};
3188Iterator.KEYS = ITERATE_KEYS;
3189Iterator.VALUES = ITERATE_VALUES;
3190Iterator.ENTRIES = ITERATE_ENTRIES;
3191Iterator.prototype.inspect = Iterator.prototype.toSource = function () {
3192 return this.toString();
3193};
3194Iterator.prototype[ITERATOR_SYMBOL] = function () {
3195 return this;
3196};
3197function iteratorValue(type, k, v, iteratorResult) {
3198 var value = type === 0 ? k : type === 1 ? v : [k, v];
3199 iteratorResult
3200 ? (iteratorResult.value = value)
3201 : (iteratorResult = {
3202 value: value,
3203 done: false,
3204 });
3205 return iteratorResult;
3206}
3207function iteratorDone() {
3208 return { value: undefined, done: true };
3209}
3210function hasIterator(maybeIterable) {
3211 return !!getIteratorFn(maybeIterable);
3212}
3213function isIterator(maybeIterator) {
3214 return maybeIterator && typeof maybeIterator.next === 'function';
3215}
3216function getIterator(iterable) {
3217 var iteratorFn = getIteratorFn(iterable);
3218 return iteratorFn && iteratorFn.call(iterable);
3219}
3220function getIteratorFn(iterable) {
3221 var iteratorFn = iterable &&
3222 ((REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) ||
3223 iterable[FAUX_ITERATOR_SYMBOL]);
3224 if (typeof iteratorFn === 'function') {
3225 return iteratorFn;
3226 }
3227}
3228var hasOwnProperty = Object.prototype.hasOwnProperty;
3229function isArrayLike(value) {
3230 if (Array.isArray(value) || typeof value === 'string') {
3231 return true;
3232 }
3233 return (value &&
3234 typeof value === 'object' &&
3235 Number.isInteger(value.length) &&
3236 value.length >= 0 &&
3237 (value.length === 0
3238 ? // Only {length: 0} is considered Array-like.
3239 Object.keys(value).length === 1
3240 : // An object is only Array-like if it has a property where the last value
3241 // in the array-like may be found (which could be undefined).
3242 value.hasOwnProperty(value.length - 1)));
3243}
3244var Seq = /*@__PURE__*/ (function (Collection$$1) {
3245 function Seq(value) {
3246 return value === null || value === undefined
3247 ? emptySequence()
3248 : isImmutable(value)
3249 ? value.toSeq()
3250 : seqFromValue(value);
3251 }
3252 if (Collection$$1)
3253 Seq.__proto__ = Collection$$1;
3254 Seq.prototype = Object.create(Collection$$1 && Collection$$1.prototype);
3255 Seq.prototype.constructor = Seq;
3256 Seq.prototype.toSeq = function toSeq() {
3257 return this;
3258 };
3259 Seq.prototype.toString = function toString() {
3260 return this.__toString('Seq {', '}');
3261 };
3262 Seq.prototype.cacheResult = function cacheResult() {
3263 if (!this._cache && this.__iterateUncached) {
3264 this._cache = this.entrySeq().toArray();
3265 this.size = this._cache.length;
3266 }
3267 return this;
3268 };
3269 // abstract __iterateUncached(fn, reverse)
3270 Seq.prototype.__iterate = function __iterate(fn, reverse) {
3271 var cache = this._cache;
3272 if (cache) {
3273 var size = cache.length;
3274 var i = 0;
3275 while (i !== size) {
3276 var entry = cache[reverse ? size - ++i : i++];
3277 if (fn(entry[1], entry[0], this) === false) {
3278 break;
3279 }
3280 }
3281 return i;
3282 }
3283 return this.__iterateUncached(fn, reverse);
3284 };
3285 // abstract __iteratorUncached(type, reverse)
3286 Seq.prototype.__iterator = function __iterator(type, reverse) {
3287 var cache = this._cache;
3288 if (cache) {
3289 var size = cache.length;
3290 var i = 0;
3291 return new Iterator(function () {
3292 if (i === size) {
3293 return iteratorDone();
3294 }
3295 var entry = cache[reverse ? size - ++i : i++];
3296 return iteratorValue(type, entry[0], entry[1]);
3297 });
3298 }
3299 return this.__iteratorUncached(type, reverse);
3300 };
3301 return Seq;
3302}(Collection));
3303var KeyedSeq = /*@__PURE__*/ (function (Seq) {
3304 function KeyedSeq(value) {
3305 return value === null || value === undefined
3306 ? emptySequence().toKeyedSeq()
3307 : isCollection(value)
3308 ? isKeyed(value)
3309 ? value.toSeq()
3310 : value.fromEntrySeq()
3311 : isRecord(value)
3312 ? value.toSeq()
3313 : keyedSeqFromValue(value);
3314 }
3315 if (Seq)
3316 KeyedSeq.__proto__ = Seq;
3317 KeyedSeq.prototype = Object.create(Seq && Seq.prototype);
3318 KeyedSeq.prototype.constructor = KeyedSeq;
3319 KeyedSeq.prototype.toKeyedSeq = function toKeyedSeq() {
3320 return this;
3321 };
3322 return KeyedSeq;
3323}(Seq));
3324var IndexedSeq = /*@__PURE__*/ (function (Seq) {
3325 function IndexedSeq(value) {
3326 return value === null || value === undefined
3327 ? emptySequence()
3328 : isCollection(value)
3329 ? isKeyed(value)
3330 ? value.entrySeq()
3331 : value.toIndexedSeq()
3332 : isRecord(value)
3333 ? value.toSeq().entrySeq()
3334 : indexedSeqFromValue(value);
3335 }
3336 if (Seq)
3337 IndexedSeq.__proto__ = Seq;
3338 IndexedSeq.prototype = Object.create(Seq && Seq.prototype);
3339 IndexedSeq.prototype.constructor = IndexedSeq;
3340 IndexedSeq.of = function of( /*...values*/) {
3341 return IndexedSeq(arguments);
3342 };
3343 IndexedSeq.prototype.toIndexedSeq = function toIndexedSeq() {
3344 return this;
3345 };
3346 IndexedSeq.prototype.toString = function toString() {
3347 return this.__toString('Seq [', ']');
3348 };
3349 return IndexedSeq;
3350}(Seq));
3351var SetSeq = /*@__PURE__*/ (function (Seq) {
3352 function SetSeq(value) {
3353 return (isCollection(value) && !isAssociative(value)
3354 ? value
3355 : IndexedSeq(value)).toSetSeq();
3356 }
3357 if (Seq)
3358 SetSeq.__proto__ = Seq;
3359 SetSeq.prototype = Object.create(Seq && Seq.prototype);
3360 SetSeq.prototype.constructor = SetSeq;
3361 SetSeq.of = function of( /*...values*/) {
3362 return SetSeq(arguments);
3363 };
3364 SetSeq.prototype.toSetSeq = function toSetSeq() {
3365 return this;
3366 };
3367 return SetSeq;
3368}(Seq));
3369Seq.isSeq = isSeq;
3370Seq.Keyed = KeyedSeq;
3371Seq.Set = SetSeq;
3372Seq.Indexed = IndexedSeq;
3373Seq.prototype[IS_SEQ_SYMBOL] = true;
3374// #pragma Root Sequences
3375var ArraySeq = /*@__PURE__*/ (function (IndexedSeq) {
3376 function ArraySeq(array) {
3377 this._array = array;
3378 this.size = array.length;
3379 }
3380 if (IndexedSeq)
3381 ArraySeq.__proto__ = IndexedSeq;
3382 ArraySeq.prototype = Object.create(IndexedSeq && IndexedSeq.prototype);
3383 ArraySeq.prototype.constructor = ArraySeq;
3384 ArraySeq.prototype.get = function get(index, notSetValue) {
3385 return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue;
3386 };
3387 ArraySeq.prototype.__iterate = function __iterate(fn, reverse) {
3388 var array = this._array;
3389 var size = array.length;
3390 var i = 0;
3391 while (i !== size) {
3392 var ii = reverse ? size - ++i : i++;
3393 if (fn(array[ii], ii, this) === false) {
3394 break;
3395 }
3396 }
3397 return i;
3398 };
3399 ArraySeq.prototype.__iterator = function __iterator(type, reverse) {
3400 var array = this._array;
3401 var size = array.length;
3402 var i = 0;
3403 return new Iterator(function () {
3404 if (i === size) {
3405 return iteratorDone();
3406 }
3407 var ii = reverse ? size - ++i : i++;
3408 return iteratorValue(type, ii, array[ii]);
3409 });
3410 };
3411 return ArraySeq;
3412}(IndexedSeq));
3413var ObjectSeq = /*@__PURE__*/ (function (KeyedSeq) {
3414 function ObjectSeq(object) {
3415 var keys = Object.keys(object);
3416 this._object = object;
3417 this._keys = keys;
3418 this.size = keys.length;
3419 }
3420 if (KeyedSeq)
3421 ObjectSeq.__proto__ = KeyedSeq;
3422 ObjectSeq.prototype = Object.create(KeyedSeq && KeyedSeq.prototype);
3423 ObjectSeq.prototype.constructor = ObjectSeq;
3424 ObjectSeq.prototype.get = function get(key, notSetValue) {
3425 if (notSetValue !== undefined && !this.has(key)) {
3426 return notSetValue;
3427 }
3428 return this._object[key];
3429 };
3430 ObjectSeq.prototype.has = function has(key) {
3431 return hasOwnProperty.call(this._object, key);
3432 };
3433 ObjectSeq.prototype.__iterate = function __iterate(fn, reverse) {
3434 var object = this._object;
3435 var keys = this._keys;
3436 var size = keys.length;
3437 var i = 0;
3438 while (i !== size) {
3439 var key = keys[reverse ? size - ++i : i++];
3440 if (fn(object[key], key, this) === false) {
3441 break;
3442 }
3443 }
3444 return i;
3445 };
3446 ObjectSeq.prototype.__iterator = function __iterator(type, reverse) {
3447 var object = this._object;
3448 var keys = this._keys;
3449 var size = keys.length;
3450 var i = 0;
3451 return new Iterator(function () {
3452 if (i === size) {
3453 return iteratorDone();
3454 }
3455 var key = keys[reverse ? size - ++i : i++];
3456 return iteratorValue(type, key, object[key]);
3457 });
3458 };
3459 return ObjectSeq;
3460}(KeyedSeq));
3461ObjectSeq.prototype[IS_ORDERED_SYMBOL] = true;
3462var CollectionSeq = /*@__PURE__*/ (function (IndexedSeq) {
3463 function CollectionSeq(collection) {
3464 this._collection = collection;
3465 this.size = collection.length || collection.size;
3466 }
3467 if (IndexedSeq)
3468 CollectionSeq.__proto__ = IndexedSeq;
3469 CollectionSeq.prototype = Object.create(IndexedSeq && IndexedSeq.prototype);
3470 CollectionSeq.prototype.constructor = CollectionSeq;
3471 CollectionSeq.prototype.__iterateUncached = function __iterateUncached(fn, reverse) {
3472 if (reverse) {
3473 return this.cacheResult().__iterate(fn, reverse);
3474 }
3475 var collection = this._collection;
3476 var iterator = getIterator(collection);
3477 var iterations = 0;
3478 if (isIterator(iterator)) {
3479 var step;
3480 while (!(step = iterator.next()).done) {
3481 if (fn(step.value, iterations++, this) === false) {
3482 break;
3483 }
3484 }
3485 }
3486 return iterations;
3487 };
3488 CollectionSeq.prototype.__iteratorUncached = function __iteratorUncached(type, reverse) {
3489 if (reverse) {
3490 return this.cacheResult().__iterator(type, reverse);
3491 }
3492 var collection = this._collection;
3493 var iterator = getIterator(collection);
3494 if (!isIterator(iterator)) {
3495 return new Iterator(iteratorDone);
3496 }
3497 var iterations = 0;
3498 return new Iterator(function () {
3499 var step = iterator.next();
3500 return step.done ? step : iteratorValue(type, iterations++, step.value);
3501 });
3502 };
3503 return CollectionSeq;
3504}(IndexedSeq));
3505// # pragma Helper functions
3506var EMPTY_SEQ;
3507function emptySequence() {
3508 return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([]));
3509}
3510function keyedSeqFromValue(value) {
3511 var seq = Array.isArray(value)
3512 ? new ArraySeq(value)
3513 : hasIterator(value)
3514 ? new CollectionSeq(value)
3515 : undefined;
3516 if (seq) {
3517 return seq.fromEntrySeq();
3518 }
3519 if (typeof value === 'object') {
3520 return new ObjectSeq(value);
3521 }
3522 throw new TypeError('Expected Array or collection object of [k, v] entries, or keyed object: ' +
3523 value);
3524}
3525function indexedSeqFromValue(value) {
3526 var seq = maybeIndexedSeqFromValue(value);
3527 if (seq) {
3528 return seq;
3529 }
3530 throw new TypeError('Expected Array or collection object of values: ' + value);
3531}
3532function seqFromValue(value) {
3533 var seq = maybeIndexedSeqFromValue(value);
3534 if (seq) {
3535 return seq;
3536 }
3537 if (typeof value === 'object') {
3538 return new ObjectSeq(value);
3539 }
3540 throw new TypeError('Expected Array or collection object of values, or keyed object: ' + value);
3541}
3542function maybeIndexedSeqFromValue(value) {
3543 return isArrayLike(value)
3544 ? new ArraySeq(value)
3545 : hasIterator(value)
3546 ? new CollectionSeq(value)
3547 : undefined;
3548}
3549var IS_MAP_SYMBOL = '@@__IMMUTABLE_MAP__@@';
3550function isMap(maybeMap) {
3551 return Boolean(maybeMap && maybeMap[IS_MAP_SYMBOL]);
3552}
3553function isOrderedMap(maybeOrderedMap) {
3554 return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap);
3555}
3556function isValueObject(maybeValue) {
3557 return Boolean(maybeValue &&
3558 typeof maybeValue.equals === 'function' &&
3559 typeof maybeValue.hashCode === 'function');
3560}
3561/**
3562 * An extension of the "same-value" algorithm as [described for use by ES6 Map
3563 * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality)
3564 *
3565 * NaN is considered the same as NaN, however -0 and 0 are considered the same
3566 * value, which is different from the algorithm described by
3567 * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
3568 *
3569 * This is extended further to allow Objects to describe the values they
3570 * represent, by way of `valueOf` or `equals` (and `hashCode`).
3571 *
3572 * Note: because of this extension, the key equality of Immutable.Map and the
3573 * value equality of Immutable.Set will differ from ES6 Map and Set.
3574 *
3575 * ### Defining custom values
3576 *
3577 * The easiest way to describe the value an object represents is by implementing
3578 * `valueOf`. For example, `Date` represents a value by returning a unix
3579 * timestamp for `valueOf`:
3580 *
3581 * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ...
3582 * var date2 = new Date(1234567890000);
3583 * date1.valueOf(); // 1234567890000
3584 * assert( date1 !== date2 );
3585 * assert( Immutable.is( date1, date2 ) );
3586 *
3587 * Note: overriding `valueOf` may have other implications if you use this object
3588 * where JavaScript expects a primitive, such as implicit string coercion.
3589 *
3590 * For more complex types, especially collections, implementing `valueOf` may
3591 * not be performant. An alternative is to implement `equals` and `hashCode`.
3592 *
3593 * `equals` takes another object, presumably of similar type, and returns true
3594 * if it is equal. Equality is symmetrical, so the same result should be
3595 * returned if this and the argument are flipped.
3596 *
3597 * assert( a.equals(b) === b.equals(a) );
3598 *
3599 * `hashCode` returns a 32bit integer number representing the object which will
3600 * be used to determine how to store the value object in a Map or Set. You must
3601 * provide both or neither methods, one must not exist without the other.
3602 *
3603 * Also, an important relationship between these methods must be upheld: if two
3604 * values are equal, they *must* return the same hashCode. If the values are not
3605 * equal, they might have the same hashCode; this is called a hash collision,
3606 * and while undesirable for performance reasons, it is acceptable.
3607 *
3608 * if (a.equals(b)) {
3609 * assert( a.hashCode() === b.hashCode() );
3610 * }
3611 *
3612 * All Immutable collections are Value Objects: they implement `equals()`
3613 * and `hashCode()`.
3614 */
3615function is(valueA, valueB) {
3616 if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
3617 return true;
3618 }
3619 if (!valueA || !valueB) {
3620 return false;
3621 }
3622 if (typeof valueA.valueOf === 'function' &&
3623 typeof valueB.valueOf === 'function') {
3624 valueA = valueA.valueOf();
3625 valueB = valueB.valueOf();
3626 if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
3627 return true;
3628 }
3629 if (!valueA || !valueB) {
3630 return false;
3631 }
3632 }
3633 return !!(isValueObject(valueA) &&
3634 isValueObject(valueB) &&
3635 valueA.equals(valueB));
3636}
3637var imul = typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2
3638 ? Math.imul
3639 : function imul(a, b) {
3640 a |= 0; // int
3641 b |= 0; // int
3642 var c = a & 0xffff;
3643 var d = b & 0xffff;
3644 // Shift by 0 fixes the sign on the high part.
3645 return (c * d + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0)) | 0; // int
3646 };
3647// v8 has an optimization for storing 31-bit signed numbers.
3648// Values which have either 00 or 11 as the high order bits qualify.
3649// This function drops the highest order bit in a signed number, maintaining
3650// the sign bit.
3651function smi(i32) {
3652 return ((i32 >>> 1) & 0x40000000) | (i32 & 0xbfffffff);
3653}
3654var defaultValueOf = Object.prototype.valueOf;
3655function hash(o) {
3656 switch (typeof o) {
3657 case 'boolean':
3658 // The hash values for built-in constants are a 1 value for each 5-byte
3659 // shift region expect for the first, which encodes the value. This
3660 // reduces the odds of a hash collision for these common values.
3661 return o ? 0x42108421 : 0x42108420;
3662 case 'number':
3663 return hashNumber(o);
3664 case 'string':
3665 return o.length > STRING_HASH_CACHE_MIN_STRLEN
3666 ? cachedHashString(o)
3667 : hashString(o);
3668 case 'object':
3669 case 'function':
3670 if (o === null) {
3671 return 0x42108422;
3672 }
3673 if (typeof o.hashCode === 'function') {
3674 // Drop any high bits from accidentally long hash codes.
3675 return smi(o.hashCode(o));
3676 }
3677 if (o.valueOf !== defaultValueOf && typeof o.valueOf === 'function') {
3678 o = o.valueOf(o);
3679 }
3680 return hashJSObj(o);
3681 case 'undefined':
3682 return 0x42108423;
3683 default:
3684 if (typeof o.toString === 'function') {
3685 return hashString(o.toString());
3686 }
3687 throw new Error('Value type ' + typeof o + ' cannot be hashed.');
3688 }
3689}
3690// Compress arbitrarily large numbers into smi hashes.
3691function hashNumber(n) {
3692 if (n !== n || n === Infinity) {
3693 return 0;
3694 }
3695 var hash = n | 0;
3696 if (hash !== n) {
3697 hash ^= n * 0xffffffff;
3698 }
3699 while (n > 0xffffffff) {
3700 n /= 0xffffffff;
3701 hash ^= n;
3702 }
3703 return smi(hash);
3704}
3705function cachedHashString(string) {
3706 var hashed = stringHashCache[string];
3707 if (hashed === undefined) {
3708 hashed = hashString(string);
3709 if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) {
3710 STRING_HASH_CACHE_SIZE = 0;
3711 stringHashCache = {};
3712 }
3713 STRING_HASH_CACHE_SIZE++;
3714 stringHashCache[string] = hashed;
3715 }
3716 return hashed;
3717}
3718// http://jsperf.com/hashing-strings
3719function hashString(string) {
3720 // This is the hash from JVM
3721 // The hash code for a string is computed as
3722 // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],
3723 // where s[i] is the ith character of the string and n is the length of
3724 // the string. We "mod" the result to make it between 0 (inclusive) and 2^31
3725 // (exclusive) by dropping high bits.
3726 var hashed = 0;
3727 for (var ii = 0; ii < string.length; ii++) {
3728 hashed = (31 * hashed + string.charCodeAt(ii)) | 0;
3729 }
3730 return smi(hashed);
3731}
3732function hashJSObj(obj) {
3733 var hashed;
3734 if (usingWeakMap) {
3735 hashed = weakMap.get(obj);
3736 if (hashed !== undefined) {
3737 return hashed;
3738 }
3739 }
3740 hashed = obj[UID_HASH_KEY];
3741 if (hashed !== undefined) {
3742 return hashed;
3743 }
3744 if (!canDefineProperty) {
3745 hashed = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY];
3746 if (hashed !== undefined) {
3747 return hashed;
3748 }
3749 hashed = getIENodeHash(obj);
3750 if (hashed !== undefined) {
3751 return hashed;
3752 }
3753 }
3754 hashed = ++objHashUID;
3755 if (objHashUID & 0x40000000) {
3756 objHashUID = 0;
3757 }
3758 if (usingWeakMap) {
3759 weakMap.set(obj, hashed);
3760 }
3761 else if (isExtensible !== undefined && isExtensible(obj) === false) {
3762 throw new Error('Non-extensible objects are not allowed as keys.');
3763 }
3764 else if (canDefineProperty) {
3765 Object.defineProperty(obj, UID_HASH_KEY, {
3766 enumerable: false,
3767 configurable: false,
3768 writable: false,
3769 value: hashed,
3770 });
3771 }
3772 else if (obj.propertyIsEnumerable !== undefined &&
3773 obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) {
3774 // Since we can't define a non-enumerable property on the object
3775 // we'll hijack one of the less-used non-enumerable properties to
3776 // save our hash on it. Since this is a function it will not show up in
3777 // `JSON.stringify` which is what we want.
3778 obj.propertyIsEnumerable = function () {
3779 return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments);
3780 };
3781 obj.propertyIsEnumerable[UID_HASH_KEY] = hashed;
3782 }
3783 else if (obj.nodeType !== undefined) {
3784 // At this point we couldn't get the IE `uniqueID` to use as a hash
3785 // and we couldn't use a non-enumerable property to exploit the
3786 // dontEnum bug so we simply add the `UID_HASH_KEY` on the node
3787 // itself.
3788 obj[UID_HASH_KEY] = hashed;
3789 }
3790 else {
3791 throw new Error('Unable to set a non-enumerable property on object.');
3792 }
3793 return hashed;
3794}
3795// Get references to ES5 object methods.
3796var isExtensible = Object.isExtensible;
3797// True if Object.defineProperty works as expected. IE8 fails this test.
3798var canDefineProperty = (function () {
3799 try {
3800 Object.defineProperty({}, '@', {});
3801 return true;
3802 }
3803 catch (e) {
3804 return false;
3805 }
3806})();
3807// IE has a `uniqueID` property on DOM nodes. We can construct the hash from it
3808// and avoid memory leaks from the IE cloneNode bug.
3809function getIENodeHash(node) {
3810 if (node && node.nodeType > 0) {
3811 switch (node.nodeType) {
3812 case 1: // Element
3813 return node.uniqueID;
3814 case 9: // Document
3815 return node.documentElement && node.documentElement.uniqueID;
3816 }
3817 }
3818}
3819// If possible, use a WeakMap.
3820var usingWeakMap = typeof WeakMap === 'function';
3821var weakMap;
3822if (usingWeakMap) {
3823 weakMap = new WeakMap();
3824}
3825var objHashUID = 0;
3826var UID_HASH_KEY = '__immutablehash__';
3827if (typeof Symbol === 'function') {
3828 UID_HASH_KEY = Symbol(UID_HASH_KEY);
3829}
3830var STRING_HASH_CACHE_MIN_STRLEN = 16;
3831var STRING_HASH_CACHE_MAX_SIZE = 255;
3832var STRING_HASH_CACHE_SIZE = 0;
3833var stringHashCache = {};
3834var ToKeyedSequence = /*@__PURE__*/ (function (KeyedSeq$$1) {
3835 function ToKeyedSequence(indexed, useKeys) {
3836 this._iter = indexed;
3837 this._useKeys = useKeys;
3838 this.size = indexed.size;
3839 }
3840 if (KeyedSeq$$1)
3841 ToKeyedSequence.__proto__ = KeyedSeq$$1;
3842 ToKeyedSequence.prototype = Object.create(KeyedSeq$$1 && KeyedSeq$$1.prototype);
3843 ToKeyedSequence.prototype.constructor = ToKeyedSequence;
3844 ToKeyedSequence.prototype.get = function get(key, notSetValue) {
3845 return this._iter.get(key, notSetValue);
3846 };
3847 ToKeyedSequence.prototype.has = function has(key) {
3848 return this._iter.has(key);
3849 };
3850 ToKeyedSequence.prototype.valueSeq = function valueSeq() {
3851 return this._iter.valueSeq();
3852 };
3853 ToKeyedSequence.prototype.reverse = function reverse() {
3854 var this$1 = this;
3855 var reversedSequence = reverseFactory(this, true);
3856 if (!this._useKeys) {
3857 reversedSequence.valueSeq = function () { return this$1._iter.toSeq().reverse(); };
3858 }
3859 return reversedSequence;
3860 };
3861 ToKeyedSequence.prototype.map = function map(mapper, context) {
3862 var this$1 = this;
3863 var mappedSequence = mapFactory(this, mapper, context);
3864 if (!this._useKeys) {
3865 mappedSequence.valueSeq = function () { return this$1._iter.toSeq().map(mapper, context); };
3866 }
3867 return mappedSequence;
3868 };
3869 ToKeyedSequence.prototype.__iterate = function __iterate(fn, reverse) {
3870 var this$1 = this;
3871 return this._iter.__iterate(function (v, k) { return fn(v, k, this$1); }, reverse);
3872 };
3873 ToKeyedSequence.prototype.__iterator = function __iterator(type, reverse) {
3874 return this._iter.__iterator(type, reverse);
3875 };
3876 return ToKeyedSequence;
3877}(KeyedSeq));
3878ToKeyedSequence.prototype[IS_ORDERED_SYMBOL] = true;
3879var ToIndexedSequence = /*@__PURE__*/ (function (IndexedSeq$$1) {
3880 function ToIndexedSequence(iter) {
3881 this._iter = iter;
3882 this.size = iter.size;
3883 }
3884 if (IndexedSeq$$1)
3885 ToIndexedSequence.__proto__ = IndexedSeq$$1;
3886 ToIndexedSequence.prototype = Object.create(IndexedSeq$$1 && IndexedSeq$$1.prototype);
3887 ToIndexedSequence.prototype.constructor = ToIndexedSequence;
3888 ToIndexedSequence.prototype.includes = function includes(value) {
3889 return this._iter.includes(value);
3890 };
3891 ToIndexedSequence.prototype.__iterate = function __iterate(fn, reverse) {
3892 var this$1 = this;
3893 var i = 0;
3894 reverse && ensureSize(this);
3895 return this._iter.__iterate(function (v) { return fn(v, reverse ? this$1.size - ++i : i++, this$1); }, reverse);
3896 };
3897 ToIndexedSequence.prototype.__iterator = function __iterator(type, reverse) {
3898 var this$1 = this;
3899 var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
3900 var i = 0;
3901 reverse && ensureSize(this);
3902 return new Iterator(function () {
3903 var step = iterator.next();
3904 return step.done
3905 ? step
3906 : iteratorValue(type, reverse ? this$1.size - ++i : i++, step.value, step);
3907 });
3908 };
3909 return ToIndexedSequence;
3910}(IndexedSeq));
3911var ToSetSequence = /*@__PURE__*/ (function (SetSeq$$1) {
3912 function ToSetSequence(iter) {
3913 this._iter = iter;
3914 this.size = iter.size;
3915 }
3916 if (SetSeq$$1)
3917 ToSetSequence.__proto__ = SetSeq$$1;
3918 ToSetSequence.prototype = Object.create(SetSeq$$1 && SetSeq$$1.prototype);
3919 ToSetSequence.prototype.constructor = ToSetSequence;
3920 ToSetSequence.prototype.has = function has(key) {
3921 return this._iter.includes(key);
3922 };
3923 ToSetSequence.prototype.__iterate = function __iterate(fn, reverse) {
3924 var this$1 = this;
3925 return this._iter.__iterate(function (v) { return fn(v, v, this$1); }, reverse);
3926 };
3927 ToSetSequence.prototype.__iterator = function __iterator(type, reverse) {
3928 var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
3929 return new Iterator(function () {
3930 var step = iterator.next();
3931 return step.done
3932 ? step
3933 : iteratorValue(type, step.value, step.value, step);
3934 });
3935 };
3936 return ToSetSequence;
3937}(SetSeq));
3938var FromEntriesSequence = /*@__PURE__*/ (function (KeyedSeq$$1) {
3939 function FromEntriesSequence(entries) {
3940 this._iter = entries;
3941 this.size = entries.size;
3942 }
3943 if (KeyedSeq$$1)
3944 FromEntriesSequence.__proto__ = KeyedSeq$$1;
3945 FromEntriesSequence.prototype = Object.create(KeyedSeq$$1 && KeyedSeq$$1.prototype);
3946 FromEntriesSequence.prototype.constructor = FromEntriesSequence;
3947 FromEntriesSequence.prototype.entrySeq = function entrySeq() {
3948 return this._iter.toSeq();
3949 };
3950 FromEntriesSequence.prototype.__iterate = function __iterate(fn, reverse) {
3951 var this$1 = this;
3952 return this._iter.__iterate(function (entry) {
3953 // Check if entry exists first so array access doesn't throw for holes
3954 // in the parent iteration.
3955 if (entry) {
3956 validateEntry(entry);
3957 var indexedCollection = isCollection(entry);
3958 return fn(indexedCollection ? entry.get(1) : entry[1], indexedCollection ? entry.get(0) : entry[0], this$1);
3959 }
3960 }, reverse);
3961 };
3962 FromEntriesSequence.prototype.__iterator = function __iterator(type, reverse) {
3963 var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
3964 return new Iterator(function () {
3965 while (true) {
3966 var step = iterator.next();
3967 if (step.done) {
3968 return step;
3969 }
3970 var entry = step.value;
3971 // Check if entry exists first so array access doesn't throw for holes
3972 // in the parent iteration.
3973 if (entry) {
3974 validateEntry(entry);
3975 var indexedCollection = isCollection(entry);
3976 return iteratorValue(type, indexedCollection ? entry.get(0) : entry[0], indexedCollection ? entry.get(1) : entry[1], step);
3977 }
3978 }
3979 });
3980 };
3981 return FromEntriesSequence;
3982}(KeyedSeq));
3983ToIndexedSequence.prototype.cacheResult = ToKeyedSequence.prototype.cacheResult = ToSetSequence.prototype.cacheResult = FromEntriesSequence.prototype.cacheResult = cacheResultThrough;
3984function flipFactory(collection) {
3985 var flipSequence = makeSequence(collection);
3986 flipSequence._iter = collection;
3987 flipSequence.size = collection.size;
3988 flipSequence.flip = function () { return collection; };
3989 flipSequence.reverse = function () {
3990 var reversedSequence = collection.reverse.apply(this); // super.reverse()
3991 reversedSequence.flip = function () { return collection.reverse(); };
3992 return reversedSequence;
3993 };
3994 flipSequence.has = function (key) { return collection.includes(key); };
3995 flipSequence.includes = function (key) { return collection.has(key); };
3996 flipSequence.cacheResult = cacheResultThrough;
3997 flipSequence.__iterateUncached = function (fn, reverse) {
3998 var this$1 = this;
3999 return collection.__iterate(function (v, k) { return fn(k, v, this$1) !== false; }, reverse);
4000 };
4001 flipSequence.__iteratorUncached = function (type, reverse) {
4002 if (type === ITERATE_ENTRIES) {
4003 var iterator = collection.__iterator(type, reverse);
4004 return new Iterator(function () {
4005 var step = iterator.next();
4006 if (!step.done) {
4007 var k = step.value[0];
4008 step.value[0] = step.value[1];
4009 step.value[1] = k;
4010 }
4011 return step;
4012 });
4013 }
4014 return collection.__iterator(type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES, reverse);
4015 };
4016 return flipSequence;
4017}
4018function mapFactory(collection, mapper, context) {
4019 var mappedSequence = makeSequence(collection);
4020 mappedSequence.size = collection.size;
4021 mappedSequence.has = function (key) { return collection.has(key); };
4022 mappedSequence.get = function (key, notSetValue) {
4023 var v = collection.get(key, NOT_SET);
4024 return v === NOT_SET
4025 ? notSetValue
4026 : mapper.call(context, v, key, collection);
4027 };
4028 mappedSequence.__iterateUncached = function (fn, reverse) {
4029 var this$1 = this;
4030 return collection.__iterate(function (v, k, c) { return fn(mapper.call(context, v, k, c), k, this$1) !== false; }, reverse);
4031 };
4032 mappedSequence.__iteratorUncached = function (type, reverse) {
4033 var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
4034 return new Iterator(function () {
4035 var step = iterator.next();
4036 if (step.done) {
4037 return step;
4038 }
4039 var entry = step.value;
4040 var key = entry[0];
4041 return iteratorValue(type, key, mapper.call(context, entry[1], key, collection), step);
4042 });
4043 };
4044 return mappedSequence;
4045}
4046function reverseFactory(collection, useKeys) {
4047 var this$1 = this;
4048 var reversedSequence = makeSequence(collection);
4049 reversedSequence._iter = collection;
4050 reversedSequence.size = collection.size;
4051 reversedSequence.reverse = function () { return collection; };
4052 if (collection.flip) {
4053 reversedSequence.flip = function () {
4054 var flipSequence = flipFactory(collection);
4055 flipSequence.reverse = function () { return collection.flip(); };
4056 return flipSequence;
4057 };
4058 }
4059 reversedSequence.get = function (key, notSetValue) { return collection.get(useKeys ? key : -1 - key, notSetValue); };
4060 reversedSequence.has = function (key) { return collection.has(useKeys ? key : -1 - key); };
4061 reversedSequence.includes = function (value) { return collection.includes(value); };
4062 reversedSequence.cacheResult = cacheResultThrough;
4063 reversedSequence.__iterate = function (fn, reverse) {
4064 var this$1 = this;
4065 var i = 0;
4066 reverse && ensureSize(collection);
4067 return collection.__iterate(function (v, k) { return fn(v, useKeys ? k : reverse ? this$1.size - ++i : i++, this$1); }, !reverse);
4068 };
4069 reversedSequence.__iterator = function (type, reverse) {
4070 var i = 0;
4071 reverse && ensureSize(collection);
4072 var iterator = collection.__iterator(ITERATE_ENTRIES, !reverse);
4073 return new Iterator(function () {
4074 var step = iterator.next();
4075 if (step.done) {
4076 return step;
4077 }
4078 var entry = step.value;
4079 return iteratorValue(type, useKeys ? entry[0] : reverse ? this$1.size - ++i : i++, entry[1], step);
4080 });
4081 };
4082 return reversedSequence;
4083}
4084function filterFactory(collection, predicate, context, useKeys) {
4085 var filterSequence = makeSequence(collection);
4086 if (useKeys) {
4087 filterSequence.has = function (key) {
4088 var v = collection.get(key, NOT_SET);
4089 return v !== NOT_SET && !!predicate.call(context, v, key, collection);
4090 };
4091 filterSequence.get = function (key, notSetValue) {
4092 var v = collection.get(key, NOT_SET);
4093 return v !== NOT_SET && predicate.call(context, v, key, collection)
4094 ? v
4095 : notSetValue;
4096 };
4097 }
4098 filterSequence.__iterateUncached = function (fn, reverse) {
4099 var this$1 = this;
4100 var iterations = 0;
4101 collection.__iterate(function (v, k, c) {
4102 if (predicate.call(context, v, k, c)) {
4103 iterations++;
4104 return fn(v, useKeys ? k : iterations - 1, this$1);
4105 }
4106 }, reverse);
4107 return iterations;
4108 };
4109 filterSequence.__iteratorUncached = function (type, reverse) {
4110 var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
4111 var iterations = 0;
4112 return new Iterator(function () {
4113 while (true) {
4114 var step = iterator.next();
4115 if (step.done) {
4116 return step;
4117 }
4118 var entry = step.value;
4119 var key = entry[0];
4120 var value = entry[1];
4121 if (predicate.call(context, value, key, collection)) {
4122 return iteratorValue(type, useKeys ? key : iterations++, value, step);
4123 }
4124 }
4125 });
4126 };
4127 return filterSequence;
4128}
4129function countByFactory(collection, grouper, context) {
4130 var groups = Map$1().asMutable();
4131 collection.__iterate(function (v, k) {
4132 groups.update(grouper.call(context, v, k, collection), 0, function (a) { return a + 1; });
4133 });
4134 return groups.asImmutable();
4135}
4136function groupByFactory(collection, grouper, context) {
4137 var isKeyedIter = isKeyed(collection);
4138 var groups = (isOrdered(collection) ? OrderedMap() : Map$1()).asMutable();
4139 collection.__iterate(function (v, k) {
4140 groups.update(grouper.call(context, v, k, collection), function (a) { return ((a = a || []), a.push(isKeyedIter ? [k, v] : v), a); });
4141 });
4142 var coerce = collectionClass(collection);
4143 return groups.map(function (arr) { return reify(collection, coerce(arr)); }).asImmutable();
4144}
4145function sliceFactory(collection, begin, end, useKeys) {
4146 var originalSize = collection.size;
4147 if (wholeSlice(begin, end, originalSize)) {
4148 return collection;
4149 }
4150 var resolvedBegin = resolveBegin(begin, originalSize);
4151 var resolvedEnd = resolveEnd(end, originalSize);
4152 // begin or end will be NaN if they were provided as negative numbers and
4153 // this collection's size is unknown. In that case, cache first so there is
4154 // a known size and these do not resolve to NaN.
4155 if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) {
4156 return sliceFactory(collection.toSeq().cacheResult(), begin, end, useKeys);
4157 }
4158 // Note: resolvedEnd is undefined when the original sequence's length is
4159 // unknown and this slice did not supply an end and should contain all
4160 // elements after resolvedBegin.
4161 // In that case, resolvedSize will be NaN and sliceSize will remain undefined.
4162 var resolvedSize = resolvedEnd - resolvedBegin;
4163 var sliceSize;
4164 if (resolvedSize === resolvedSize) {
4165 sliceSize = resolvedSize < 0 ? 0 : resolvedSize;
4166 }
4167 var sliceSeq = makeSequence(collection);
4168 // If collection.size is undefined, the size of the realized sliceSeq is
4169 // unknown at this point unless the number of items to slice is 0
4170 sliceSeq.size =
4171 sliceSize === 0 ? sliceSize : (collection.size && sliceSize) || undefined;
4172 if (!useKeys && isSeq(collection) && sliceSize >= 0) {
4173 sliceSeq.get = function (index, notSetValue) {
4174 index = wrapIndex(this, index);
4175 return index >= 0 && index < sliceSize
4176 ? collection.get(index + resolvedBegin, notSetValue)
4177 : notSetValue;
4178 };
4179 }
4180 sliceSeq.__iterateUncached = function (fn, reverse) {
4181 var this$1 = this;
4182 if (sliceSize === 0) {
4183 return 0;
4184 }
4185 if (reverse) {
4186 return this.cacheResult().__iterate(fn, reverse);
4187 }
4188 var skipped = 0;
4189 var isSkipping = true;
4190 var iterations = 0;
4191 collection.__iterate(function (v, k) {
4192 if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) {
4193 iterations++;
4194 return (fn(v, useKeys ? k : iterations - 1, this$1) !== false &&
4195 iterations !== sliceSize);
4196 }
4197 });
4198 return iterations;
4199 };
4200 sliceSeq.__iteratorUncached = function (type, reverse) {
4201 if (sliceSize !== 0 && reverse) {
4202 return this.cacheResult().__iterator(type, reverse);
4203 }
4204 // Don't bother instantiating parent iterator if taking 0.
4205 if (sliceSize === 0) {
4206 return new Iterator(iteratorDone);
4207 }
4208 var iterator = collection.__iterator(type, reverse);
4209 var skipped = 0;
4210 var iterations = 0;
4211 return new Iterator(function () {
4212 while (skipped++ < resolvedBegin) {
4213 iterator.next();
4214 }
4215 if (++iterations > sliceSize) {
4216 return iteratorDone();
4217 }
4218 var step = iterator.next();
4219 if (useKeys || type === ITERATE_VALUES || step.done) {
4220 return step;
4221 }
4222 if (type === ITERATE_KEYS) {
4223 return iteratorValue(type, iterations - 1, undefined, step);
4224 }
4225 return iteratorValue(type, iterations - 1, step.value[1], step);
4226 });
4227 };
4228 return sliceSeq;
4229}
4230function takeWhileFactory(collection, predicate, context) {
4231 var takeSequence = makeSequence(collection);
4232 takeSequence.__iterateUncached = function (fn, reverse) {
4233 var this$1 = this;
4234 if (reverse) {
4235 return this.cacheResult().__iterate(fn, reverse);
4236 }
4237 var iterations = 0;
4238 collection.__iterate(function (v, k, c) { return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$1); });
4239 return iterations;
4240 };
4241 takeSequence.__iteratorUncached = function (type, reverse) {
4242 var this$1 = this;
4243 if (reverse) {
4244 return this.cacheResult().__iterator(type, reverse);
4245 }
4246 var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
4247 var iterating = true;
4248 return new Iterator(function () {
4249 if (!iterating) {
4250 return iteratorDone();
4251 }
4252 var step = iterator.next();
4253 if (step.done) {
4254 return step;
4255 }
4256 var entry = step.value;
4257 var k = entry[0];
4258 var v = entry[1];
4259 if (!predicate.call(context, v, k, this$1)) {
4260 iterating = false;
4261 return iteratorDone();
4262 }
4263 return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step);
4264 });
4265 };
4266 return takeSequence;
4267}
4268function skipWhileFactory(collection, predicate, context, useKeys) {
4269 var skipSequence = makeSequence(collection);
4270 skipSequence.__iterateUncached = function (fn, reverse) {
4271 var this$1 = this;
4272 if (reverse) {
4273 return this.cacheResult().__iterate(fn, reverse);
4274 }
4275 var isSkipping = true;
4276 var iterations = 0;
4277 collection.__iterate(function (v, k, c) {
4278 if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) {
4279 iterations++;
4280 return fn(v, useKeys ? k : iterations - 1, this$1);
4281 }
4282 });
4283 return iterations;
4284 };
4285 skipSequence.__iteratorUncached = function (type, reverse) {
4286 var this$1 = this;
4287 if (reverse) {
4288 return this.cacheResult().__iterator(type, reverse);
4289 }
4290 var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
4291 var skipping = true;
4292 var iterations = 0;
4293 return new Iterator(function () {
4294 var step;
4295 var k;
4296 var v;
4297 do {
4298 step = iterator.next();
4299 if (step.done) {
4300 if (useKeys || type === ITERATE_VALUES) {
4301 return step;
4302 }
4303 if (type === ITERATE_KEYS) {
4304 return iteratorValue(type, iterations++, undefined, step);
4305 }
4306 return iteratorValue(type, iterations++, step.value[1], step);
4307 }
4308 var entry = step.value;
4309 k = entry[0];
4310 v = entry[1];
4311 skipping && (skipping = predicate.call(context, v, k, this$1));
4312 } while (skipping);
4313 return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step);
4314 });
4315 };
4316 return skipSequence;
4317}
4318function concatFactory(collection, values) {
4319 var isKeyedCollection = isKeyed(collection);
4320 var iters = [collection]
4321 .concat(values)
4322 .map(function (v) {
4323 if (!isCollection(v)) {
4324 v = isKeyedCollection
4325 ? keyedSeqFromValue(v)
4326 : indexedSeqFromValue(Array.isArray(v) ? v : [v]);
4327 }
4328 else if (isKeyedCollection) {
4329 v = KeyedCollection(v);
4330 }
4331 return v;
4332 })
4333 .filter(function (v) { return v.size !== 0; });
4334 if (iters.length === 0) {
4335 return collection;
4336 }
4337 if (iters.length === 1) {
4338 var singleton = iters[0];
4339 if (singleton === collection ||
4340 (isKeyedCollection && isKeyed(singleton)) ||
4341 (isIndexed(collection) && isIndexed(singleton))) {
4342 return singleton;
4343 }
4344 }
4345 var concatSeq = new ArraySeq(iters);
4346 if (isKeyedCollection) {
4347 concatSeq = concatSeq.toKeyedSeq();
4348 }
4349 else if (!isIndexed(collection)) {
4350 concatSeq = concatSeq.toSetSeq();
4351 }
4352 concatSeq = concatSeq.flatten(true);
4353 concatSeq.size = iters.reduce(function (sum, seq) {
4354 if (sum !== undefined) {
4355 var size = seq.size;
4356 if (size !== undefined) {
4357 return sum + size;
4358 }
4359 }
4360 }, 0);
4361 return concatSeq;
4362}
4363function flattenFactory(collection, depth, useKeys) {
4364 var flatSequence = makeSequence(collection);
4365 flatSequence.__iterateUncached = function (fn, reverse) {
4366 if (reverse) {
4367 return this.cacheResult().__iterate(fn, reverse);
4368 }
4369 var iterations = 0;
4370 var stopped = false;
4371 function flatDeep(iter, currentDepth) {
4372 iter.__iterate(function (v, k) {
4373 if ((!depth || currentDepth < depth) && isCollection(v)) {
4374 flatDeep(v, currentDepth + 1);
4375 }
4376 else {
4377 iterations++;
4378 if (fn(v, useKeys ? k : iterations - 1, flatSequence) === false) {
4379 stopped = true;
4380 }
4381 }
4382 return !stopped;
4383 }, reverse);
4384 }
4385 flatDeep(collection, 0);
4386 return iterations;
4387 };
4388 flatSequence.__iteratorUncached = function (type, reverse) {
4389 if (reverse) {
4390 return this.cacheResult().__iterator(type, reverse);
4391 }
4392 var iterator = collection.__iterator(type, reverse);
4393 var stack = [];
4394 var iterations = 0;
4395 return new Iterator(function () {
4396 while (iterator) {
4397 var step = iterator.next();
4398 if (step.done !== false) {
4399 iterator = stack.pop();
4400 continue;
4401 }
4402 var v = step.value;
4403 if (type === ITERATE_ENTRIES) {
4404 v = v[1];
4405 }
4406 if ((!depth || stack.length < depth) && isCollection(v)) {
4407 stack.push(iterator);
4408 iterator = v.__iterator(type, reverse);
4409 }
4410 else {
4411 return useKeys ? step : iteratorValue(type, iterations++, v, step);
4412 }
4413 }
4414 return iteratorDone();
4415 });
4416 };
4417 return flatSequence;
4418}
4419function flatMapFactory(collection, mapper, context) {
4420 var coerce = collectionClass(collection);
4421 return collection
4422 .toSeq()
4423 .map(function (v, k) { return coerce(mapper.call(context, v, k, collection)); })
4424 .flatten(true);
4425}
4426function interposeFactory(collection, separator) {
4427 var interposedSequence = makeSequence(collection);
4428 interposedSequence.size = collection.size && collection.size * 2 - 1;
4429 interposedSequence.__iterateUncached = function (fn, reverse) {
4430 var this$1 = this;
4431 var iterations = 0;
4432 collection.__iterate(function (v) {
4433 return (!iterations || fn(separator, iterations++, this$1) !== false) &&
4434 fn(v, iterations++, this$1) !== false;
4435 }, reverse);
4436 return iterations;
4437 };
4438 interposedSequence.__iteratorUncached = function (type, reverse) {
4439 var iterator = collection.__iterator(ITERATE_VALUES, reverse);
4440 var iterations = 0;
4441 var step;
4442 return new Iterator(function () {
4443 if (!step || iterations % 2) {
4444 step = iterator.next();
4445 if (step.done) {
4446 return step;
4447 }
4448 }
4449 return iterations % 2
4450 ? iteratorValue(type, iterations++, separator)
4451 : iteratorValue(type, iterations++, step.value, step);
4452 });
4453 };
4454 return interposedSequence;
4455}
4456function sortFactory(collection, comparator, mapper) {
4457 if (!comparator) {
4458 comparator = defaultComparator;
4459 }
4460 var isKeyedCollection = isKeyed(collection);
4461 var index = 0;
4462 var entries = collection
4463 .toSeq()
4464 .map(function (v, k) { return [k, v, index++, mapper ? mapper(v, k, collection) : v]; })
4465 .valueSeq()
4466 .toArray();
4467 entries.sort(function (a, b) { return comparator(a[3], b[3]) || a[2] - b[2]; }).forEach(isKeyedCollection
4468 ? function (v, i) {
4469 entries[i].length = 2;
4470 }
4471 : function (v, i) {
4472 entries[i] = v[1];
4473 });
4474 return isKeyedCollection
4475 ? KeyedSeq(entries)
4476 : isIndexed(collection)
4477 ? IndexedSeq(entries)
4478 : SetSeq(entries);
4479}
4480function maxFactory(collection, comparator, mapper) {
4481 if (!comparator) {
4482 comparator = defaultComparator;
4483 }
4484 if (mapper) {
4485 var entry = collection
4486 .toSeq()
4487 .map(function (v, k) { return [v, mapper(v, k, collection)]; })
4488 .reduce(function (a, b) { return (maxCompare(comparator, a[1], b[1]) ? b : a); });
4489 return entry && entry[0];
4490 }
4491 return collection.reduce(function (a, b) { return (maxCompare(comparator, a, b) ? b : a); });
4492}
4493function maxCompare(comparator, a, b) {
4494 var comp = comparator(b, a);
4495 // b is considered the new max if the comparator declares them equal, but
4496 // they are not equal and b is in fact a nullish value.
4497 return ((comp === 0 && b !== a && (b === undefined || b === null || b !== b)) ||
4498 comp > 0);
4499}
4500function zipWithFactory(keyIter, zipper, iters, zipAll) {
4501 var zipSequence = makeSequence(keyIter);
4502 var sizes = new ArraySeq(iters).map(function (i) { return i.size; });
4503 zipSequence.size = zipAll ? sizes.max() : sizes.min();
4504 // Note: this a generic base implementation of __iterate in terms of
4505 // __iterator which may be more generically useful in the future.
4506 zipSequence.__iterate = function (fn, reverse) {
4507 /* generic:
4508 var iterator = this.__iterator(ITERATE_ENTRIES, reverse);
4509 var step;
4510 var iterations = 0;
4511 while (!(step = iterator.next()).done) {
4512 iterations++;
4513 if (fn(step.value[1], step.value[0], this) === false) {
4514 break;
4515 }
4516 }
4517 return iterations;
4518 */
4519 // indexed:
4520 var iterator = this.__iterator(ITERATE_VALUES, reverse);
4521 var step;
4522 var iterations = 0;
4523 while (!(step = iterator.next()).done) {
4524 if (fn(step.value, iterations++, this) === false) {
4525 break;
4526 }
4527 }
4528 return iterations;
4529 };
4530 zipSequence.__iteratorUncached = function (type, reverse) {
4531 var iterators = iters.map(function (i) { return ((i = Collection(i)), getIterator(reverse ? i.reverse() : i)); });
4532 var iterations = 0;
4533 var isDone = false;
4534 return new Iterator(function () {
4535 var steps;
4536 if (!isDone) {
4537 steps = iterators.map(function (i) { return i.next(); });
4538 isDone = zipAll ? steps.every(function (s) { return s.done; }) : steps.some(function (s) { return s.done; });
4539 }
4540 if (isDone) {
4541 return iteratorDone();
4542 }
4543 return iteratorValue(type, iterations++, zipper.apply(null, steps.map(function (s) { return s.value; })));
4544 });
4545 };
4546 return zipSequence;
4547}
4548// #pragma Helper Functions
4549function reify(iter, seq) {
4550 return iter === seq ? iter : isSeq(iter) ? seq : iter.constructor(seq);
4551}
4552function validateEntry(entry) {
4553 if (entry !== Object(entry)) {
4554 throw new TypeError('Expected [K, V] tuple: ' + entry);
4555 }
4556}
4557function collectionClass(collection) {
4558 return isKeyed(collection)
4559 ? KeyedCollection
4560 : isIndexed(collection)
4561 ? IndexedCollection
4562 : SetCollection;
4563}
4564function makeSequence(collection) {
4565 return Object.create((isKeyed(collection)
4566 ? KeyedSeq
4567 : isIndexed(collection)
4568 ? IndexedSeq
4569 : SetSeq).prototype);
4570}
4571function cacheResultThrough() {
4572 if (this._iter.cacheResult) {
4573 this._iter.cacheResult();
4574 this.size = this._iter.size;
4575 return this;
4576 }
4577 return Seq.prototype.cacheResult.call(this);
4578}
4579function defaultComparator(a, b) {
4580 if (a === undefined && b === undefined) {
4581 return 0;
4582 }
4583 if (a === undefined) {
4584 return 1;
4585 }
4586 if (b === undefined) {
4587 return -1;
4588 }
4589 return a > b ? 1 : a < b ? -1 : 0;
4590}
4591// http://jsperf.com/copy-array-inline
4592function arrCopy(arr, offset) {
4593 offset = offset || 0;
4594 var len = Math.max(0, arr.length - offset);
4595 var newArr = new Array(len);
4596 for (var ii = 0; ii < len; ii++) {
4597 newArr[ii] = arr[ii + offset];
4598 }
4599 return newArr;
4600}
4601function invariant(condition, error) {
4602 if (!condition) {
4603 throw new Error(error);
4604 }
4605}
4606function assertNotInfinite(size) {
4607 invariant(size !== Infinity, 'Cannot perform this action with an infinite size.');
4608}
4609function coerceKeyPath(keyPath) {
4610 if (isArrayLike(keyPath) && typeof keyPath !== 'string') {
4611 return keyPath;
4612 }
4613 if (isOrdered(keyPath)) {
4614 return keyPath.toArray();
4615 }
4616 throw new TypeError('Invalid keyPath: expected Ordered Collection or Array: ' + keyPath);
4617}
4618function isPlainObj(value) {
4619 return (value &&
4620 (typeof value.constructor !== 'function' ||
4621 value.constructor.name === 'Object'));
4622}
4623/**
4624 * Returns true if the value is a potentially-persistent data structure, either
4625 * provided by Immutable.js or a plain Array or Object.
4626 */
4627function isDataStructure(value) {
4628 return (typeof value === 'object' &&
4629 (isImmutable(value) || Array.isArray(value) || isPlainObj(value)));
4630}
4631/**
4632 * Converts a value to a string, adding quotes if a string was provided.
4633 */
4634function quoteString(value) {
4635 try {
4636 return typeof value === 'string' ? JSON.stringify(value) : String(value);
4637 }
4638 catch (_ignoreError) {
4639 return JSON.stringify(value);
4640 }
4641}
4642function has(collection, key) {
4643 return isImmutable(collection)
4644 ? collection.has(key)
4645 : isDataStructure(collection) && hasOwnProperty.call(collection, key);
4646}
4647function get(collection, key, notSetValue) {
4648 return isImmutable(collection)
4649 ? collection.get(key, notSetValue)
4650 : !has(collection, key)
4651 ? notSetValue
4652 : typeof collection.get === 'function'
4653 ? collection.get(key)
4654 : collection[key];
4655}
4656function shallowCopy(from) {
4657 if (Array.isArray(from)) {
4658 return arrCopy(from);
4659 }
4660 var to = {};
4661 for (var key in from) {
4662 if (hasOwnProperty.call(from, key)) {
4663 to[key] = from[key];
4664 }
4665 }
4666 return to;
4667}
4668function remove(collection, key) {
4669 if (!isDataStructure(collection)) {
4670 throw new TypeError('Cannot update non-data-structure value: ' + collection);
4671 }
4672 if (isImmutable(collection)) {
4673 if (!collection.remove) {
4674 throw new TypeError('Cannot update immutable value without .remove() method: ' + collection);
4675 }
4676 return collection.remove(key);
4677 }
4678 if (!hasOwnProperty.call(collection, key)) {
4679 return collection;
4680 }
4681 var collectionCopy = shallowCopy(collection);
4682 if (Array.isArray(collectionCopy)) {
4683 collectionCopy.splice(key, 1);
4684 }
4685 else {
4686 delete collectionCopy[key];
4687 }
4688 return collectionCopy;
4689}
4690function set(collection, key, value) {
4691 if (!isDataStructure(collection)) {
4692 throw new TypeError('Cannot update non-data-structure value: ' + collection);
4693 }
4694 if (isImmutable(collection)) {
4695 if (!collection.set) {
4696 throw new TypeError('Cannot update immutable value without .set() method: ' + collection);
4697 }
4698 return collection.set(key, value);
4699 }
4700 if (hasOwnProperty.call(collection, key) && value === collection[key]) {
4701 return collection;
4702 }
4703 var collectionCopy = shallowCopy(collection);
4704 collectionCopy[key] = value;
4705 return collectionCopy;
4706}
4707function updateIn(collection, keyPath, notSetValue, updater) {
4708 if (!updater) {
4709 updater = notSetValue;
4710 notSetValue = undefined;
4711 }
4712 var updatedValue = updateInDeeply(isImmutable(collection), collection, coerceKeyPath(keyPath), 0, notSetValue, updater);
4713 return updatedValue === NOT_SET ? notSetValue : updatedValue;
4714}
4715function updateInDeeply(inImmutable, existing, keyPath, i, notSetValue, updater) {
4716 var wasNotSet = existing === NOT_SET;
4717 if (i === keyPath.length) {
4718 var existingValue = wasNotSet ? notSetValue : existing;
4719 var newValue = updater(existingValue);
4720 return newValue === existingValue ? existing : newValue;
4721 }
4722 if (!wasNotSet && !isDataStructure(existing)) {
4723 throw new TypeError('Cannot update within non-data-structure value in path [' +
4724 keyPath.slice(0, i).map(quoteString) +
4725 ']: ' +
4726 existing);
4727 }
4728 var key = keyPath[i];
4729 var nextExisting = wasNotSet ? NOT_SET : get(existing, key, NOT_SET);
4730 var nextUpdated = updateInDeeply(nextExisting === NOT_SET ? inImmutable : isImmutable(nextExisting), nextExisting, keyPath, i + 1, notSetValue, updater);
4731 return nextUpdated === nextExisting
4732 ? existing
4733 : nextUpdated === NOT_SET
4734 ? remove(existing, key)
4735 : set(wasNotSet ? (inImmutable ? emptyMap() : {}) : existing, key, nextUpdated);
4736}
4737function setIn(collection, keyPath, value) {
4738 return updateIn(collection, keyPath, NOT_SET, function () { return value; });
4739}
4740function setIn$1(keyPath, v) {
4741 return setIn(this, keyPath, v);
4742}
4743function removeIn(collection, keyPath) {
4744 return updateIn(collection, keyPath, function () { return NOT_SET; });
4745}
4746function deleteIn(keyPath) {
4747 return removeIn(this, keyPath);
4748}
4749function update(collection, key, notSetValue, updater) {
4750 return updateIn(collection, [key], notSetValue, updater);
4751}
4752function update$1(key, notSetValue, updater) {
4753 return arguments.length === 1
4754 ? key(this)
4755 : update(this, key, notSetValue, updater);
4756}
4757function updateIn$1(keyPath, notSetValue, updater) {
4758 return updateIn(this, keyPath, notSetValue, updater);
4759}
4760function merge() {
4761 var iters = [], len = arguments.length;
4762 while (len--)
4763 iters[len] = arguments[len];
4764 return mergeIntoKeyedWith(this, iters);
4765}
4766function mergeWith(merger) {
4767 var iters = [], len = arguments.length - 1;
4768 while (len-- > 0)
4769 iters[len] = arguments[len + 1];
4770 if (typeof merger !== 'function') {
4771 throw new TypeError('Invalid merger function: ' + merger);
4772 }
4773 return mergeIntoKeyedWith(this, iters, merger);
4774}
4775function mergeIntoKeyedWith(collection, collections, merger) {
4776 var iters = [];
4777 for (var ii = 0; ii < collections.length; ii++) {
4778 var collection$1 = KeyedCollection(collections[ii]);
4779 if (collection$1.size !== 0) {
4780 iters.push(collection$1);
4781 }
4782 }
4783 if (iters.length === 0) {
4784 return collection;
4785 }
4786 if (collection.toSeq().size === 0 &&
4787 !collection.__ownerID &&
4788 iters.length === 1) {
4789 return collection.constructor(iters[0]);
4790 }
4791 return collection.withMutations(function (collection) {
4792 var mergeIntoCollection = merger
4793 ? function (value, key) {
4794 update(collection, key, NOT_SET, function (oldVal) { return (oldVal === NOT_SET ? value : merger(oldVal, value, key)); });
4795 }
4796 : function (value, key) {
4797 collection.set(key, value);
4798 };
4799 for (var ii = 0; ii < iters.length; ii++) {
4800 iters[ii].forEach(mergeIntoCollection);
4801 }
4802 });
4803}
4804function merge$1(collection) {
4805 var sources = [], len = arguments.length - 1;
4806 while (len-- > 0)
4807 sources[len] = arguments[len + 1];
4808 return mergeWithSources(collection, sources);
4809}
4810function mergeWith$1(merger, collection) {
4811 var sources = [], len = arguments.length - 2;
4812 while (len-- > 0)
4813 sources[len] = arguments[len + 2];
4814 return mergeWithSources(collection, sources, merger);
4815}
4816function mergeDeep(collection) {
4817 var sources = [], len = arguments.length - 1;
4818 while (len-- > 0)
4819 sources[len] = arguments[len + 1];
4820 return mergeDeepWithSources(collection, sources);
4821}
4822function mergeDeepWith(merger, collection) {
4823 var sources = [], len = arguments.length - 2;
4824 while (len-- > 0)
4825 sources[len] = arguments[len + 2];
4826 return mergeDeepWithSources(collection, sources, merger);
4827}
4828function mergeDeepWithSources(collection, sources, merger) {
4829 return mergeWithSources(collection, sources, deepMergerWith(merger));
4830}
4831function mergeWithSources(collection, sources, merger) {
4832 if (!isDataStructure(collection)) {
4833 throw new TypeError('Cannot merge into non-data-structure value: ' + collection);
4834 }
4835 if (isImmutable(collection)) {
4836 return typeof merger === 'function' && collection.mergeWith
4837 ? collection.mergeWith.apply(collection, [merger].concat(sources))
4838 : collection.merge
4839 ? collection.merge.apply(collection, sources)
4840 : collection.concat.apply(collection, sources);
4841 }
4842 var isArray = Array.isArray(collection);
4843 var merged = collection;
4844 var Collection$$1 = isArray ? IndexedCollection : KeyedCollection;
4845 var mergeItem = isArray
4846 ? function (value) {
4847 // Copy on write
4848 if (merged === collection) {
4849 merged = shallowCopy(merged);
4850 }
4851 merged.push(value);
4852 }
4853 : function (value, key) {
4854 var hasVal = hasOwnProperty.call(merged, key);
4855 var nextVal = hasVal && merger ? merger(merged[key], value, key) : value;
4856 if (!hasVal || nextVal !== merged[key]) {
4857 // Copy on write
4858 if (merged === collection) {
4859 merged = shallowCopy(merged);
4860 }
4861 merged[key] = nextVal;
4862 }
4863 };
4864 for (var i = 0; i < sources.length; i++) {
4865 Collection$$1(sources[i]).forEach(mergeItem);
4866 }
4867 return merged;
4868}
4869function deepMergerWith(merger) {
4870 function deepMerger(oldValue, newValue, key) {
4871 return isDataStructure(oldValue) && isDataStructure(newValue)
4872 ? mergeWithSources(oldValue, [newValue], deepMerger)
4873 : merger
4874 ? merger(oldValue, newValue, key)
4875 : newValue;
4876 }
4877 return deepMerger;
4878}
4879function mergeDeep$1() {
4880 var iters = [], len = arguments.length;
4881 while (len--)
4882 iters[len] = arguments[len];
4883 return mergeDeepWithSources(this, iters);
4884}
4885function mergeDeepWith$1(merger) {
4886 var iters = [], len = arguments.length - 1;
4887 while (len-- > 0)
4888 iters[len] = arguments[len + 1];
4889 return mergeDeepWithSources(this, iters, merger);
4890}
4891function mergeIn(keyPath) {
4892 var iters = [], len = arguments.length - 1;
4893 while (len-- > 0)
4894 iters[len] = arguments[len + 1];
4895 return updateIn(this, keyPath, emptyMap(), function (m) { return mergeWithSources(m, iters); });
4896}
4897function mergeDeepIn(keyPath) {
4898 var iters = [], len = arguments.length - 1;
4899 while (len-- > 0)
4900 iters[len] = arguments[len + 1];
4901 return updateIn(this, keyPath, emptyMap(), function (m) { return mergeDeepWithSources(m, iters); });
4902}
4903function withMutations(fn) {
4904 var mutable = this.asMutable();
4905 fn(mutable);
4906 return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this;
4907}
4908function asMutable() {
4909 return this.__ownerID ? this : this.__ensureOwner(new OwnerID());
4910}
4911function asImmutable() {
4912 return this.__ensureOwner();
4913}
4914function wasAltered() {
4915 return this.__altered;
4916}
4917var Map$1 = /*@__PURE__*/ (function (KeyedCollection$$1) {
4918 function Map(value) {
4919 return value === null || value === undefined
4920 ? emptyMap()
4921 : isMap(value) && !isOrdered(value)
4922 ? value
4923 : emptyMap().withMutations(function (map) {
4924 var iter = KeyedCollection$$1(value);
4925 assertNotInfinite(iter.size);
4926 iter.forEach(function (v, k) { return map.set(k, v); });
4927 });
4928 }
4929 if (KeyedCollection$$1)
4930 Map.__proto__ = KeyedCollection$$1;
4931 Map.prototype = Object.create(KeyedCollection$$1 && KeyedCollection$$1.prototype);
4932 Map.prototype.constructor = Map;
4933 Map.of = function of() {
4934 var keyValues = [], len = arguments.length;
4935 while (len--)
4936 keyValues[len] = arguments[len];
4937 return emptyMap().withMutations(function (map) {
4938 for (var i = 0; i < keyValues.length; i += 2) {
4939 if (i + 1 >= keyValues.length) {
4940 throw new Error('Missing value for key: ' + keyValues[i]);
4941 }
4942 map.set(keyValues[i], keyValues[i + 1]);
4943 }
4944 });
4945 };
4946 Map.prototype.toString = function toString() {
4947 return this.__toString('Map {', '}');
4948 };
4949 // @pragma Access
4950 Map.prototype.get = function get(k, notSetValue) {
4951 return this._root
4952 ? this._root.get(0, undefined, k, notSetValue)
4953 : notSetValue;
4954 };
4955 // @pragma Modification
4956 Map.prototype.set = function set(k, v) {
4957 return updateMap(this, k, v);
4958 };
4959 Map.prototype.remove = function remove(k) {
4960 return updateMap(this, k, NOT_SET);
4961 };
4962 Map.prototype.deleteAll = function deleteAll(keys) {
4963 var collection = Collection(keys);
4964 if (collection.size === 0) {
4965 return this;
4966 }
4967 return this.withMutations(function (map) {
4968 collection.forEach(function (key) { return map.remove(key); });
4969 });
4970 };
4971 Map.prototype.clear = function clear() {
4972 if (this.size === 0) {
4973 return this;
4974 }
4975 if (this.__ownerID) {
4976 this.size = 0;
4977 this._root = null;
4978 this.__hash = undefined;
4979 this.__altered = true;
4980 return this;
4981 }
4982 return emptyMap();
4983 };
4984 // @pragma Composition
4985 Map.prototype.sort = function sort(comparator) {
4986 // Late binding
4987 return OrderedMap(sortFactory(this, comparator));
4988 };
4989 Map.prototype.sortBy = function sortBy(mapper, comparator) {
4990 // Late binding
4991 return OrderedMap(sortFactory(this, comparator, mapper));
4992 };
4993 Map.prototype.map = function map(mapper, context) {
4994 return this.withMutations(function (map) {
4995 map.forEach(function (value, key) {
4996 map.set(key, mapper.call(context, value, key, map));
4997 });
4998 });
4999 };
5000 // @pragma Mutability
5001 Map.prototype.__iterator = function __iterator(type, reverse) {
5002 return new MapIterator(this, type, reverse);
5003 };
5004 Map.prototype.__iterate = function __iterate(fn, reverse) {
5005 var this$1 = this;
5006 var iterations = 0;
5007 this._root &&
5008 this._root.iterate(function (entry) {
5009 iterations++;
5010 return fn(entry[1], entry[0], this$1);
5011 }, reverse);
5012 return iterations;
5013 };
5014 Map.prototype.__ensureOwner = function __ensureOwner(ownerID) {
5015 if (ownerID === this.__ownerID) {
5016 return this;
5017 }
5018 if (!ownerID) {
5019 if (this.size === 0) {
5020 return emptyMap();
5021 }
5022 this.__ownerID = ownerID;
5023 this.__altered = false;
5024 return this;
5025 }
5026 return makeMap(this.size, this._root, ownerID, this.__hash);
5027 };
5028 return Map;
5029}(KeyedCollection));
5030Map$1.isMap = isMap;
5031var MapPrototype = Map$1.prototype;
5032MapPrototype[IS_MAP_SYMBOL] = true;
5033MapPrototype[DELETE] = MapPrototype.remove;
5034MapPrototype.removeAll = MapPrototype.deleteAll;
5035MapPrototype.setIn = setIn$1;
5036MapPrototype.removeIn = MapPrototype.deleteIn = deleteIn;
5037MapPrototype.update = update$1;
5038MapPrototype.updateIn = updateIn$1;
5039MapPrototype.merge = MapPrototype.concat = merge;
5040MapPrototype.mergeWith = mergeWith;
5041MapPrototype.mergeDeep = mergeDeep$1;
5042MapPrototype.mergeDeepWith = mergeDeepWith$1;
5043MapPrototype.mergeIn = mergeIn;
5044MapPrototype.mergeDeepIn = mergeDeepIn;
5045MapPrototype.withMutations = withMutations;
5046MapPrototype.wasAltered = wasAltered;
5047MapPrototype.asImmutable = asImmutable;
5048MapPrototype['@@transducer/init'] = MapPrototype.asMutable = asMutable;
5049MapPrototype['@@transducer/step'] = function (result, arr) {
5050 return result.set(arr[0], arr[1]);
5051};
5052MapPrototype['@@transducer/result'] = function (obj) {
5053 return obj.asImmutable();
5054};
5055// #pragma Trie Nodes
5056var ArrayMapNode = function ArrayMapNode(ownerID, entries) {
5057 this.ownerID = ownerID;
5058 this.entries = entries;
5059};
5060ArrayMapNode.prototype.get = function get(shift, keyHash, key, notSetValue) {
5061 var entries = this.entries;
5062 for (var ii = 0, len = entries.length; ii < len; ii++) {
5063 if (is(key, entries[ii][0])) {
5064 return entries[ii][1];
5065 }
5066 }
5067 return notSetValue;
5068};
5069ArrayMapNode.prototype.update = function update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
5070 var removed = value === NOT_SET;
5071 var entries = this.entries;
5072 var idx = 0;
5073 var len = entries.length;
5074 for (; idx < len; idx++) {
5075 if (is(key, entries[idx][0])) {
5076 break;
5077 }
5078 }
5079 var exists = idx < len;
5080 if (exists ? entries[idx][1] === value : removed) {
5081 return this;
5082 }
5083 SetRef(didAlter);
5084 (removed || !exists) && SetRef(didChangeSize);
5085 if (removed && entries.length === 1) {
5086 return; // undefined
5087 }
5088 if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) {
5089 return createNodes(ownerID, entries, key, value);
5090 }
5091 var isEditable = ownerID && ownerID === this.ownerID;
5092 var newEntries = isEditable ? entries : arrCopy(entries);
5093 if (exists) {
5094 if (removed) {
5095 idx === len - 1
5096 ? newEntries.pop()
5097 : (newEntries[idx] = newEntries.pop());
5098 }
5099 else {
5100 newEntries[idx] = [key, value];
5101 }
5102 }
5103 else {
5104 newEntries.push([key, value]);
5105 }
5106 if (isEditable) {
5107 this.entries = newEntries;
5108 return this;
5109 }
5110 return new ArrayMapNode(ownerID, newEntries);
5111};
5112var BitmapIndexedNode = function BitmapIndexedNode(ownerID, bitmap, nodes) {
5113 this.ownerID = ownerID;
5114 this.bitmap = bitmap;
5115 this.nodes = nodes;
5116};
5117BitmapIndexedNode.prototype.get = function get(shift, keyHash, key, notSetValue) {
5118 if (keyHash === undefined) {
5119 keyHash = hash(key);
5120 }
5121 var bit = 1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK);
5122 var bitmap = this.bitmap;
5123 return (bitmap & bit) === 0
5124 ? notSetValue
5125 : this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue);
5126};
5127BitmapIndexedNode.prototype.update = function update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
5128 if (keyHash === undefined) {
5129 keyHash = hash(key);
5130 }
5131 var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
5132 var bit = 1 << keyHashFrag;
5133 var bitmap = this.bitmap;
5134 var exists = (bitmap & bit) !== 0;
5135 if (!exists && value === NOT_SET) {
5136 return this;
5137 }
5138 var idx = popCount(bitmap & (bit - 1));
5139 var nodes = this.nodes;
5140 var node = exists ? nodes[idx] : undefined;
5141 var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter);
5142 if (newNode === node) {
5143 return this;
5144 }
5145 if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) {
5146 return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode);
5147 }
5148 if (exists &&
5149 !newNode &&
5150 nodes.length === 2 &&
5151 isLeafNode(nodes[idx ^ 1])) {
5152 return nodes[idx ^ 1];
5153 }
5154 if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) {
5155 return newNode;
5156 }
5157 var isEditable = ownerID && ownerID === this.ownerID;
5158 var newBitmap = exists ? (newNode ? bitmap : bitmap ^ bit) : bitmap | bit;
5159 var newNodes = exists
5160 ? newNode
5161 ? setAt(nodes, idx, newNode, isEditable)
5162 : spliceOut(nodes, idx, isEditable)
5163 : spliceIn(nodes, idx, newNode, isEditable);
5164 if (isEditable) {
5165 this.bitmap = newBitmap;
5166 this.nodes = newNodes;
5167 return this;
5168 }
5169 return new BitmapIndexedNode(ownerID, newBitmap, newNodes);
5170};
5171var HashArrayMapNode = function HashArrayMapNode(ownerID, count, nodes) {
5172 this.ownerID = ownerID;
5173 this.count = count;
5174 this.nodes = nodes;
5175};
5176HashArrayMapNode.prototype.get = function get(shift, keyHash, key, notSetValue) {
5177 if (keyHash === undefined) {
5178 keyHash = hash(key);
5179 }
5180 var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
5181 var node = this.nodes[idx];
5182 return node
5183 ? node.get(shift + SHIFT, keyHash, key, notSetValue)
5184 : notSetValue;
5185};
5186HashArrayMapNode.prototype.update = function update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
5187 if (keyHash === undefined) {
5188 keyHash = hash(key);
5189 }
5190 var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
5191 var removed = value === NOT_SET;
5192 var nodes = this.nodes;
5193 var node = nodes[idx];
5194 if (removed && !node) {
5195 return this;
5196 }
5197 var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter);
5198 if (newNode === node) {
5199 return this;
5200 }
5201 var newCount = this.count;
5202 if (!node) {
5203 newCount++;
5204 }
5205 else if (!newNode) {
5206 newCount--;
5207 if (newCount < MIN_HASH_ARRAY_MAP_SIZE) {
5208 return packNodes(ownerID, nodes, newCount, idx);
5209 }
5210 }
5211 var isEditable = ownerID && ownerID === this.ownerID;
5212 var newNodes = setAt(nodes, idx, newNode, isEditable);
5213 if (isEditable) {
5214 this.count = newCount;
5215 this.nodes = newNodes;
5216 return this;
5217 }
5218 return new HashArrayMapNode(ownerID, newCount, newNodes);
5219};
5220var HashCollisionNode = function HashCollisionNode(ownerID, keyHash, entries) {
5221 this.ownerID = ownerID;
5222 this.keyHash = keyHash;
5223 this.entries = entries;
5224};
5225HashCollisionNode.prototype.get = function get(shift, keyHash, key, notSetValue) {
5226 var entries = this.entries;
5227 for (var ii = 0, len = entries.length; ii < len; ii++) {
5228 if (is(key, entries[ii][0])) {
5229 return entries[ii][1];
5230 }
5231 }
5232 return notSetValue;
5233};
5234HashCollisionNode.prototype.update = function update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
5235 if (keyHash === undefined) {
5236 keyHash = hash(key);
5237 }
5238 var removed = value === NOT_SET;
5239 if (keyHash !== this.keyHash) {
5240 if (removed) {
5241 return this;
5242 }
5243 SetRef(didAlter);
5244 SetRef(didChangeSize);
5245 return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]);
5246 }
5247 var entries = this.entries;
5248 var idx = 0;
5249 var len = entries.length;
5250 for (; idx < len; idx++) {
5251 if (is(key, entries[idx][0])) {
5252 break;
5253 }
5254 }
5255 var exists = idx < len;
5256 if (exists ? entries[idx][1] === value : removed) {
5257 return this;
5258 }
5259 SetRef(didAlter);
5260 (removed || !exists) && SetRef(didChangeSize);
5261 if (removed && len === 2) {
5262 return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]);
5263 }
5264 var isEditable = ownerID && ownerID === this.ownerID;
5265 var newEntries = isEditable ? entries : arrCopy(entries);
5266 if (exists) {
5267 if (removed) {
5268 idx === len - 1
5269 ? newEntries.pop()
5270 : (newEntries[idx] = newEntries.pop());
5271 }
5272 else {
5273 newEntries[idx] = [key, value];
5274 }
5275 }
5276 else {
5277 newEntries.push([key, value]);
5278 }
5279 if (isEditable) {
5280 this.entries = newEntries;
5281 return this;
5282 }
5283 return new HashCollisionNode(ownerID, this.keyHash, newEntries);
5284};
5285var ValueNode = function ValueNode(ownerID, keyHash, entry) {
5286 this.ownerID = ownerID;
5287 this.keyHash = keyHash;
5288 this.entry = entry;
5289};
5290ValueNode.prototype.get = function get(shift, keyHash, key, notSetValue) {
5291 return is(key, this.entry[0]) ? this.entry[1] : notSetValue;
5292};
5293ValueNode.prototype.update = function update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
5294 var removed = value === NOT_SET;
5295 var keyMatch = is(key, this.entry[0]);
5296 if (keyMatch ? value === this.entry[1] : removed) {
5297 return this;
5298 }
5299 SetRef(didAlter);
5300 if (removed) {
5301 SetRef(didChangeSize);
5302 return; // undefined
5303 }
5304 if (keyMatch) {
5305 if (ownerID && ownerID === this.ownerID) {
5306 this.entry[1] = value;
5307 return this;
5308 }
5309 return new ValueNode(ownerID, this.keyHash, [key, value]);
5310 }
5311 SetRef(didChangeSize);
5312 return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]);
5313};
5314// #pragma Iterators
5315ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate = function (fn, reverse) {
5316 var entries = this.entries;
5317 for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) {
5318 if (fn(entries[reverse ? maxIndex - ii : ii]) === false) {
5319 return false;
5320 }
5321 }
5322};
5323BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate = function (fn, reverse) {
5324 var nodes = this.nodes;
5325 for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) {
5326 var node = nodes[reverse ? maxIndex - ii : ii];
5327 if (node && node.iterate(fn, reverse) === false) {
5328 return false;
5329 }
5330 }
5331};
5332// eslint-disable-next-line no-unused-vars
5333ValueNode.prototype.iterate = function (fn, reverse) {
5334 return fn(this.entry);
5335};
5336var MapIterator = /*@__PURE__*/ (function (Iterator$$1) {
5337 function MapIterator(map, type, reverse) {
5338 this._type = type;
5339 this._reverse = reverse;
5340 this._stack = map._root && mapIteratorFrame(map._root);
5341 }
5342 if (Iterator$$1)
5343 MapIterator.__proto__ = Iterator$$1;
5344 MapIterator.prototype = Object.create(Iterator$$1 && Iterator$$1.prototype);
5345 MapIterator.prototype.constructor = MapIterator;
5346 MapIterator.prototype.next = function next() {
5347 var type = this._type;
5348 var stack = this._stack;
5349 while (stack) {
5350 var node = stack.node;
5351 var index = stack.index++;
5352 var maxIndex = (void 0);
5353 if (node.entry) {
5354 if (index === 0) {
5355 return mapIteratorValue(type, node.entry);
5356 }
5357 }
5358 else if (node.entries) {
5359 maxIndex = node.entries.length - 1;
5360 if (index <= maxIndex) {
5361 return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]);
5362 }
5363 }
5364 else {
5365 maxIndex = node.nodes.length - 1;
5366 if (index <= maxIndex) {
5367 var subNode = node.nodes[this._reverse ? maxIndex - index : index];
5368 if (subNode) {
5369 if (subNode.entry) {
5370 return mapIteratorValue(type, subNode.entry);
5371 }
5372 stack = this._stack = mapIteratorFrame(subNode, stack);
5373 }
5374 continue;
5375 }
5376 }
5377 stack = this._stack = this._stack.__prev;
5378 }
5379 return iteratorDone();
5380 };
5381 return MapIterator;
5382}(Iterator));
5383function mapIteratorValue(type, entry) {
5384 return iteratorValue(type, entry[0], entry[1]);
5385}
5386function mapIteratorFrame(node, prev) {
5387 return {
5388 node: node,
5389 index: 0,
5390 __prev: prev,
5391 };
5392}
5393function makeMap(size, root, ownerID, hash$$1) {
5394 var map = Object.create(MapPrototype);
5395 map.size = size;
5396 map._root = root;
5397 map.__ownerID = ownerID;
5398 map.__hash = hash$$1;
5399 map.__altered = false;
5400 return map;
5401}
5402var EMPTY_MAP;
5403function emptyMap() {
5404 return EMPTY_MAP || (EMPTY_MAP = makeMap(0));
5405}
5406function updateMap(map, k, v) {
5407 var newRoot;
5408 var newSize;
5409 if (!map._root) {
5410 if (v === NOT_SET) {
5411 return map;
5412 }
5413 newSize = 1;
5414 newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]);
5415 }
5416 else {
5417 var didChangeSize = MakeRef();
5418 var didAlter = MakeRef();
5419 newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter);
5420 if (!didAlter.value) {
5421 return map;
5422 }
5423 newSize = map.size + (didChangeSize.value ? (v === NOT_SET ? -1 : 1) : 0);
5424 }
5425 if (map.__ownerID) {
5426 map.size = newSize;
5427 map._root = newRoot;
5428 map.__hash = undefined;
5429 map.__altered = true;
5430 return map;
5431 }
5432 return newRoot ? makeMap(newSize, newRoot) : emptyMap();
5433}
5434function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
5435 if (!node) {
5436 if (value === NOT_SET) {
5437 return node;
5438 }
5439 SetRef(didAlter);
5440 SetRef(didChangeSize);
5441 return new ValueNode(ownerID, keyHash, [key, value]);
5442 }
5443 return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter);
5444}
5445function isLeafNode(node) {
5446 return (node.constructor === ValueNode || node.constructor === HashCollisionNode);
5447}
5448function mergeIntoNode(node, ownerID, shift, keyHash, entry) {
5449 if (node.keyHash === keyHash) {
5450 return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]);
5451 }
5452 var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK;
5453 var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
5454 var newNode;
5455 var nodes = idx1 === idx2
5456 ? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)]
5457 : ((newNode = new ValueNode(ownerID, keyHash, entry)),
5458 idx1 < idx2 ? [node, newNode] : [newNode, node]);
5459 return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes);
5460}
5461function createNodes(ownerID, entries, key, value) {
5462 if (!ownerID) {
5463 ownerID = new OwnerID();
5464 }
5465 var node = new ValueNode(ownerID, hash(key), [key, value]);
5466 for (var ii = 0; ii < entries.length; ii++) {
5467 var entry = entries[ii];
5468 node = node.update(ownerID, 0, undefined, entry[0], entry[1]);
5469 }
5470 return node;
5471}
5472function packNodes(ownerID, nodes, count, excluding) {
5473 var bitmap = 0;
5474 var packedII = 0;
5475 var packedNodes = new Array(count);
5476 for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) {
5477 var node = nodes[ii];
5478 if (node !== undefined && ii !== excluding) {
5479 bitmap |= bit;
5480 packedNodes[packedII++] = node;
5481 }
5482 }
5483 return new BitmapIndexedNode(ownerID, bitmap, packedNodes);
5484}
5485function expandNodes(ownerID, nodes, bitmap, including, node) {
5486 var count = 0;
5487 var expandedNodes = new Array(SIZE);
5488 for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) {
5489 expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined;
5490 }
5491 expandedNodes[including] = node;
5492 return new HashArrayMapNode(ownerID, count + 1, expandedNodes);
5493}
5494function popCount(x) {
5495 x -= (x >> 1) & 0x55555555;
5496 x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
5497 x = (x + (x >> 4)) & 0x0f0f0f0f;
5498 x += x >> 8;
5499 x += x >> 16;
5500 return x & 0x7f;
5501}
5502function setAt(array, idx, val, canEdit) {
5503 var newArray = canEdit ? array : arrCopy(array);
5504 newArray[idx] = val;
5505 return newArray;
5506}
5507function spliceIn(array, idx, val, canEdit) {
5508 var newLen = array.length + 1;
5509 if (canEdit && idx + 1 === newLen) {
5510 array[idx] = val;
5511 return array;
5512 }
5513 var newArray = new Array(newLen);
5514 var after = 0;
5515 for (var ii = 0; ii < newLen; ii++) {
5516 if (ii === idx) {
5517 newArray[ii] = val;
5518 after = -1;
5519 }
5520 else {
5521 newArray[ii] = array[ii + after];
5522 }
5523 }
5524 return newArray;
5525}
5526function spliceOut(array, idx, canEdit) {
5527 var newLen = array.length - 1;
5528 if (canEdit && idx === newLen) {
5529 array.pop();
5530 return array;
5531 }
5532 var newArray = new Array(newLen);
5533 var after = 0;
5534 for (var ii = 0; ii < newLen; ii++) {
5535 if (ii === idx) {
5536 after = 1;
5537 }
5538 newArray[ii] = array[ii + after];
5539 }
5540 return newArray;
5541}
5542var MAX_ARRAY_MAP_SIZE = SIZE / 4;
5543var MAX_BITMAP_INDEXED_SIZE = SIZE / 2;
5544var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4;
5545var IS_LIST_SYMBOL = '@@__IMMUTABLE_LIST__@@';
5546function isList(maybeList) {
5547 return Boolean(maybeList && maybeList[IS_LIST_SYMBOL]);
5548}
5549var List = /*@__PURE__*/ (function (IndexedCollection$$1) {
5550 function List(value) {
5551 var empty = emptyList();
5552 if (value === null || value === undefined) {
5553 return empty;
5554 }
5555 if (isList(value)) {
5556 return value;
5557 }
5558 var iter = IndexedCollection$$1(value);
5559 var size = iter.size;
5560 if (size === 0) {
5561 return empty;
5562 }
5563 assertNotInfinite(size);
5564 if (size > 0 && size < SIZE) {
5565 return makeList(0, size, SHIFT, null, new VNode(iter.toArray()));
5566 }
5567 return empty.withMutations(function (list) {
5568 list.setSize(size);
5569 iter.forEach(function (v, i) { return list.set(i, v); });
5570 });
5571 }
5572 if (IndexedCollection$$1)
5573 List.__proto__ = IndexedCollection$$1;
5574 List.prototype = Object.create(IndexedCollection$$1 && IndexedCollection$$1.prototype);
5575 List.prototype.constructor = List;
5576 List.of = function of( /*...values*/) {
5577 return this(arguments);
5578 };
5579 List.prototype.toString = function toString() {
5580 return this.__toString('List [', ']');
5581 };
5582 // @pragma Access
5583 List.prototype.get = function get(index, notSetValue) {
5584 index = wrapIndex(this, index);
5585 if (index >= 0 && index < this.size) {
5586 index += this._origin;
5587 var node = listNodeFor(this, index);
5588 return node && node.array[index & MASK];
5589 }
5590 return notSetValue;
5591 };
5592 // @pragma Modification
5593 List.prototype.set = function set(index, value) {
5594 return updateList(this, index, value);
5595 };
5596 List.prototype.remove = function remove(index) {
5597 return !this.has(index)
5598 ? this
5599 : index === 0
5600 ? this.shift()
5601 : index === this.size - 1
5602 ? this.pop()
5603 : this.splice(index, 1);
5604 };
5605 List.prototype.insert = function insert(index, value) {
5606 return this.splice(index, 0, value);
5607 };
5608 List.prototype.clear = function clear() {
5609 if (this.size === 0) {
5610 return this;
5611 }
5612 if (this.__ownerID) {
5613 this.size = this._origin = this._capacity = 0;
5614 this._level = SHIFT;
5615 this._root = this._tail = null;
5616 this.__hash = undefined;
5617 this.__altered = true;
5618 return this;
5619 }
5620 return emptyList();
5621 };
5622 List.prototype.push = function push( /*...values*/) {
5623 var values = arguments;
5624 var oldSize = this.size;
5625 return this.withMutations(function (list) {
5626 setListBounds(list, 0, oldSize + values.length);
5627 for (var ii = 0; ii < values.length; ii++) {
5628 list.set(oldSize + ii, values[ii]);
5629 }
5630 });
5631 };
5632 List.prototype.pop = function pop() {
5633 return setListBounds(this, 0, -1);
5634 };
5635 List.prototype.unshift = function unshift( /*...values*/) {
5636 var values = arguments;
5637 return this.withMutations(function (list) {
5638 setListBounds(list, -values.length);
5639 for (var ii = 0; ii < values.length; ii++) {
5640 list.set(ii, values[ii]);
5641 }
5642 });
5643 };
5644 List.prototype.shift = function shift() {
5645 return setListBounds(this, 1);
5646 };
5647 // @pragma Composition
5648 List.prototype.concat = function concat( /*...collections*/) {
5649 var arguments$1 = arguments;
5650 var seqs = [];
5651 for (var i = 0; i < arguments.length; i++) {
5652 var argument = arguments$1[i];
5653 var seq = IndexedCollection$$1(typeof argument !== 'string' && hasIterator(argument)
5654 ? argument
5655 : [argument]);
5656 if (seq.size !== 0) {
5657 seqs.push(seq);
5658 }
5659 }
5660 if (seqs.length === 0) {
5661 return this;
5662 }
5663 if (this.size === 0 && !this.__ownerID && seqs.length === 1) {
5664 return this.constructor(seqs[0]);
5665 }
5666 return this.withMutations(function (list) {
5667 seqs.forEach(function (seq) { return seq.forEach(function (value) { return list.push(value); }); });
5668 });
5669 };
5670 List.prototype.setSize = function setSize(size) {
5671 return setListBounds(this, 0, size);
5672 };
5673 List.prototype.map = function map(mapper, context) {
5674 var this$1 = this;
5675 return this.withMutations(function (list) {
5676 for (var i = 0; i < this$1.size; i++) {
5677 list.set(i, mapper.call(context, list.get(i), i, list));
5678 }
5679 });
5680 };
5681 // @pragma Iteration
5682 List.prototype.slice = function slice(begin, end) {
5683 var size = this.size;
5684 if (wholeSlice(begin, end, size)) {
5685 return this;
5686 }
5687 return setListBounds(this, resolveBegin(begin, size), resolveEnd(end, size));
5688 };
5689 List.prototype.__iterator = function __iterator(type, reverse) {
5690 var index = reverse ? this.size : 0;
5691 var values = iterateList(this, reverse);
5692 return new Iterator(function () {
5693 var value = values();
5694 return value === DONE
5695 ? iteratorDone()
5696 : iteratorValue(type, reverse ? --index : index++, value);
5697 });
5698 };
5699 List.prototype.__iterate = function __iterate(fn, reverse) {
5700 var index = reverse ? this.size : 0;
5701 var values = iterateList(this, reverse);
5702 var value;
5703 while ((value = values()) !== DONE) {
5704 if (fn(value, reverse ? --index : index++, this) === false) {
5705 break;
5706 }
5707 }
5708 return index;
5709 };
5710 List.prototype.__ensureOwner = function __ensureOwner(ownerID) {
5711 if (ownerID === this.__ownerID) {
5712 return this;
5713 }
5714 if (!ownerID) {
5715 if (this.size === 0) {
5716 return emptyList();
5717 }
5718 this.__ownerID = ownerID;
5719 this.__altered = false;
5720 return this;
5721 }
5722 return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash);
5723 };
5724 return List;
5725}(IndexedCollection));
5726List.isList = isList;
5727var ListPrototype = List.prototype;
5728ListPrototype[IS_LIST_SYMBOL] = true;
5729ListPrototype[DELETE] = ListPrototype.remove;
5730ListPrototype.merge = ListPrototype.concat;
5731ListPrototype.setIn = setIn$1;
5732ListPrototype.deleteIn = ListPrototype.removeIn = deleteIn;
5733ListPrototype.update = update$1;
5734ListPrototype.updateIn = updateIn$1;
5735ListPrototype.mergeIn = mergeIn;
5736ListPrototype.mergeDeepIn = mergeDeepIn;
5737ListPrototype.withMutations = withMutations;
5738ListPrototype.wasAltered = wasAltered;
5739ListPrototype.asImmutable = asImmutable;
5740ListPrototype['@@transducer/init'] = ListPrototype.asMutable = asMutable;
5741ListPrototype['@@transducer/step'] = function (result, arr) {
5742 return result.push(arr);
5743};
5744ListPrototype['@@transducer/result'] = function (obj) {
5745 return obj.asImmutable();
5746};
5747var VNode = function VNode(array, ownerID) {
5748 this.array = array;
5749 this.ownerID = ownerID;
5750};
5751// TODO: seems like these methods are very similar
5752VNode.prototype.removeBefore = function removeBefore(ownerID, level, index) {
5753 if (index === level ? 1 << level : this.array.length === 0) {
5754 return this;
5755 }
5756 var originIndex = (index >>> level) & MASK;
5757 if (originIndex >= this.array.length) {
5758 return new VNode([], ownerID);
5759 }
5760 var removingFirst = originIndex === 0;
5761 var newChild;
5762 if (level > 0) {
5763 var oldChild = this.array[originIndex];
5764 newChild =
5765 oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index);
5766 if (newChild === oldChild && removingFirst) {
5767 return this;
5768 }
5769 }
5770 if (removingFirst && !newChild) {
5771 return this;
5772 }
5773 var editable = editableVNode(this, ownerID);
5774 if (!removingFirst) {
5775 for (var ii = 0; ii < originIndex; ii++) {
5776 editable.array[ii] = undefined;
5777 }
5778 }
5779 if (newChild) {
5780 editable.array[originIndex] = newChild;
5781 }
5782 return editable;
5783};
5784VNode.prototype.removeAfter = function removeAfter(ownerID, level, index) {
5785 if (index === (level ? 1 << level : 0) || this.array.length === 0) {
5786 return this;
5787 }
5788 var sizeIndex = ((index - 1) >>> level) & MASK;
5789 if (sizeIndex >= this.array.length) {
5790 return this;
5791 }
5792 var newChild;
5793 if (level > 0) {
5794 var oldChild = this.array[sizeIndex];
5795 newChild =
5796 oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index);
5797 if (newChild === oldChild && sizeIndex === this.array.length - 1) {
5798 return this;
5799 }
5800 }
5801 var editable = editableVNode(this, ownerID);
5802 editable.array.splice(sizeIndex + 1);
5803 if (newChild) {
5804 editable.array[sizeIndex] = newChild;
5805 }
5806 return editable;
5807};
5808var DONE = {};
5809function iterateList(list, reverse) {
5810 var left = list._origin;
5811 var right = list._capacity;
5812 var tailPos = getTailOffset(right);
5813 var tail = list._tail;
5814 return iterateNodeOrLeaf(list._root, list._level, 0);
5815 function iterateNodeOrLeaf(node, level, offset) {
5816 return level === 0
5817 ? iterateLeaf(node, offset)
5818 : iterateNode(node, level, offset);
5819 }
5820 function iterateLeaf(node, offset) {
5821 var array = offset === tailPos ? tail && tail.array : node && node.array;
5822 var from = offset > left ? 0 : left - offset;
5823 var to = right - offset;
5824 if (to > SIZE) {
5825 to = SIZE;
5826 }
5827 return function () {
5828 if (from === to) {
5829 return DONE;
5830 }
5831 var idx = reverse ? --to : from++;
5832 return array && array[idx];
5833 };
5834 }
5835 function iterateNode(node, level, offset) {
5836 var values;
5837 var array = node && node.array;
5838 var from = offset > left ? 0 : (left - offset) >> level;
5839 var to = ((right - offset) >> level) + 1;
5840 if (to > SIZE) {
5841 to = SIZE;
5842 }
5843 return function () {
5844 while (true) {
5845 if (values) {
5846 var value = values();
5847 if (value !== DONE) {
5848 return value;
5849 }
5850 values = null;
5851 }
5852 if (from === to) {
5853 return DONE;
5854 }
5855 var idx = reverse ? --to : from++;
5856 values = iterateNodeOrLeaf(array && array[idx], level - SHIFT, offset + (idx << level));
5857 }
5858 };
5859 }
5860}
5861function makeList(origin, capacity, level, root, tail, ownerID, hash) {
5862 var list = Object.create(ListPrototype);
5863 list.size = capacity - origin;
5864 list._origin = origin;
5865 list._capacity = capacity;
5866 list._level = level;
5867 list._root = root;
5868 list._tail = tail;
5869 list.__ownerID = ownerID;
5870 list.__hash = hash;
5871 list.__altered = false;
5872 return list;
5873}
5874var EMPTY_LIST;
5875function emptyList() {
5876 return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT));
5877}
5878function updateList(list, index, value) {
5879 index = wrapIndex(list, index);
5880 if (index !== index) {
5881 return list;
5882 }
5883 if (index >= list.size || index < 0) {
5884 return list.withMutations(function (list) {
5885 index < 0
5886 ? setListBounds(list, index).set(0, value)
5887 : setListBounds(list, 0, index + 1).set(index, value);
5888 });
5889 }
5890 index += list._origin;
5891 var newTail = list._tail;
5892 var newRoot = list._root;
5893 var didAlter = MakeRef();
5894 if (index >= getTailOffset(list._capacity)) {
5895 newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter);
5896 }
5897 else {
5898 newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter);
5899 }
5900 if (!didAlter.value) {
5901 return list;
5902 }
5903 if (list.__ownerID) {
5904 list._root = newRoot;
5905 list._tail = newTail;
5906 list.__hash = undefined;
5907 list.__altered = true;
5908 return list;
5909 }
5910 return makeList(list._origin, list._capacity, list._level, newRoot, newTail);
5911}
5912function updateVNode(node, ownerID, level, index, value, didAlter) {
5913 var idx = (index >>> level) & MASK;
5914 var nodeHas = node && idx < node.array.length;
5915 if (!nodeHas && value === undefined) {
5916 return node;
5917 }
5918 var newNode;
5919 if (level > 0) {
5920 var lowerNode = node && node.array[idx];
5921 var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter);
5922 if (newLowerNode === lowerNode) {
5923 return node;
5924 }
5925 newNode = editableVNode(node, ownerID);
5926 newNode.array[idx] = newLowerNode;
5927 return newNode;
5928 }
5929 if (nodeHas && node.array[idx] === value) {
5930 return node;
5931 }
5932 if (didAlter) {
5933 SetRef(didAlter);
5934 }
5935 newNode = editableVNode(node, ownerID);
5936 if (value === undefined && idx === newNode.array.length - 1) {
5937 newNode.array.pop();
5938 }
5939 else {
5940 newNode.array[idx] = value;
5941 }
5942 return newNode;
5943}
5944function editableVNode(node, ownerID) {
5945 if (ownerID && node && ownerID === node.ownerID) {
5946 return node;
5947 }
5948 return new VNode(node ? node.array.slice() : [], ownerID);
5949}
5950function listNodeFor(list, rawIndex) {
5951 if (rawIndex >= getTailOffset(list._capacity)) {
5952 return list._tail;
5953 }
5954 if (rawIndex < 1 << (list._level + SHIFT)) {
5955 var node = list._root;
5956 var level = list._level;
5957 while (node && level > 0) {
5958 node = node.array[(rawIndex >>> level) & MASK];
5959 level -= SHIFT;
5960 }
5961 return node;
5962 }
5963}
5964function setListBounds(list, begin, end) {
5965 // Sanitize begin & end using this shorthand for ToInt32(argument)
5966 // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
5967 if (begin !== undefined) {
5968 begin |= 0;
5969 }
5970 if (end !== undefined) {
5971 end |= 0;
5972 }
5973 var owner = list.__ownerID || new OwnerID();
5974 var oldOrigin = list._origin;
5975 var oldCapacity = list._capacity;
5976 var newOrigin = oldOrigin + begin;
5977 var newCapacity = end === undefined
5978 ? oldCapacity
5979 : end < 0
5980 ? oldCapacity + end
5981 : oldOrigin + end;
5982 if (newOrigin === oldOrigin && newCapacity === oldCapacity) {
5983 return list;
5984 }
5985 // If it's going to end after it starts, it's empty.
5986 if (newOrigin >= newCapacity) {
5987 return list.clear();
5988 }
5989 var newLevel = list._level;
5990 var newRoot = list._root;
5991 // New origin might need creating a higher root.
5992 var offsetShift = 0;
5993 while (newOrigin + offsetShift < 0) {
5994 newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner);
5995 newLevel += SHIFT;
5996 offsetShift += 1 << newLevel;
5997 }
5998 if (offsetShift) {
5999 newOrigin += offsetShift;
6000 oldOrigin += offsetShift;
6001 newCapacity += offsetShift;
6002 oldCapacity += offsetShift;
6003 }
6004 var oldTailOffset = getTailOffset(oldCapacity);
6005 var newTailOffset = getTailOffset(newCapacity);
6006 // New size might need creating a higher root.
6007 while (newTailOffset >= 1 << (newLevel + SHIFT)) {
6008 newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner);
6009 newLevel += SHIFT;
6010 }
6011 // Locate or create the new tail.
6012 var oldTail = list._tail;
6013 var newTail = newTailOffset < oldTailOffset
6014 ? listNodeFor(list, newCapacity - 1)
6015 : newTailOffset > oldTailOffset
6016 ? new VNode([], owner)
6017 : oldTail;
6018 // Merge Tail into tree.
6019 if (oldTail &&
6020 newTailOffset > oldTailOffset &&
6021 newOrigin < oldCapacity &&
6022 oldTail.array.length) {
6023 newRoot = editableVNode(newRoot, owner);
6024 var node = newRoot;
6025 for (var level = newLevel; level > SHIFT; level -= SHIFT) {
6026 var idx = (oldTailOffset >>> level) & MASK;
6027 node = node.array[idx] = editableVNode(node.array[idx], owner);
6028 }
6029 node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail;
6030 }
6031 // If the size has been reduced, there's a chance the tail needs to be trimmed.
6032 if (newCapacity < oldCapacity) {
6033 newTail = newTail && newTail.removeAfter(owner, 0, newCapacity);
6034 }
6035 // If the new origin is within the tail, then we do not need a root.
6036 if (newOrigin >= newTailOffset) {
6037 newOrigin -= newTailOffset;
6038 newCapacity -= newTailOffset;
6039 newLevel = SHIFT;
6040 newRoot = null;
6041 newTail = newTail && newTail.removeBefore(owner, 0, newOrigin);
6042 // Otherwise, if the root has been trimmed, garbage collect.
6043 }
6044 else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) {
6045 offsetShift = 0;
6046 // Identify the new top root node of the subtree of the old root.
6047 while (newRoot) {
6048 var beginIndex = (newOrigin >>> newLevel) & MASK;
6049 if ((beginIndex !== newTailOffset >>> newLevel) & MASK) {
6050 break;
6051 }
6052 if (beginIndex) {
6053 offsetShift += (1 << newLevel) * beginIndex;
6054 }
6055 newLevel -= SHIFT;
6056 newRoot = newRoot.array[beginIndex];
6057 }
6058 // Trim the new sides of the new root.
6059 if (newRoot && newOrigin > oldOrigin) {
6060 newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift);
6061 }
6062 if (newRoot && newTailOffset < oldTailOffset) {
6063 newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift);
6064 }
6065 if (offsetShift) {
6066 newOrigin -= offsetShift;
6067 newCapacity -= offsetShift;
6068 }
6069 }
6070 if (list.__ownerID) {
6071 list.size = newCapacity - newOrigin;
6072 list._origin = newOrigin;
6073 list._capacity = newCapacity;
6074 list._level = newLevel;
6075 list._root = newRoot;
6076 list._tail = newTail;
6077 list.__hash = undefined;
6078 list.__altered = true;
6079 return list;
6080 }
6081 return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail);
6082}
6083function getTailOffset(size) {
6084 return size < SIZE ? 0 : ((size - 1) >>> SHIFT) << SHIFT;
6085}
6086var OrderedMap = /*@__PURE__*/ (function (Map$$1) {
6087 function OrderedMap(value) {
6088 return value === null || value === undefined
6089 ? emptyOrderedMap()
6090 : isOrderedMap(value)
6091 ? value
6092 : emptyOrderedMap().withMutations(function (map) {
6093 var iter = KeyedCollection(value);
6094 assertNotInfinite(iter.size);
6095 iter.forEach(function (v, k) { return map.set(k, v); });
6096 });
6097 }
6098 if (Map$$1)
6099 OrderedMap.__proto__ = Map$$1;
6100 OrderedMap.prototype = Object.create(Map$$1 && Map$$1.prototype);
6101 OrderedMap.prototype.constructor = OrderedMap;
6102 OrderedMap.of = function of( /*...values*/) {
6103 return this(arguments);
6104 };
6105 OrderedMap.prototype.toString = function toString() {
6106 return this.__toString('OrderedMap {', '}');
6107 };
6108 // @pragma Access
6109 OrderedMap.prototype.get = function get(k, notSetValue) {
6110 var index = this._map.get(k);
6111 return index !== undefined ? this._list.get(index)[1] : notSetValue;
6112 };
6113 // @pragma Modification
6114 OrderedMap.prototype.clear = function clear() {
6115 if (this.size === 0) {
6116 return this;
6117 }
6118 if (this.__ownerID) {
6119 this.size = 0;
6120 this._map.clear();
6121 this._list.clear();
6122 return this;
6123 }
6124 return emptyOrderedMap();
6125 };
6126 OrderedMap.prototype.set = function set(k, v) {
6127 return updateOrderedMap(this, k, v);
6128 };
6129 OrderedMap.prototype.remove = function remove(k) {
6130 return updateOrderedMap(this, k, NOT_SET);
6131 };
6132 OrderedMap.prototype.wasAltered = function wasAltered() {
6133 return this._map.wasAltered() || this._list.wasAltered();
6134 };
6135 OrderedMap.prototype.__iterate = function __iterate(fn, reverse) {
6136 var this$1 = this;
6137 return this._list.__iterate(function (entry) { return entry && fn(entry[1], entry[0], this$1); }, reverse);
6138 };
6139 OrderedMap.prototype.__iterator = function __iterator(type, reverse) {
6140 return this._list.fromEntrySeq().__iterator(type, reverse);
6141 };
6142 OrderedMap.prototype.__ensureOwner = function __ensureOwner(ownerID) {
6143 if (ownerID === this.__ownerID) {
6144 return this;
6145 }
6146 var newMap = this._map.__ensureOwner(ownerID);
6147 var newList = this._list.__ensureOwner(ownerID);
6148 if (!ownerID) {
6149 if (this.size === 0) {
6150 return emptyOrderedMap();
6151 }
6152 this.__ownerID = ownerID;
6153 this._map = newMap;
6154 this._list = newList;
6155 return this;
6156 }
6157 return makeOrderedMap(newMap, newList, ownerID, this.__hash);
6158 };
6159 return OrderedMap;
6160}(Map$1));
6161OrderedMap.isOrderedMap = isOrderedMap;
6162OrderedMap.prototype[IS_ORDERED_SYMBOL] = true;
6163OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove;
6164function makeOrderedMap(map, list, ownerID, hash) {
6165 var omap = Object.create(OrderedMap.prototype);
6166 omap.size = map ? map.size : 0;
6167 omap._map = map;
6168 omap._list = list;
6169 omap.__ownerID = ownerID;
6170 omap.__hash = hash;
6171 return omap;
6172}
6173var EMPTY_ORDERED_MAP;
6174function emptyOrderedMap() {
6175 return (EMPTY_ORDERED_MAP ||
6176 (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList())));
6177}
6178function updateOrderedMap(omap, k, v) {
6179 var map = omap._map;
6180 var list = omap._list;
6181 var i = map.get(k);
6182 var has = i !== undefined;
6183 var newMap;
6184 var newList;
6185 if (v === NOT_SET) {
6186 // removed
6187 if (!has) {
6188 return omap;
6189 }
6190 if (list.size >= SIZE && list.size >= map.size * 2) {
6191 newList = list.filter(function (entry, idx) { return entry !== undefined && i !== idx; });
6192 newMap = newList
6193 .toKeyedSeq()
6194 .map(function (entry) { return entry[0]; })
6195 .flip()
6196 .toMap();
6197 if (omap.__ownerID) {
6198 newMap.__ownerID = newList.__ownerID = omap.__ownerID;
6199 }
6200 }
6201 else {
6202 newMap = map.remove(k);
6203 newList = i === list.size - 1 ? list.pop() : list.set(i, undefined);
6204 }
6205 }
6206 else if (has) {
6207 if (v === list.get(i)[1]) {
6208 return omap;
6209 }
6210 newMap = map;
6211 newList = list.set(i, [k, v]);
6212 }
6213 else {
6214 newMap = map.set(k, list.size);
6215 newList = list.set(list.size, [k, v]);
6216 }
6217 if (omap.__ownerID) {
6218 omap.size = newMap.size;
6219 omap._map = newMap;
6220 omap._list = newList;
6221 omap.__hash = undefined;
6222 return omap;
6223 }
6224 return makeOrderedMap(newMap, newList);
6225}
6226var IS_STACK_SYMBOL = '@@__IMMUTABLE_STACK__@@';
6227function isStack(maybeStack) {
6228 return Boolean(maybeStack && maybeStack[IS_STACK_SYMBOL]);
6229}
6230var Stack = /*@__PURE__*/ (function (IndexedCollection$$1) {
6231 function Stack(value) {
6232 return value === null || value === undefined
6233 ? emptyStack()
6234 : isStack(value)
6235 ? value
6236 : emptyStack().pushAll(value);
6237 }
6238 if (IndexedCollection$$1)
6239 Stack.__proto__ = IndexedCollection$$1;
6240 Stack.prototype = Object.create(IndexedCollection$$1 && IndexedCollection$$1.prototype);
6241 Stack.prototype.constructor = Stack;
6242 Stack.of = function of( /*...values*/) {
6243 return this(arguments);
6244 };
6245 Stack.prototype.toString = function toString() {
6246 return this.__toString('Stack [', ']');
6247 };
6248 // @pragma Access
6249 Stack.prototype.get = function get(index, notSetValue) {
6250 var head = this._head;
6251 index = wrapIndex(this, index);
6252 while (head && index--) {
6253 head = head.next;
6254 }
6255 return head ? head.value : notSetValue;
6256 };
6257 Stack.prototype.peek = function peek() {
6258 return this._head && this._head.value;
6259 };
6260 // @pragma Modification
6261 Stack.prototype.push = function push( /*...values*/) {
6262 var arguments$1 = arguments;
6263 if (arguments.length === 0) {
6264 return this;
6265 }
6266 var newSize = this.size + arguments.length;
6267 var head = this._head;
6268 for (var ii = arguments.length - 1; ii >= 0; ii--) {
6269 head = {
6270 value: arguments$1[ii],
6271 next: head,
6272 };
6273 }
6274 if (this.__ownerID) {
6275 this.size = newSize;
6276 this._head = head;
6277 this.__hash = undefined;
6278 this.__altered = true;
6279 return this;
6280 }
6281 return makeStack(newSize, head);
6282 };
6283 Stack.prototype.pushAll = function pushAll(iter) {
6284 iter = IndexedCollection$$1(iter);
6285 if (iter.size === 0) {
6286 return this;
6287 }
6288 if (this.size === 0 && isStack(iter)) {
6289 return iter;
6290 }
6291 assertNotInfinite(iter.size);
6292 var newSize = this.size;
6293 var head = this._head;
6294 iter.__iterate(function (value) {
6295 newSize++;
6296 head = {
6297 value: value,
6298 next: head,
6299 };
6300 }, /* reverse */ true);
6301 if (this.__ownerID) {
6302 this.size = newSize;
6303 this._head = head;
6304 this.__hash = undefined;
6305 this.__altered = true;
6306 return this;
6307 }
6308 return makeStack(newSize, head);
6309 };
6310 Stack.prototype.pop = function pop() {
6311 return this.slice(1);
6312 };
6313 Stack.prototype.clear = function clear() {
6314 if (this.size === 0) {
6315 return this;
6316 }
6317 if (this.__ownerID) {
6318 this.size = 0;
6319 this._head = undefined;
6320 this.__hash = undefined;
6321 this.__altered = true;
6322 return this;
6323 }
6324 return emptyStack();
6325 };
6326 Stack.prototype.slice = function slice(begin, end) {
6327 if (wholeSlice(begin, end, this.size)) {
6328 return this;
6329 }
6330 var resolvedBegin = resolveBegin(begin, this.size);
6331 var resolvedEnd = resolveEnd(end, this.size);
6332 if (resolvedEnd !== this.size) {
6333 // super.slice(begin, end);
6334 return IndexedCollection$$1.prototype.slice.call(this, begin, end);
6335 }
6336 var newSize = this.size - resolvedBegin;
6337 var head = this._head;
6338 while (resolvedBegin--) {
6339 head = head.next;
6340 }
6341 if (this.__ownerID) {
6342 this.size = newSize;
6343 this._head = head;
6344 this.__hash = undefined;
6345 this.__altered = true;
6346 return this;
6347 }
6348 return makeStack(newSize, head);
6349 };
6350 // @pragma Mutability
6351 Stack.prototype.__ensureOwner = function __ensureOwner(ownerID) {
6352 if (ownerID === this.__ownerID) {
6353 return this;
6354 }
6355 if (!ownerID) {
6356 if (this.size === 0) {
6357 return emptyStack();
6358 }
6359 this.__ownerID = ownerID;
6360 this.__altered = false;
6361 return this;
6362 }
6363 return makeStack(this.size, this._head, ownerID, this.__hash);
6364 };
6365 // @pragma Iteration
6366 Stack.prototype.__iterate = function __iterate(fn, reverse) {
6367 var this$1 = this;
6368 if (reverse) {
6369 return new ArraySeq(this.toArray()).__iterate(function (v, k) { return fn(v, k, this$1); }, reverse);
6370 }
6371 var iterations = 0;
6372 var node = this._head;
6373 while (node) {
6374 if (fn(node.value, iterations++, this) === false) {
6375 break;
6376 }
6377 node = node.next;
6378 }
6379 return iterations;
6380 };
6381 Stack.prototype.__iterator = function __iterator(type, reverse) {
6382 if (reverse) {
6383 return new ArraySeq(this.toArray()).__iterator(type, reverse);
6384 }
6385 var iterations = 0;
6386 var node = this._head;
6387 return new Iterator(function () {
6388 if (node) {
6389 var value = node.value;
6390 node = node.next;
6391 return iteratorValue(type, iterations++, value);
6392 }
6393 return iteratorDone();
6394 });
6395 };
6396 return Stack;
6397}(IndexedCollection));
6398Stack.isStack = isStack;
6399var StackPrototype = Stack.prototype;
6400StackPrototype[IS_STACK_SYMBOL] = true;
6401StackPrototype.shift = StackPrototype.pop;
6402StackPrototype.unshift = StackPrototype.push;
6403StackPrototype.unshiftAll = StackPrototype.pushAll;
6404StackPrototype.withMutations = withMutations;
6405StackPrototype.wasAltered = wasAltered;
6406StackPrototype.asImmutable = asImmutable;
6407StackPrototype['@@transducer/init'] = StackPrototype.asMutable = asMutable;
6408StackPrototype['@@transducer/step'] = function (result, arr) {
6409 return result.unshift(arr);
6410};
6411StackPrototype['@@transducer/result'] = function (obj) {
6412 return obj.asImmutable();
6413};
6414function makeStack(size, head, ownerID, hash) {
6415 var map = Object.create(StackPrototype);
6416 map.size = size;
6417 map._head = head;
6418 map.__ownerID = ownerID;
6419 map.__hash = hash;
6420 map.__altered = false;
6421 return map;
6422}
6423var EMPTY_STACK;
6424function emptyStack() {
6425 return EMPTY_STACK || (EMPTY_STACK = makeStack(0));
6426}
6427var IS_SET_SYMBOL = '@@__IMMUTABLE_SET__@@';
6428function isSet(maybeSet) {
6429 return Boolean(maybeSet && maybeSet[IS_SET_SYMBOL]);
6430}
6431function isOrderedSet(maybeOrderedSet) {
6432 return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet);
6433}
6434function deepEqual(a, b) {
6435 if (a === b) {
6436 return true;
6437 }
6438 if (!isCollection(b) ||
6439 (a.size !== undefined && b.size !== undefined && a.size !== b.size) ||
6440 (a.__hash !== undefined &&
6441 b.__hash !== undefined &&
6442 a.__hash !== b.__hash) ||
6443 isKeyed(a) !== isKeyed(b) ||
6444 isIndexed(a) !== isIndexed(b) ||
6445 isOrdered(a) !== isOrdered(b)) {
6446 return false;
6447 }
6448 if (a.size === 0 && b.size === 0) {
6449 return true;
6450 }
6451 var notAssociative = !isAssociative(a);
6452 if (isOrdered(a)) {
6453 var entries = a.entries();
6454 return (b.every(function (v, k) {
6455 var entry = entries.next().value;
6456 return entry && is(entry[1], v) && (notAssociative || is(entry[0], k));
6457 }) && entries.next().done);
6458 }
6459 var flipped = false;
6460 if (a.size === undefined) {
6461 if (b.size === undefined) {
6462 if (typeof a.cacheResult === 'function') {
6463 a.cacheResult();
6464 }
6465 }
6466 else {
6467 flipped = true;
6468 var _ = a;
6469 a = b;
6470 b = _;
6471 }
6472 }
6473 var allEqual = true;
6474 var bSize = b.__iterate(function (v, k) {
6475 if (notAssociative
6476 ? !a.has(v)
6477 : flipped
6478 ? !is(v, a.get(k, NOT_SET))
6479 : !is(a.get(k, NOT_SET), v)) {
6480 allEqual = false;
6481 return false;
6482 }
6483 });
6484 return allEqual && a.size === bSize;
6485}
6486/**
6487 * Contributes additional methods to a constructor
6488 */
6489function mixin(ctor, methods) {
6490 var keyCopier = function (key) {
6491 ctor.prototype[key] = methods[key];
6492 };
6493 Object.keys(methods).forEach(keyCopier);
6494 Object.getOwnPropertySymbols &&
6495 Object.getOwnPropertySymbols(methods).forEach(keyCopier);
6496 return ctor;
6497}
6498function toJS(value) {
6499 if (!value || typeof value !== 'object') {
6500 return value;
6501 }
6502 if (!isCollection(value)) {
6503 if (!isDataStructure(value)) {
6504 return value;
6505 }
6506 value = Seq(value);
6507 }
6508 if (isKeyed(value)) {
6509 var result$1 = {};
6510 value.__iterate(function (v, k) {
6511 result$1[k] = toJS(v);
6512 });
6513 return result$1;
6514 }
6515 var result = [];
6516 value.__iterate(function (v) {
6517 result.push(toJS(v));
6518 });
6519 return result;
6520}
6521var Set$1 = /*@__PURE__*/ (function (SetCollection$$1) {
6522 function Set(value) {
6523 return value === null || value === undefined
6524 ? emptySet()
6525 : isSet(value) && !isOrdered(value)
6526 ? value
6527 : emptySet().withMutations(function (set) {
6528 var iter = SetCollection$$1(value);
6529 assertNotInfinite(iter.size);
6530 iter.forEach(function (v) { return set.add(v); });
6531 });
6532 }
6533 if (SetCollection$$1)
6534 Set.__proto__ = SetCollection$$1;
6535 Set.prototype = Object.create(SetCollection$$1 && SetCollection$$1.prototype);
6536 Set.prototype.constructor = Set;
6537 Set.of = function of( /*...values*/) {
6538 return this(arguments);
6539 };
6540 Set.fromKeys = function fromKeys(value) {
6541 return this(KeyedCollection(value).keySeq());
6542 };
6543 Set.intersect = function intersect(sets) {
6544 sets = Collection(sets).toArray();
6545 return sets.length
6546 ? SetPrototype.intersect.apply(Set(sets.pop()), sets)
6547 : emptySet();
6548 };
6549 Set.union = function union(sets) {
6550 sets = Collection(sets).toArray();
6551 return sets.length
6552 ? SetPrototype.union.apply(Set(sets.pop()), sets)
6553 : emptySet();
6554 };
6555 Set.prototype.toString = function toString() {
6556 return this.__toString('Set {', '}');
6557 };
6558 // @pragma Access
6559 Set.prototype.has = function has(value) {
6560 return this._map.has(value);
6561 };
6562 // @pragma Modification
6563 Set.prototype.add = function add(value) {
6564 return updateSet(this, this._map.set(value, value));
6565 };
6566 Set.prototype.remove = function remove(value) {
6567 return updateSet(this, this._map.remove(value));
6568 };
6569 Set.prototype.clear = function clear() {
6570 return updateSet(this, this._map.clear());
6571 };
6572 // @pragma Composition
6573 Set.prototype.map = function map(mapper, context) {
6574 var this$1 = this;
6575 var removes = [];
6576 var adds = [];
6577 this.forEach(function (value) {
6578 var mapped = mapper.call(context, value, value, this$1);
6579 if (mapped !== value) {
6580 removes.push(value);
6581 adds.push(mapped);
6582 }
6583 });
6584 return this.withMutations(function (set) {
6585 removes.forEach(function (value) { return set.remove(value); });
6586 adds.forEach(function (value) { return set.add(value); });
6587 });
6588 };
6589 Set.prototype.union = function union() {
6590 var iters = [], len = arguments.length;
6591 while (len--)
6592 iters[len] = arguments[len];
6593 iters = iters.filter(function (x) { return x.size !== 0; });
6594 if (iters.length === 0) {
6595 return this;
6596 }
6597 if (this.size === 0 && !this.__ownerID && iters.length === 1) {
6598 return this.constructor(iters[0]);
6599 }
6600 return this.withMutations(function (set) {
6601 for (var ii = 0; ii < iters.length; ii++) {
6602 SetCollection$$1(iters[ii]).forEach(function (value) { return set.add(value); });
6603 }
6604 });
6605 };
6606 Set.prototype.intersect = function intersect() {
6607 var iters = [], len = arguments.length;
6608 while (len--)
6609 iters[len] = arguments[len];
6610 if (iters.length === 0) {
6611 return this;
6612 }
6613 iters = iters.map(function (iter) { return SetCollection$$1(iter); });
6614 var toRemove = [];
6615 this.forEach(function (value) {
6616 if (!iters.every(function (iter) { return iter.includes(value); })) {
6617 toRemove.push(value);
6618 }
6619 });
6620 return this.withMutations(function (set) {
6621 toRemove.forEach(function (value) {
6622 set.remove(value);
6623 });
6624 });
6625 };
6626 Set.prototype.subtract = function subtract() {
6627 var iters = [], len = arguments.length;
6628 while (len--)
6629 iters[len] = arguments[len];
6630 if (iters.length === 0) {
6631 return this;
6632 }
6633 iters = iters.map(function (iter) { return SetCollection$$1(iter); });
6634 var toRemove = [];
6635 this.forEach(function (value) {
6636 if (iters.some(function (iter) { return iter.includes(value); })) {
6637 toRemove.push(value);
6638 }
6639 });
6640 return this.withMutations(function (set) {
6641 toRemove.forEach(function (value) {
6642 set.remove(value);
6643 });
6644 });
6645 };
6646 Set.prototype.sort = function sort(comparator) {
6647 // Late binding
6648 return OrderedSet(sortFactory(this, comparator));
6649 };
6650 Set.prototype.sortBy = function sortBy(mapper, comparator) {
6651 // Late binding
6652 return OrderedSet(sortFactory(this, comparator, mapper));
6653 };
6654 Set.prototype.wasAltered = function wasAltered() {
6655 return this._map.wasAltered();
6656 };
6657 Set.prototype.__iterate = function __iterate(fn, reverse) {
6658 var this$1 = this;
6659 return this._map.__iterate(function (k) { return fn(k, k, this$1); }, reverse);
6660 };
6661 Set.prototype.__iterator = function __iterator(type, reverse) {
6662 return this._map.__iterator(type, reverse);
6663 };
6664 Set.prototype.__ensureOwner = function __ensureOwner(ownerID) {
6665 if (ownerID === this.__ownerID) {
6666 return this;
6667 }
6668 var newMap = this._map.__ensureOwner(ownerID);
6669 if (!ownerID) {
6670 if (this.size === 0) {
6671 return this.__empty();
6672 }
6673 this.__ownerID = ownerID;
6674 this._map = newMap;
6675 return this;
6676 }
6677 return this.__make(newMap, ownerID);
6678 };
6679 return Set;
6680}(SetCollection));
6681Set$1.isSet = isSet;
6682var SetPrototype = Set$1.prototype;
6683SetPrototype[IS_SET_SYMBOL] = true;
6684SetPrototype[DELETE] = SetPrototype.remove;
6685SetPrototype.merge = SetPrototype.concat = SetPrototype.union;
6686SetPrototype.withMutations = withMutations;
6687SetPrototype.asImmutable = asImmutable;
6688SetPrototype['@@transducer/init'] = SetPrototype.asMutable = asMutable;
6689SetPrototype['@@transducer/step'] = function (result, arr) {
6690 return result.add(arr);
6691};
6692SetPrototype['@@transducer/result'] = function (obj) {
6693 return obj.asImmutable();
6694};
6695SetPrototype.__empty = emptySet;
6696SetPrototype.__make = makeSet;
6697function updateSet(set, newMap) {
6698 if (set.__ownerID) {
6699 set.size = newMap.size;
6700 set._map = newMap;
6701 return set;
6702 }
6703 return newMap === set._map
6704 ? set
6705 : newMap.size === 0
6706 ? set.__empty()
6707 : set.__make(newMap);
6708}
6709function makeSet(map, ownerID) {
6710 var set = Object.create(SetPrototype);
6711 set.size = map ? map.size : 0;
6712 set._map = map;
6713 set.__ownerID = ownerID;
6714 return set;
6715}
6716var EMPTY_SET;
6717function emptySet() {
6718 return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap()));
6719}
6720/**
6721 * Returns a lazy seq of nums from start (inclusive) to end
6722 * (exclusive), by step, where start defaults to 0, step to 1, and end to
6723 * infinity. When start is equal to end, returns empty list.
6724 */
6725var Range = /*@__PURE__*/ (function (IndexedSeq$$1) {
6726 function Range(start, end, step) {
6727 if (!(this instanceof Range)) {
6728 return new Range(start, end, step);
6729 }
6730 invariant(step !== 0, 'Cannot step a Range by 0');
6731 start = start || 0;
6732 if (end === undefined) {
6733 end = Infinity;
6734 }
6735 step = step === undefined ? 1 : Math.abs(step);
6736 if (end < start) {
6737 step = -step;
6738 }
6739 this._start = start;
6740 this._end = end;
6741 this._step = step;
6742 this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1);
6743 if (this.size === 0) {
6744 if (EMPTY_RANGE) {
6745 return EMPTY_RANGE;
6746 }
6747 EMPTY_RANGE = this;
6748 }
6749 }
6750 if (IndexedSeq$$1)
6751 Range.__proto__ = IndexedSeq$$1;
6752 Range.prototype = Object.create(IndexedSeq$$1 && IndexedSeq$$1.prototype);
6753 Range.prototype.constructor = Range;
6754 Range.prototype.toString = function toString() {
6755 if (this.size === 0) {
6756 return 'Range []';
6757 }
6758 return ('Range [ ' +
6759 this._start +
6760 '...' +
6761 this._end +
6762 (this._step !== 1 ? ' by ' + this._step : '') +
6763 ' ]');
6764 };
6765 Range.prototype.get = function get(index, notSetValue) {
6766 return this.has(index)
6767 ? this._start + wrapIndex(this, index) * this._step
6768 : notSetValue;
6769 };
6770 Range.prototype.includes = function includes(searchValue) {
6771 var possibleIndex = (searchValue - this._start) / this._step;
6772 return (possibleIndex >= 0 &&
6773 possibleIndex < this.size &&
6774 possibleIndex === Math.floor(possibleIndex));
6775 };
6776 Range.prototype.slice = function slice(begin, end) {
6777 if (wholeSlice(begin, end, this.size)) {
6778 return this;
6779 }
6780 begin = resolveBegin(begin, this.size);
6781 end = resolveEnd(end, this.size);
6782 if (end <= begin) {
6783 return new Range(0, 0);
6784 }
6785 return new Range(this.get(begin, this._end), this.get(end, this._end), this._step);
6786 };
6787 Range.prototype.indexOf = function indexOf(searchValue) {
6788 var offsetValue = searchValue - this._start;
6789 if (offsetValue % this._step === 0) {
6790 var index = offsetValue / this._step;
6791 if (index >= 0 && index < this.size) {
6792 return index;
6793 }
6794 }
6795 return -1;
6796 };
6797 Range.prototype.lastIndexOf = function lastIndexOf(searchValue) {
6798 return this.indexOf(searchValue);
6799 };
6800 Range.prototype.__iterate = function __iterate(fn, reverse) {
6801 var size = this.size;
6802 var step = this._step;
6803 var value = reverse ? this._start + (size - 1) * step : this._start;
6804 var i = 0;
6805 while (i !== size) {
6806 if (fn(value, reverse ? size - ++i : i++, this) === false) {
6807 break;
6808 }
6809 value += reverse ? -step : step;
6810 }
6811 return i;
6812 };
6813 Range.prototype.__iterator = function __iterator(type, reverse) {
6814 var size = this.size;
6815 var step = this._step;
6816 var value = reverse ? this._start + (size - 1) * step : this._start;
6817 var i = 0;
6818 return new Iterator(function () {
6819 if (i === size) {
6820 return iteratorDone();
6821 }
6822 var v = value;
6823 value += reverse ? -step : step;
6824 return iteratorValue(type, reverse ? size - ++i : i++, v);
6825 });
6826 };
6827 Range.prototype.equals = function equals(other) {
6828 return other instanceof Range
6829 ? this._start === other._start &&
6830 this._end === other._end &&
6831 this._step === other._step
6832 : deepEqual(this, other);
6833 };
6834 return Range;
6835}(IndexedSeq));
6836var EMPTY_RANGE;
6837function getIn(collection, searchKeyPath, notSetValue) {
6838 var keyPath = coerceKeyPath(searchKeyPath);
6839 var i = 0;
6840 while (i !== keyPath.length) {
6841 collection = get(collection, keyPath[i++], NOT_SET);
6842 if (collection === NOT_SET) {
6843 return notSetValue;
6844 }
6845 }
6846 return collection;
6847}
6848function getIn$1(searchKeyPath, notSetValue) {
6849 return getIn(this, searchKeyPath, notSetValue);
6850}
6851function hasIn(collection, keyPath) {
6852 return getIn(collection, keyPath, NOT_SET) !== NOT_SET;
6853}
6854function hasIn$1(searchKeyPath) {
6855 return hasIn(this, searchKeyPath);
6856}
6857function toObject() {
6858 assertNotInfinite(this.size);
6859 var object = {};
6860 this.__iterate(function (v, k) {
6861 object[k] = v;
6862 });
6863 return object;
6864}
6865// Note: all of these methods are deprecated.
6866Collection.isIterable = isCollection;
6867Collection.isKeyed = isKeyed;
6868Collection.isIndexed = isIndexed;
6869Collection.isAssociative = isAssociative;
6870Collection.isOrdered = isOrdered;
6871Collection.Iterator = Iterator;
6872mixin(Collection, {
6873 // ### Conversion to other types
6874 toArray: function toArray() {
6875 assertNotInfinite(this.size);
6876 var array = new Array(this.size || 0);
6877 var useTuples = isKeyed(this);
6878 var i = 0;
6879 this.__iterate(function (v, k) {
6880 // Keyed collections produce an array of tuples.
6881 array[i++] = useTuples ? [k, v] : v;
6882 });
6883 return array;
6884 },
6885 toIndexedSeq: function toIndexedSeq() {
6886 return new ToIndexedSequence(this);
6887 },
6888 toJS: function toJS$1() {
6889 return toJS(this);
6890 },
6891 toKeyedSeq: function toKeyedSeq() {
6892 return new ToKeyedSequence(this, true);
6893 },
6894 toMap: function toMap() {
6895 // Use Late Binding here to solve the circular dependency.
6896 return Map$1(this.toKeyedSeq());
6897 },
6898 toObject: toObject,
6899 toOrderedMap: function toOrderedMap() {
6900 // Use Late Binding here to solve the circular dependency.
6901 return OrderedMap(this.toKeyedSeq());
6902 },
6903 toOrderedSet: function toOrderedSet() {
6904 // Use Late Binding here to solve the circular dependency.
6905 return OrderedSet(isKeyed(this) ? this.valueSeq() : this);
6906 },
6907 toSet: function toSet() {
6908 // Use Late Binding here to solve the circular dependency.
6909 return Set$1(isKeyed(this) ? this.valueSeq() : this);
6910 },
6911 toSetSeq: function toSetSeq() {
6912 return new ToSetSequence(this);
6913 },
6914 toSeq: function toSeq() {
6915 return isIndexed(this)
6916 ? this.toIndexedSeq()
6917 : isKeyed(this)
6918 ? this.toKeyedSeq()
6919 : this.toSetSeq();
6920 },
6921 toStack: function toStack() {
6922 // Use Late Binding here to solve the circular dependency.
6923 return Stack(isKeyed(this) ? this.valueSeq() : this);
6924 },
6925 toList: function toList() {
6926 // Use Late Binding here to solve the circular dependency.
6927 return List(isKeyed(this) ? this.valueSeq() : this);
6928 },
6929 // ### Common JavaScript methods and properties
6930 toString: function toString() {
6931 return '[Collection]';
6932 },
6933 __toString: function __toString(head, tail) {
6934 if (this.size === 0) {
6935 return head + tail;
6936 }
6937 return (head +
6938 ' ' +
6939 this.toSeq()
6940 .map(this.__toStringMapper)
6941 .join(', ') +
6942 ' ' +
6943 tail);
6944 },
6945 // ### ES6 Collection methods (ES6 Array and Map)
6946 concat: function concat() {
6947 var values = [], len = arguments.length;
6948 while (len--)
6949 values[len] = arguments[len];
6950 return reify(this, concatFactory(this, values));
6951 },
6952 includes: function includes(searchValue) {
6953 return this.some(function (value) { return is(value, searchValue); });
6954 },
6955 entries: function entries() {
6956 return this.__iterator(ITERATE_ENTRIES);
6957 },
6958 every: function every(predicate, context) {
6959 assertNotInfinite(this.size);
6960 var returnValue = true;
6961 this.__iterate(function (v, k, c) {
6962 if (!predicate.call(context, v, k, c)) {
6963 returnValue = false;
6964 return false;
6965 }
6966 });
6967 return returnValue;
6968 },
6969 filter: function filter(predicate, context) {
6970 return reify(this, filterFactory(this, predicate, context, true));
6971 },
6972 find: function find(predicate, context, notSetValue) {
6973 var entry = this.findEntry(predicate, context);
6974 return entry ? entry[1] : notSetValue;
6975 },
6976 forEach: function forEach(sideEffect, context) {
6977 assertNotInfinite(this.size);
6978 return this.__iterate(context ? sideEffect.bind(context) : sideEffect);
6979 },
6980 join: function join(separator) {
6981 assertNotInfinite(this.size);
6982 separator = separator !== undefined ? '' + separator : ',';
6983 var joined = '';
6984 var isFirst = true;
6985 this.__iterate(function (v) {
6986 isFirst ? (isFirst = false) : (joined += separator);
6987 joined += v !== null && v !== undefined ? v.toString() : '';
6988 });
6989 return joined;
6990 },
6991 keys: function keys() {
6992 return this.__iterator(ITERATE_KEYS);
6993 },
6994 map: function map(mapper, context) {
6995 return reify(this, mapFactory(this, mapper, context));
6996 },
6997 reduce: function reduce$1(reducer, initialReduction, context) {
6998 return reduce(this, reducer, initialReduction, context, arguments.length < 2, false);
6999 },
7000 reduceRight: function reduceRight(reducer, initialReduction, context) {
7001 return reduce(this, reducer, initialReduction, context, arguments.length < 2, true);
7002 },
7003 reverse: function reverse() {
7004 return reify(this, reverseFactory(this, true));
7005 },
7006 slice: function slice(begin, end) {
7007 return reify(this, sliceFactory(this, begin, end, true));
7008 },
7009 some: function some(predicate, context) {
7010 return !this.every(not(predicate), context);
7011 },
7012 sort: function sort(comparator) {
7013 return reify(this, sortFactory(this, comparator));
7014 },
7015 values: function values() {
7016 return this.__iterator(ITERATE_VALUES);
7017 },
7018 // ### More sequential methods
7019 butLast: function butLast() {
7020 return this.slice(0, -1);
7021 },
7022 isEmpty: function isEmpty() {
7023 return this.size !== undefined ? this.size === 0 : !this.some(function () { return true; });
7024 },
7025 count: function count(predicate, context) {
7026 return ensureSize(predicate ? this.toSeq().filter(predicate, context) : this);
7027 },
7028 countBy: function countBy(grouper, context) {
7029 return countByFactory(this, grouper, context);
7030 },
7031 equals: function equals(other) {
7032 return deepEqual(this, other);
7033 },
7034 entrySeq: function entrySeq() {
7035 var collection = this;
7036 if (collection._cache) {
7037 // We cache as an entries array, so we can just return the cache!
7038 return new ArraySeq(collection._cache);
7039 }
7040 var entriesSequence = collection
7041 .toSeq()
7042 .map(entryMapper)
7043 .toIndexedSeq();
7044 entriesSequence.fromEntrySeq = function () { return collection.toSeq(); };
7045 return entriesSequence;
7046 },
7047 filterNot: function filterNot(predicate, context) {
7048 return this.filter(not(predicate), context);
7049 },
7050 findEntry: function findEntry(predicate, context, notSetValue) {
7051 var found = notSetValue;
7052 this.__iterate(function (v, k, c) {
7053 if (predicate.call(context, v, k, c)) {
7054 found = [k, v];
7055 return false;
7056 }
7057 });
7058 return found;
7059 },
7060 findKey: function findKey(predicate, context) {
7061 var entry = this.findEntry(predicate, context);
7062 return entry && entry[0];
7063 },
7064 findLast: function findLast(predicate, context, notSetValue) {
7065 return this.toKeyedSeq()
7066 .reverse()
7067 .find(predicate, context, notSetValue);
7068 },
7069 findLastEntry: function findLastEntry(predicate, context, notSetValue) {
7070 return this.toKeyedSeq()
7071 .reverse()
7072 .findEntry(predicate, context, notSetValue);
7073 },
7074 findLastKey: function findLastKey(predicate, context) {
7075 return this.toKeyedSeq()
7076 .reverse()
7077 .findKey(predicate, context);
7078 },
7079 first: function first(notSetValue) {
7080 return this.find(returnTrue, null, notSetValue);
7081 },
7082 flatMap: function flatMap(mapper, context) {
7083 return reify(this, flatMapFactory(this, mapper, context));
7084 },
7085 flatten: function flatten(depth) {
7086 return reify(this, flattenFactory(this, depth, true));
7087 },
7088 fromEntrySeq: function fromEntrySeq() {
7089 return new FromEntriesSequence(this);
7090 },
7091 get: function get(searchKey, notSetValue) {
7092 return this.find(function (_, key) { return is(key, searchKey); }, undefined, notSetValue);
7093 },
7094 getIn: getIn$1,
7095 groupBy: function groupBy(grouper, context) {
7096 return groupByFactory(this, grouper, context);
7097 },
7098 has: function has(searchKey) {
7099 return this.get(searchKey, NOT_SET) !== NOT_SET;
7100 },
7101 hasIn: hasIn$1,
7102 isSubset: function isSubset(iter) {
7103 iter = typeof iter.includes === 'function' ? iter : Collection(iter);
7104 return this.every(function (value) { return iter.includes(value); });
7105 },
7106 isSuperset: function isSuperset(iter) {
7107 iter = typeof iter.isSubset === 'function' ? iter : Collection(iter);
7108 return iter.isSubset(this);
7109 },
7110 keyOf: function keyOf(searchValue) {
7111 return this.findKey(function (value) { return is(value, searchValue); });
7112 },
7113 keySeq: function keySeq() {
7114 return this.toSeq()
7115 .map(keyMapper)
7116 .toIndexedSeq();
7117 },
7118 last: function last(notSetValue) {
7119 return this.toSeq()
7120 .reverse()
7121 .first(notSetValue);
7122 },
7123 lastKeyOf: function lastKeyOf(searchValue) {
7124 return this.toKeyedSeq()
7125 .reverse()
7126 .keyOf(searchValue);
7127 },
7128 max: function max(comparator) {
7129 return maxFactory(this, comparator);
7130 },
7131 maxBy: function maxBy(mapper, comparator) {
7132 return maxFactory(this, comparator, mapper);
7133 },
7134 min: function min(comparator) {
7135 return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator);
7136 },
7137 minBy: function minBy(mapper, comparator) {
7138 return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper);
7139 },
7140 rest: function rest() {
7141 return this.slice(1);
7142 },
7143 skip: function skip(amount) {
7144 return amount === 0 ? this : this.slice(Math.max(0, amount));
7145 },
7146 skipLast: function skipLast(amount) {
7147 return amount === 0 ? this : this.slice(0, -Math.max(0, amount));
7148 },
7149 skipWhile: function skipWhile(predicate, context) {
7150 return reify(this, skipWhileFactory(this, predicate, context, true));
7151 },
7152 skipUntil: function skipUntil(predicate, context) {
7153 return this.skipWhile(not(predicate), context);
7154 },
7155 sortBy: function sortBy(mapper, comparator) {
7156 return reify(this, sortFactory(this, comparator, mapper));
7157 },
7158 take: function take(amount) {
7159 return this.slice(0, Math.max(0, amount));
7160 },
7161 takeLast: function takeLast(amount) {
7162 return this.slice(-Math.max(0, amount));
7163 },
7164 takeWhile: function takeWhile(predicate, context) {
7165 return reify(this, takeWhileFactory(this, predicate, context));
7166 },
7167 takeUntil: function takeUntil(predicate, context) {
7168 return this.takeWhile(not(predicate), context);
7169 },
7170 update: function update(fn) {
7171 return fn(this);
7172 },
7173 valueSeq: function valueSeq() {
7174 return this.toIndexedSeq();
7175 },
7176 // ### Hashable Object
7177 hashCode: function hashCode() {
7178 return this.__hash || (this.__hash = hashCollection(this));
7179 },
7180});
7181var CollectionPrototype = Collection.prototype;
7182CollectionPrototype[IS_COLLECTION_SYMBOL] = true;
7183CollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.values;
7184CollectionPrototype.toJSON = CollectionPrototype.toArray;
7185CollectionPrototype.__toStringMapper = quoteString;
7186CollectionPrototype.inspect = CollectionPrototype.toSource = function () {
7187 return this.toString();
7188};
7189CollectionPrototype.chain = CollectionPrototype.flatMap;
7190CollectionPrototype.contains = CollectionPrototype.includes;
7191mixin(KeyedCollection, {
7192 // ### More sequential methods
7193 flip: function flip() {
7194 return reify(this, flipFactory(this));
7195 },
7196 mapEntries: function mapEntries(mapper, context) {
7197 var this$1 = this;
7198 var iterations = 0;
7199 return reify(this, this.toSeq()
7200 .map(function (v, k) { return mapper.call(context, [k, v], iterations++, this$1); })
7201 .fromEntrySeq());
7202 },
7203 mapKeys: function mapKeys(mapper, context) {
7204 var this$1 = this;
7205 return reify(this, this.toSeq()
7206 .flip()
7207 .map(function (k, v) { return mapper.call(context, k, v, this$1); })
7208 .flip());
7209 },
7210});
7211var KeyedCollectionPrototype = KeyedCollection.prototype;
7212KeyedCollectionPrototype[IS_KEYED_SYMBOL] = true;
7213KeyedCollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.entries;
7214KeyedCollectionPrototype.toJSON = toObject;
7215KeyedCollectionPrototype.__toStringMapper = function (v, k) { return quoteString(k) + ': ' + quoteString(v); };
7216mixin(IndexedCollection, {
7217 // ### Conversion to other types
7218 toKeyedSeq: function toKeyedSeq() {
7219 return new ToKeyedSequence(this, false);
7220 },
7221 // ### ES6 Collection methods (ES6 Array and Map)
7222 filter: function filter(predicate, context) {
7223 return reify(this, filterFactory(this, predicate, context, false));
7224 },
7225 findIndex: function findIndex(predicate, context) {
7226 var entry = this.findEntry(predicate, context);
7227 return entry ? entry[0] : -1;
7228 },
7229 indexOf: function indexOf(searchValue) {
7230 var key = this.keyOf(searchValue);
7231 return key === undefined ? -1 : key;
7232 },
7233 lastIndexOf: function lastIndexOf(searchValue) {
7234 var key = this.lastKeyOf(searchValue);
7235 return key === undefined ? -1 : key;
7236 },
7237 reverse: function reverse() {
7238 return reify(this, reverseFactory(this, false));
7239 },
7240 slice: function slice(begin, end) {
7241 return reify(this, sliceFactory(this, begin, end, false));
7242 },
7243 splice: function splice(index, removeNum /*, ...values*/) {
7244 var numArgs = arguments.length;
7245 removeNum = Math.max(removeNum || 0, 0);
7246 if (numArgs === 0 || (numArgs === 2 && !removeNum)) {
7247 return this;
7248 }
7249 // If index is negative, it should resolve relative to the size of the
7250 // collection. However size may be expensive to compute if not cached, so
7251 // only call count() if the number is in fact negative.
7252 index = resolveBegin(index, index < 0 ? this.count() : this.size);
7253 var spliced = this.slice(0, index);
7254 return reify(this, numArgs === 1
7255 ? spliced
7256 : spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum)));
7257 },
7258 // ### More collection methods
7259 findLastIndex: function findLastIndex(predicate, context) {
7260 var entry = this.findLastEntry(predicate, context);
7261 return entry ? entry[0] : -1;
7262 },
7263 first: function first(notSetValue) {
7264 return this.get(0, notSetValue);
7265 },
7266 flatten: function flatten(depth) {
7267 return reify(this, flattenFactory(this, depth, false));
7268 },
7269 get: function get(index, notSetValue) {
7270 index = wrapIndex(this, index);
7271 return index < 0 ||
7272 (this.size === Infinity || (this.size !== undefined && index > this.size))
7273 ? notSetValue
7274 : this.find(function (_, key) { return key === index; }, undefined, notSetValue);
7275 },
7276 has: function has(index) {
7277 index = wrapIndex(this, index);
7278 return (index >= 0 &&
7279 (this.size !== undefined
7280 ? this.size === Infinity || index < this.size
7281 : this.indexOf(index) !== -1));
7282 },
7283 interpose: function interpose(separator) {
7284 return reify(this, interposeFactory(this, separator));
7285 },
7286 interleave: function interleave( /*...collections*/) {
7287 var collections = [this].concat(arrCopy(arguments));
7288 var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, collections);
7289 var interleaved = zipped.flatten(true);
7290 if (zipped.size) {
7291 interleaved.size = zipped.size * collections.length;
7292 }
7293 return reify(this, interleaved);
7294 },
7295 keySeq: function keySeq() {
7296 return Range(0, this.size);
7297 },
7298 last: function last(notSetValue) {
7299 return this.get(-1, notSetValue);
7300 },
7301 skipWhile: function skipWhile(predicate, context) {
7302 return reify(this, skipWhileFactory(this, predicate, context, false));
7303 },
7304 zip: function zip( /*, ...collections */) {
7305 var collections = [this].concat(arrCopy(arguments));
7306 return reify(this, zipWithFactory(this, defaultZipper, collections));
7307 },
7308 zipAll: function zipAll( /*, ...collections */) {
7309 var collections = [this].concat(arrCopy(arguments));
7310 return reify(this, zipWithFactory(this, defaultZipper, collections, true));
7311 },
7312 zipWith: function zipWith(zipper /*, ...collections */) {
7313 var collections = arrCopy(arguments);
7314 collections[0] = this;
7315 return reify(this, zipWithFactory(this, zipper, collections));
7316 },
7317});
7318var IndexedCollectionPrototype = IndexedCollection.prototype;
7319IndexedCollectionPrototype[IS_INDEXED_SYMBOL] = true;
7320IndexedCollectionPrototype[IS_ORDERED_SYMBOL] = true;
7321mixin(SetCollection, {
7322 // ### ES6 Collection methods (ES6 Array and Map)
7323 get: function get(value, notSetValue) {
7324 return this.has(value) ? value : notSetValue;
7325 },
7326 includes: function includes(value) {
7327 return this.has(value);
7328 },
7329 // ### More sequential methods
7330 keySeq: function keySeq() {
7331 return this.valueSeq();
7332 },
7333});
7334SetCollection.prototype.has = CollectionPrototype.includes;
7335SetCollection.prototype.contains = SetCollection.prototype.includes;
7336// Mixin subclasses
7337mixin(KeyedSeq, KeyedCollection.prototype);
7338mixin(IndexedSeq, IndexedCollection.prototype);
7339mixin(SetSeq, SetCollection.prototype);
7340// #pragma Helper functions
7341function reduce(collection, reducer, reduction, context, useFirst, reverse) {
7342 assertNotInfinite(collection.size);
7343 collection.__iterate(function (v, k, c) {
7344 if (useFirst) {
7345 useFirst = false;
7346 reduction = v;
7347 }
7348 else {
7349 reduction = reducer.call(context, reduction, v, k, c);
7350 }
7351 }, reverse);
7352 return reduction;
7353}
7354function keyMapper(v, k) {
7355 return k;
7356}
7357function entryMapper(v, k) {
7358 return [k, v];
7359}
7360function not(predicate) {
7361 return function () {
7362 return !predicate.apply(this, arguments);
7363 };
7364}
7365function neg(predicate) {
7366 return function () {
7367 return -predicate.apply(this, arguments);
7368 };
7369}
7370function defaultZipper() {
7371 return arrCopy(arguments);
7372}
7373function defaultNegComparator(a, b) {
7374 return a < b ? 1 : a > b ? -1 : 0;
7375}
7376function hashCollection(collection) {
7377 if (collection.size === Infinity) {
7378 return 0;
7379 }
7380 var ordered = isOrdered(collection);
7381 var keyed = isKeyed(collection);
7382 var h = ordered ? 1 : 0;
7383 var size = collection.__iterate(keyed
7384 ? ordered
7385 ? function (v, k) {
7386 h = (31 * h + hashMerge(hash(v), hash(k))) | 0;
7387 }
7388 : function (v, k) {
7389 h = (h + hashMerge(hash(v), hash(k))) | 0;
7390 }
7391 : ordered
7392 ? function (v) {
7393 h = (31 * h + hash(v)) | 0;
7394 }
7395 : function (v) {
7396 h = (h + hash(v)) | 0;
7397 });
7398 return murmurHashOfSize(size, h);
7399}
7400function murmurHashOfSize(size, h) {
7401 h = imul(h, 0xcc9e2d51);
7402 h = imul((h << 15) | (h >>> -15), 0x1b873593);
7403 h = imul((h << 13) | (h >>> -13), 5);
7404 h = ((h + 0xe6546b64) | 0) ^ size;
7405 h = imul(h ^ (h >>> 16), 0x85ebca6b);
7406 h = imul(h ^ (h >>> 13), 0xc2b2ae35);
7407 h = smi(h ^ (h >>> 16));
7408 return h;
7409}
7410function hashMerge(a, b) {
7411 return (a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2))) | 0; // int
7412}
7413var OrderedSet = /*@__PURE__*/ (function (Set$$1) {
7414 function OrderedSet(value) {
7415 return value === null || value === undefined
7416 ? emptyOrderedSet()
7417 : isOrderedSet(value)
7418 ? value
7419 : emptyOrderedSet().withMutations(function (set) {
7420 var iter = SetCollection(value);
7421 assertNotInfinite(iter.size);
7422 iter.forEach(function (v) { return set.add(v); });
7423 });
7424 }
7425 if (Set$$1)
7426 OrderedSet.__proto__ = Set$$1;
7427 OrderedSet.prototype = Object.create(Set$$1 && Set$$1.prototype);
7428 OrderedSet.prototype.constructor = OrderedSet;
7429 OrderedSet.of = function of( /*...values*/) {
7430 return this(arguments);
7431 };
7432 OrderedSet.fromKeys = function fromKeys(value) {
7433 return this(KeyedCollection(value).keySeq());
7434 };
7435 OrderedSet.prototype.toString = function toString() {
7436 return this.__toString('OrderedSet {', '}');
7437 };
7438 return OrderedSet;
7439}(Set$1));
7440OrderedSet.isOrderedSet = isOrderedSet;
7441var OrderedSetPrototype = OrderedSet.prototype;
7442OrderedSetPrototype[IS_ORDERED_SYMBOL] = true;
7443OrderedSetPrototype.zip = IndexedCollectionPrototype.zip;
7444OrderedSetPrototype.zipWith = IndexedCollectionPrototype.zipWith;
7445OrderedSetPrototype.__empty = emptyOrderedSet;
7446OrderedSetPrototype.__make = makeOrderedSet;
7447function makeOrderedSet(map, ownerID) {
7448 var set = Object.create(OrderedSetPrototype);
7449 set.size = map ? map.size : 0;
7450 set._map = map;
7451 set.__ownerID = ownerID;
7452 return set;
7453}
7454var EMPTY_ORDERED_SET;
7455function emptyOrderedSet() {
7456 return (EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap())));
7457}
7458var Record = function Record(defaultValues, name) {
7459 var hasInitialized;
7460 var RecordType = function Record(values) {
7461 var this$1 = this;
7462 if (values instanceof RecordType) {
7463 return values;
7464 }
7465 if (!(this instanceof RecordType)) {
7466 return new RecordType(values);
7467 }
7468 if (!hasInitialized) {
7469 hasInitialized = true;
7470 var keys = Object.keys(defaultValues);
7471 var indices = (RecordTypePrototype._indices = {});
7472 // Deprecated: left to attempt not to break any external code which
7473 // relies on a ._name property existing on record instances.
7474 // Use Record.getDescriptiveName() instead
7475 RecordTypePrototype._name = name;
7476 RecordTypePrototype._keys = keys;
7477 RecordTypePrototype._defaultValues = defaultValues;
7478 for (var i = 0; i < keys.length; i++) {
7479 var propName = keys[i];
7480 indices[propName] = i;
7481 if (RecordTypePrototype[propName]) {
7482 /* eslint-disable no-console */
7483 typeof console === 'object' &&
7484 console.warn &&
7485 console.warn('Cannot define ' +
7486 recordName(this) +
7487 ' with property "' +
7488 propName +
7489 '" since that property name is part of the Record API.');
7490 /* eslint-enable no-console */
7491 }
7492 else {
7493 setProp(RecordTypePrototype, propName);
7494 }
7495 }
7496 }
7497 this.__ownerID = undefined;
7498 this._values = List().withMutations(function (l) {
7499 l.setSize(this$1._keys.length);
7500 KeyedCollection(values).forEach(function (v, k) {
7501 l.set(this$1._indices[k], v === this$1._defaultValues[k] ? undefined : v);
7502 });
7503 });
7504 };
7505 var RecordTypePrototype = (RecordType.prototype = Object.create(RecordPrototype));
7506 RecordTypePrototype.constructor = RecordType;
7507 if (name) {
7508 RecordType.displayName = name;
7509 }
7510 return RecordType;
7511};
7512Record.prototype.toString = function toString() {
7513 var str = recordName(this) + ' { ';
7514 var keys = this._keys;
7515 var k;
7516 for (var i = 0, l = keys.length; i !== l; i++) {
7517 k = keys[i];
7518 str += (i ? ', ' : '') + k + ': ' + quoteString(this.get(k));
7519 }
7520 return str + ' }';
7521};
7522Record.prototype.equals = function equals(other) {
7523 return (this === other ||
7524 (other &&
7525 this._keys === other._keys &&
7526 recordSeq(this).equals(recordSeq(other))));
7527};
7528Record.prototype.hashCode = function hashCode() {
7529 return recordSeq(this).hashCode();
7530};
7531// @pragma Access
7532Record.prototype.has = function has(k) {
7533 return this._indices.hasOwnProperty(k);
7534};
7535Record.prototype.get = function get(k, notSetValue) {
7536 if (!this.has(k)) {
7537 return notSetValue;
7538 }
7539 var index = this._indices[k];
7540 var value = this._values.get(index);
7541 return value === undefined ? this._defaultValues[k] : value;
7542};
7543// @pragma Modification
7544Record.prototype.set = function set(k, v) {
7545 if (this.has(k)) {
7546 var newValues = this._values.set(this._indices[k], v === this._defaultValues[k] ? undefined : v);
7547 if (newValues !== this._values && !this.__ownerID) {
7548 return makeRecord(this, newValues);
7549 }
7550 }
7551 return this;
7552};
7553Record.prototype.remove = function remove(k) {
7554 return this.set(k);
7555};
7556Record.prototype.clear = function clear() {
7557 var newValues = this._values.clear().setSize(this._keys.length);
7558 return this.__ownerID ? this : makeRecord(this, newValues);
7559};
7560Record.prototype.wasAltered = function wasAltered() {
7561 return this._values.wasAltered();
7562};
7563Record.prototype.toSeq = function toSeq() {
7564 return recordSeq(this);
7565};
7566Record.prototype.toJS = function toJS$1() {
7567 return toJS(this);
7568};
7569Record.prototype.entries = function entries() {
7570 return this.__iterator(ITERATE_ENTRIES);
7571};
7572Record.prototype.__iterator = function __iterator(type, reverse) {
7573 return recordSeq(this).__iterator(type, reverse);
7574};
7575Record.prototype.__iterate = function __iterate(fn, reverse) {
7576 return recordSeq(this).__iterate(fn, reverse);
7577};
7578Record.prototype.__ensureOwner = function __ensureOwner(ownerID) {
7579 if (ownerID === this.__ownerID) {
7580 return this;
7581 }
7582 var newValues = this._values.__ensureOwner(ownerID);
7583 if (!ownerID) {
7584 this.__ownerID = ownerID;
7585 this._values = newValues;
7586 return this;
7587 }
7588 return makeRecord(this, newValues, ownerID);
7589};
7590Record.isRecord = isRecord;
7591Record.getDescriptiveName = recordName;
7592var RecordPrototype = Record.prototype;
7593RecordPrototype[IS_RECORD_SYMBOL] = true;
7594RecordPrototype[DELETE] = RecordPrototype.remove;
7595RecordPrototype.deleteIn = RecordPrototype.removeIn = deleteIn;
7596RecordPrototype.getIn = getIn$1;
7597RecordPrototype.hasIn = CollectionPrototype.hasIn;
7598RecordPrototype.merge = merge;
7599RecordPrototype.mergeWith = mergeWith;
7600RecordPrototype.mergeIn = mergeIn;
7601RecordPrototype.mergeDeep = mergeDeep$1;
7602RecordPrototype.mergeDeepWith = mergeDeepWith$1;
7603RecordPrototype.mergeDeepIn = mergeDeepIn;
7604RecordPrototype.setIn = setIn$1;
7605RecordPrototype.update = update$1;
7606RecordPrototype.updateIn = updateIn$1;
7607RecordPrototype.withMutations = withMutations;
7608RecordPrototype.asMutable = asMutable;
7609RecordPrototype.asImmutable = asImmutable;
7610RecordPrototype[ITERATOR_SYMBOL] = RecordPrototype.entries;
7611RecordPrototype.toJSON = RecordPrototype.toObject =
7612 CollectionPrototype.toObject;
7613RecordPrototype.inspect = RecordPrototype.toSource = function () {
7614 return this.toString();
7615};
7616function makeRecord(likeRecord, values, ownerID) {
7617 var record = Object.create(Object.getPrototypeOf(likeRecord));
7618 record._values = values;
7619 record.__ownerID = ownerID;
7620 return record;
7621}
7622function recordName(record) {
7623 return record.constructor.displayName || record.constructor.name || 'Record';
7624}
7625function recordSeq(record) {
7626 return keyedSeqFromValue(record._keys.map(function (k) { return [k, record.get(k)]; }));
7627}
7628function setProp(prototype, name) {
7629 try {
7630 Object.defineProperty(prototype, name, {
7631 get: function () {
7632 return this.get(name);
7633 },
7634 set: function (value) {
7635 invariant(this.__ownerID, 'Cannot set on an immutable record.');
7636 this.set(name, value);
7637 },
7638 });
7639 }
7640 catch (error) {
7641 // Object.defineProperty failed. Probably IE8.
7642 }
7643}
7644/**
7645 * Returns a lazy Seq of `value` repeated `times` times. When `times` is
7646 * undefined, returns an infinite sequence of `value`.
7647 */
7648var Repeat = /*@__PURE__*/ (function (IndexedSeq$$1) {
7649 function Repeat(value, times) {
7650 if (!(this instanceof Repeat)) {
7651 return new Repeat(value, times);
7652 }
7653 this._value = value;
7654 this.size = times === undefined ? Infinity : Math.max(0, times);
7655 if (this.size === 0) {
7656 if (EMPTY_REPEAT) {
7657 return EMPTY_REPEAT;
7658 }
7659 EMPTY_REPEAT = this;
7660 }
7661 }
7662 if (IndexedSeq$$1)
7663 Repeat.__proto__ = IndexedSeq$$1;
7664 Repeat.prototype = Object.create(IndexedSeq$$1 && IndexedSeq$$1.prototype);
7665 Repeat.prototype.constructor = Repeat;
7666 Repeat.prototype.toString = function toString() {
7667 if (this.size === 0) {
7668 return 'Repeat []';
7669 }
7670 return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]';
7671 };
7672 Repeat.prototype.get = function get(index, notSetValue) {
7673 return this.has(index) ? this._value : notSetValue;
7674 };
7675 Repeat.prototype.includes = function includes(searchValue) {
7676 return is(this._value, searchValue);
7677 };
7678 Repeat.prototype.slice = function slice(begin, end) {
7679 var size = this.size;
7680 return wholeSlice(begin, end, size)
7681 ? this
7682 : new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size));
7683 };
7684 Repeat.prototype.reverse = function reverse() {
7685 return this;
7686 };
7687 Repeat.prototype.indexOf = function indexOf(searchValue) {
7688 if (is(this._value, searchValue)) {
7689 return 0;
7690 }
7691 return -1;
7692 };
7693 Repeat.prototype.lastIndexOf = function lastIndexOf(searchValue) {
7694 if (is(this._value, searchValue)) {
7695 return this.size;
7696 }
7697 return -1;
7698 };
7699 Repeat.prototype.__iterate = function __iterate(fn, reverse) {
7700 var size = this.size;
7701 var i = 0;
7702 while (i !== size) {
7703 if (fn(this._value, reverse ? size - ++i : i++, this) === false) {
7704 break;
7705 }
7706 }
7707 return i;
7708 };
7709 Repeat.prototype.__iterator = function __iterator(type, reverse) {
7710 var this$1 = this;
7711 var size = this.size;
7712 var i = 0;
7713 return new Iterator(function () {
7714 return i === size
7715 ? iteratorDone()
7716 : iteratorValue(type, reverse ? size - ++i : i++, this$1._value);
7717 });
7718 };
7719 Repeat.prototype.equals = function equals(other) {
7720 return other instanceof Repeat
7721 ? is(this._value, other._value)
7722 : deepEqual(other);
7723 };
7724 return Repeat;
7725}(IndexedSeq));
7726var EMPTY_REPEAT;
7727function fromJS(value, converter) {
7728 return fromJSWith([], converter || defaultConverter, value, '', converter && converter.length > 2 ? [] : undefined, { '': value });
7729}
7730function fromJSWith(stack, converter, value, key, keyPath, parentValue) {
7731 var toSeq = Array.isArray(value)
7732 ? IndexedSeq
7733 : isPlainObj(value)
7734 ? KeyedSeq
7735 : null;
7736 if (toSeq) {
7737 if (~stack.indexOf(value)) {
7738 throw new TypeError('Cannot convert circular structure to Immutable');
7739 }
7740 stack.push(value);
7741 keyPath && key !== '' && keyPath.push(key);
7742 var converted = converter.call(parentValue, key, toSeq(value).map(function (v, k) { return fromJSWith(stack, converter, v, k, keyPath, value); }), keyPath && keyPath.slice());
7743 stack.pop();
7744 keyPath && keyPath.pop();
7745 return converted;
7746 }
7747 return value;
7748}
7749function defaultConverter(k, v) {
7750 return isKeyed(v) ? v.toMap() : v.toList();
7751}
7752var version = "4.0.0-rc.11";
7753var Immutable = {
7754 version: version,
7755 Collection: Collection,
7756 // Note: Iterable is deprecated
7757 Iterable: Collection,
7758 Seq: Seq,
7759 Map: Map$1,
7760 OrderedMap: OrderedMap,
7761 List: List,
7762 Stack: Stack,
7763 Set: Set$1,
7764 OrderedSet: OrderedSet,
7765 Record: Record,
7766 Range: Range,
7767 Repeat: Repeat,
7768 is: is,
7769 fromJS: fromJS,
7770 hash: hash,
7771 isImmutable: isImmutable,
7772 isCollection: isCollection,
7773 isKeyed: isKeyed,
7774 isIndexed: isIndexed,
7775 isAssociative: isAssociative,
7776 isOrdered: isOrdered,
7777 isValueObject: isValueObject,
7778 isSeq: isSeq,
7779 isList: isList,
7780 isMap: isMap,
7781 isOrderedMap: isOrderedMap,
7782 isStack: isStack,
7783 isSet: isSet,
7784 isOrderedSet: isOrderedSet,
7785 isRecord: isRecord,
7786 get: get,
7787 getIn: getIn,
7788 has: has,
7789 hasIn: hasIn,
7790 merge: merge$1,
7791 mergeDeep: mergeDeep,
7792 mergeWith: mergeWith$1,
7793 mergeDeepWith: mergeDeepWith,
7794 remove: remove,
7795 removeIn: removeIn,
7796 set: set,
7797 setIn: setIn,
7798 update: update,
7799 updateIn: updateIn,
7800};
7801
7802var OptionTypes;
7803(function (OptionTypes) {
7804 OptionTypes[OptionTypes["IGNORED_LABELS"] = 0] = "IGNORED_LABELS";
7805 OptionTypes[OptionTypes["ACCESSED_NODES"] = 1] = "ACCESSED_NODES";
7806 OptionTypes[OptionTypes["ASSIGNED_NODES"] = 2] = "ASSIGNED_NODES";
7807 OptionTypes[OptionTypes["IGNORE_BREAK_STATEMENTS"] = 3] = "IGNORE_BREAK_STATEMENTS";
7808 OptionTypes[OptionTypes["IGNORE_RETURN_AWAIT_YIELD"] = 4] = "IGNORE_RETURN_AWAIT_YIELD";
7809 OptionTypes[OptionTypes["NODES_CALLED_AT_PATH_WITH_OPTIONS"] = 5] = "NODES_CALLED_AT_PATH_WITH_OPTIONS";
7810 OptionTypes[OptionTypes["REPLACED_VARIABLE_INITS"] = 6] = "REPLACED_VARIABLE_INITS";
7811 OptionTypes[OptionTypes["RETURN_EXPRESSIONS_ACCESSED_AT_PATH"] = 7] = "RETURN_EXPRESSIONS_ACCESSED_AT_PATH";
7812 OptionTypes[OptionTypes["RETURN_EXPRESSIONS_ASSIGNED_AT_PATH"] = 8] = "RETURN_EXPRESSIONS_ASSIGNED_AT_PATH";
7813 OptionTypes[OptionTypes["RETURN_EXPRESSIONS_CALLED_AT_PATH"] = 9] = "RETURN_EXPRESSIONS_CALLED_AT_PATH";
7814})(OptionTypes || (OptionTypes = {}));
7815const RESULT_KEY = {};
7816class ExecutionPathOptions {
7817 static create() {
7818 return new this(Immutable.Map());
7819 }
7820 constructor(optionValues) {
7821 this.optionValues = optionValues;
7822 }
7823 addAccessedNodeAtPath(path, node) {
7824 return this.setIn([OptionTypes.ACCESSED_NODES, node, ...path, RESULT_KEY], true);
7825 }
7826 addAccessedReturnExpressionAtPath(path, callExpression) {
7827 return this.setIn([OptionTypes.RETURN_EXPRESSIONS_ACCESSED_AT_PATH, callExpression, ...path, RESULT_KEY], true);
7828 }
7829 addAssignedNodeAtPath(path, node) {
7830 return this.setIn([OptionTypes.ASSIGNED_NODES, node, ...path, RESULT_KEY], true);
7831 }
7832 addAssignedReturnExpressionAtPath(path, callExpression) {
7833 return this.setIn([OptionTypes.RETURN_EXPRESSIONS_ASSIGNED_AT_PATH, callExpression, ...path, RESULT_KEY], true);
7834 }
7835 addCalledNodeAtPathWithOptions(path, node, callOptions) {
7836 return this.setIn([OptionTypes.NODES_CALLED_AT_PATH_WITH_OPTIONS, node, ...path, RESULT_KEY, callOptions], true);
7837 }
7838 addCalledReturnExpressionAtPath(path, callExpression) {
7839 return this.setIn([OptionTypes.RETURN_EXPRESSIONS_CALLED_AT_PATH, callExpression, ...path, RESULT_KEY], true);
7840 }
7841 getHasEffectsWhenCalledOptions() {
7842 return this.setIgnoreReturnAwaitYield()
7843 .setIgnoreBreakStatements(false)
7844 .setIgnoreNoLabels();
7845 }
7846 getReplacedVariableInit(variable) {
7847 return this.optionValues.getIn([OptionTypes.REPLACED_VARIABLE_INITS, variable]);
7848 }
7849 hasNodeBeenAccessedAtPath(path, node) {
7850 return this.optionValues.getIn([OptionTypes.ACCESSED_NODES, node, ...path, RESULT_KEY]);
7851 }
7852 hasNodeBeenAssignedAtPath(path, node) {
7853 return this.optionValues.getIn([OptionTypes.ASSIGNED_NODES, node, ...path, RESULT_KEY]);
7854 }
7855 hasNodeBeenCalledAtPathWithOptions(path, node, callOptions) {
7856 const previousCallOptions = this.optionValues.getIn([
7857 OptionTypes.NODES_CALLED_AT_PATH_WITH_OPTIONS,
7858 node,
7859 ...path,
7860 RESULT_KEY
7861 ]);
7862 return (previousCallOptions &&
7863 previousCallOptions.find((_, otherCallOptions) => otherCallOptions.equals(callOptions)));
7864 }
7865 hasReturnExpressionBeenAccessedAtPath(path, callExpression) {
7866 return this.optionValues.getIn([
7867 OptionTypes.RETURN_EXPRESSIONS_ACCESSED_AT_PATH,
7868 callExpression,
7869 ...path,
7870 RESULT_KEY
7871 ]);
7872 }
7873 hasReturnExpressionBeenAssignedAtPath(path, callExpression) {
7874 return this.optionValues.getIn([
7875 OptionTypes.RETURN_EXPRESSIONS_ASSIGNED_AT_PATH,
7876 callExpression,
7877 ...path,
7878 RESULT_KEY
7879 ]);
7880 }
7881 hasReturnExpressionBeenCalledAtPath(path, callExpression) {
7882 return this.optionValues.getIn([
7883 OptionTypes.RETURN_EXPRESSIONS_CALLED_AT_PATH,
7884 callExpression,
7885 ...path,
7886 RESULT_KEY
7887 ]);
7888 }
7889 ignoreBreakStatements() {
7890 return this.get(OptionTypes.IGNORE_BREAK_STATEMENTS);
7891 }
7892 ignoreLabel(labelName) {
7893 return this.optionValues.getIn([OptionTypes.IGNORED_LABELS, labelName]);
7894 }
7895 ignoreReturnAwaitYield() {
7896 return this.get(OptionTypes.IGNORE_RETURN_AWAIT_YIELD);
7897 }
7898 replaceVariableInit(variable, init) {
7899 return this.setIn([OptionTypes.REPLACED_VARIABLE_INITS, variable], init);
7900 }
7901 setIgnoreBreakStatements(value = true) {
7902 return this.set(OptionTypes.IGNORE_BREAK_STATEMENTS, value);
7903 }
7904 setIgnoreLabel(labelName) {
7905 return this.setIn([OptionTypes.IGNORED_LABELS, labelName], true);
7906 }
7907 setIgnoreNoLabels() {
7908 return this.remove(OptionTypes.IGNORED_LABELS);
7909 }
7910 setIgnoreReturnAwaitYield(value = true) {
7911 return this.set(OptionTypes.IGNORE_RETURN_AWAIT_YIELD, value);
7912 }
7913 get(option) {
7914 return this.optionValues.get(option);
7915 }
7916 remove(option) {
7917 return new ExecutionPathOptions(this.optionValues.remove(option));
7918 }
7919 set(option, value) {
7920 return new ExecutionPathOptions(this.optionValues.set(option, value));
7921 }
7922 setIn(optionPath, value) {
7923 return new ExecutionPathOptions(this.optionValues.setIn(optionPath, value));
7924 }
7925}
7926
7927const keys = {
7928 Literal: [],
7929 Program: ['body']
7930};
7931function getAndCreateKeys(esTreeNode) {
7932 keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object');
7933 return keys[esTreeNode.type];
7934}
7935
7936const INCLUDE_PARAMETERS = 'variables';
7937const NEW_EXECUTION_PATH = ExecutionPathOptions.create();
7938class NodeBase {
7939 constructor(esTreeNode, parent, parentScope) {
7940 this.included = false;
7941 this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
7942 this.parent = parent;
7943 this.context = parent.context;
7944 this.createScope(parentScope);
7945 this.parseNode(esTreeNode);
7946 this.initialise();
7947 this.context.magicString.addSourcemapLocation(this.start);
7948 this.context.magicString.addSourcemapLocation(this.end);
7949 }
7950 /**
7951 * Override this to bind assignments to variables and do any initialisations that
7952 * require the scopes to be populated with variables.
7953 */
7954 bind() {
7955 for (const key of this.keys) {
7956 const value = this[key];
7957 if (value === null || key === 'annotations')
7958 continue;
7959 if (Array.isArray(value)) {
7960 for (const child of value) {
7961 if (child !== null)
7962 child.bind();
7963 }
7964 }
7965 else {
7966 value.bind();
7967 }
7968 }
7969 }
7970 /**
7971 * Override if this node should receive a different scope than the parent scope.
7972 */
7973 createScope(parentScope) {
7974 this.scope = parentScope;
7975 }
7976 declare(_kind, _init) {
7977 return [];
7978 }
7979 deoptimizePath(_path) { }
7980 getLiteralValueAtPath(_path, _recursionTracker, _origin) {
7981 return UNKNOWN_VALUE;
7982 }
7983 getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
7984 return UNKNOWN_EXPRESSION;
7985 }
7986 hasEffects(options) {
7987 for (const key of this.keys) {
7988 const value = this[key];
7989 if (value === null || key === 'annotations')
7990 continue;
7991 if (Array.isArray(value)) {
7992 for (const child of value) {
7993 if (child !== null && child.hasEffects(options))
7994 return true;
7995 }
7996 }
7997 else if (value.hasEffects(options))
7998 return true;
7999 }
8000 return false;
8001 }
8002 hasEffectsWhenAccessedAtPath(path, _options) {
8003 return path.length > 0;
8004 }
8005 hasEffectsWhenAssignedAtPath(_path, _options) {
8006 return true;
8007 }
8008 hasEffectsWhenCalledAtPath(_path, _callOptions, _options) {
8009 return true;
8010 }
8011 include(includeChildrenRecursively) {
8012 this.included = true;
8013 for (const key of this.keys) {
8014 const value = this[key];
8015 if (value === null || key === 'annotations')
8016 continue;
8017 if (Array.isArray(value)) {
8018 for (const child of value) {
8019 if (child !== null)
8020 child.include(includeChildrenRecursively);
8021 }
8022 }
8023 else {
8024 value.include(includeChildrenRecursively);
8025 }
8026 }
8027 }
8028 includeCallArguments(args) {
8029 for (const arg of args) {
8030 arg.include(false);
8031 }
8032 }
8033 includeWithAllDeclaredVariables(includeChildrenRecursively) {
8034 this.include(includeChildrenRecursively);
8035 }
8036 /**
8037 * Override to perform special initialisation steps after the scope is initialised
8038 */
8039 initialise() { }
8040 insertSemicolon(code) {
8041 if (code.original[this.end - 1] !== ';') {
8042 code.appendLeft(this.end, ';');
8043 }
8044 }
8045 locate() {
8046 // useful for debugging
8047 const location = locate(this.context.code, this.start, { offsetLine: 1 });
8048 location.file = this.context.fileName;
8049 location.toString = () => JSON.stringify(location);
8050 return location;
8051 }
8052 parseNode(esTreeNode) {
8053 for (const key of Object.keys(esTreeNode)) {
8054 // That way, we can override this function to add custom initialisation and then call super.parseNode
8055 if (this.hasOwnProperty(key))
8056 continue;
8057 const value = esTreeNode[key];
8058 if (typeof value !== 'object' || value === null || key === 'annotations') {
8059 this[key] = value;
8060 }
8061 else if (Array.isArray(value)) {
8062 this[key] = [];
8063 for (const child of value) {
8064 this[key].push(child === null
8065 ? null
8066 : new (this.context.nodeConstructors[child.type] ||
8067 this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
8068 }
8069 }
8070 else {
8071 this[key] = new (this.context.nodeConstructors[value.type] ||
8072 this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
8073 }
8074 }
8075 }
8076 render(code, options) {
8077 for (const key of this.keys) {
8078 const value = this[key];
8079 if (value === null || key === 'annotations')
8080 continue;
8081 if (Array.isArray(value)) {
8082 for (const child of value) {
8083 if (child !== null)
8084 child.render(code, options);
8085 }
8086 }
8087 else {
8088 value.render(code, options);
8089 }
8090 }
8091 }
8092 shouldBeIncluded() {
8093 return this.included || this.hasEffects(NEW_EXECUTION_PATH);
8094 }
8095 toString() {
8096 return this.context.code.slice(this.start, this.end);
8097 }
8098}
8099
8100class ClassNode extends NodeBase {
8101 createScope(parentScope) {
8102 this.scope = new ChildScope(parentScope);
8103 }
8104 hasEffectsWhenAccessedAtPath(path, _options) {
8105 return path.length > 1;
8106 }
8107 hasEffectsWhenAssignedAtPath(path, _options) {
8108 return path.length > 1;
8109 }
8110 hasEffectsWhenCalledAtPath(path, callOptions, options) {
8111 return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, options) ||
8112 (this.superClass !== null &&
8113 this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, options)));
8114 }
8115 initialise() {
8116 if (this.id !== null) {
8117 this.id.declare('class', this);
8118 }
8119 }
8120}
8121
8122class ClassDeclaration extends ClassNode {
8123 initialise() {
8124 super.initialise();
8125 if (this.id !== null) {
8126 this.id.variable.isId = true;
8127 }
8128 }
8129 parseNode(esTreeNode) {
8130 if (esTreeNode.id !== null) {
8131 this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope
8132 .parent);
8133 }
8134 super.parseNode(esTreeNode);
8135 }
8136 render(code, options) {
8137 if (options.format === 'system' && this.id && this.id.variable.exportName) {
8138 code.appendLeft(this.end, ` exports('${this.id.variable.exportName}', ${this.id.variable.getName()});`);
8139 }
8140 super.render(code, options);
8141 }
8142}
8143
8144class ArgumentsVariable extends LocalVariable {
8145 constructor(context) {
8146 super('arguments', null, UNKNOWN_EXPRESSION, context);
8147 }
8148 hasEffectsWhenAccessedAtPath(path) {
8149 return path.length > 1;
8150 }
8151 hasEffectsWhenAssignedAtPath() {
8152 return true;
8153 }
8154 hasEffectsWhenCalledAtPath() {
8155 return true;
8156 }
8157}
8158
8159class ThisVariable extends LocalVariable {
8160 constructor(context) {
8161 super('this', null, null, context);
8162 }
8163 _getInit(options) {
8164 return options.getReplacedVariableInit(this) || UNKNOWN_EXPRESSION;
8165 }
8166 getLiteralValueAtPath() {
8167 return UNKNOWN_VALUE;
8168 }
8169 hasEffectsWhenAccessedAtPath(path, options) {
8170 return (this._getInit(options).hasEffectsWhenAccessedAtPath(path, options) ||
8171 super.hasEffectsWhenAccessedAtPath(path, options));
8172 }
8173 hasEffectsWhenAssignedAtPath(path, options) {
8174 return (this._getInit(options).hasEffectsWhenAssignedAtPath(path, options) ||
8175 super.hasEffectsWhenAssignedAtPath(path, options));
8176 }
8177 hasEffectsWhenCalledAtPath(path, callOptions, options) {
8178 return (this._getInit(options).hasEffectsWhenCalledAtPath(path, callOptions, options) ||
8179 super.hasEffectsWhenCalledAtPath(path, callOptions, options));
8180 }
8181}
8182
8183class ParameterScope extends ChildScope {
8184 constructor(parent, context) {
8185 super(parent);
8186 this.parameters = [];
8187 this.hasRest = false;
8188 this.context = context;
8189 this.hoistedBodyVarScope = new ChildScope(this);
8190 }
8191 /**
8192 * Adds a parameter to this scope. Parameters must be added in the correct
8193 * order, e.g. from left to right.
8194 */
8195 addParameterDeclaration(identifier) {
8196 const name = identifier.name;
8197 let variable = this.hoistedBodyVarScope.variables.get(name);
8198 if (variable) {
8199 variable.addDeclaration(identifier, null);
8200 }
8201 else {
8202 variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
8203 }
8204 this.variables.set(name, variable);
8205 return variable;
8206 }
8207 addParameterVariables(parameters, hasRest) {
8208 this.parameters = parameters;
8209 for (const parameterList of parameters) {
8210 for (const parameter of parameterList) {
8211 parameter.alwaysRendered = true;
8212 }
8213 }
8214 this.hasRest = hasRest;
8215 }
8216 includeCallArguments(args) {
8217 let calledFromTryStatement = false;
8218 let argIncluded = false;
8219 const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
8220 for (let index = args.length - 1; index >= 0; index--) {
8221 const paramVars = this.parameters[index] || restParam;
8222 const arg = args[index];
8223 if (paramVars) {
8224 calledFromTryStatement = false;
8225 for (const variable of paramVars) {
8226 if (variable.included) {
8227 argIncluded = true;
8228 }
8229 if (variable.calledFromTryStatement) {
8230 calledFromTryStatement = true;
8231 }
8232 }
8233 }
8234 if (!argIncluded && arg.shouldBeIncluded()) {
8235 argIncluded = true;
8236 }
8237 if (argIncluded) {
8238 arg.include(calledFromTryStatement);
8239 }
8240 }
8241 }
8242}
8243
8244class ReturnValueScope extends ParameterScope {
8245 constructor() {
8246 super(...arguments);
8247 this.returnExpression = null;
8248 this.returnExpressions = [];
8249 }
8250 addReturnExpression(expression) {
8251 this.returnExpressions.push(expression);
8252 }
8253 getReturnExpression() {
8254 if (this.returnExpression === null)
8255 this.updateReturnExpression();
8256 return this.returnExpression;
8257 }
8258 updateReturnExpression() {
8259 if (this.returnExpressions.length === 1) {
8260 this.returnExpression = this.returnExpressions[0];
8261 }
8262 else {
8263 this.returnExpression = UNKNOWN_EXPRESSION;
8264 for (const expression of this.returnExpressions) {
8265 expression.deoptimizePath(UNKNOWN_PATH);
8266 }
8267 }
8268 }
8269}
8270
8271class FunctionScope extends ReturnValueScope {
8272 constructor(parent, context) {
8273 super(parent, context);
8274 this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
8275 this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
8276 }
8277 findLexicalBoundary() {
8278 return this;
8279 }
8280 getOptionsWhenCalledWith({ withNew }, options) {
8281 return options.replaceVariableInit(this.thisVariable, withNew ? new UnknownObjectExpression() : UNKNOWN_EXPRESSION);
8282 }
8283 includeCallArguments(args) {
8284 super.includeCallArguments(args);
8285 if (this.argumentsVariable.included) {
8286 for (const arg of args) {
8287 if (!arg.included) {
8288 arg.include(false);
8289 }
8290 }
8291 }
8292 }
8293}
8294
8295function isReference(node, parent) {
8296 if (node.type === 'MemberExpression') {
8297 return !node.computed && isReference(node.object, node);
8298 }
8299 if (node.type === 'Identifier') {
8300 if (!parent)
8301 return true;
8302 switch (parent.type) {
8303 // disregard `bar` in `foo.bar`
8304 case 'MemberExpression': return parent.computed || node === parent.object;
8305 // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
8306 case 'MethodDefinition': return parent.computed;
8307 // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
8308 case 'Property': return parent.computed || node === parent.value;
8309 // disregard the `bar` in `export { foo as bar }`
8310 case 'ExportSpecifier': return node === parent.local;
8311 // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
8312 case 'LabeledStatement':
8313 case 'BreakStatement':
8314 case 'ContinueStatement': return false;
8315 default: return true;
8316 }
8317 }
8318 return false;
8319}
8320
8321class Identifier$1 extends NodeBase {
8322 constructor() {
8323 super(...arguments);
8324 this.variable = null;
8325 this.bound = false;
8326 }
8327 addExportedVariables(variables) {
8328 if (this.variable !== null && this.variable.exportName) {
8329 variables.push(this.variable);
8330 }
8331 }
8332 bind() {
8333 if (this.bound)
8334 return;
8335 this.bound = true;
8336 if (this.variable === null && isReference(this, this.parent)) {
8337 this.variable = this.scope.findVariable(this.name);
8338 this.variable.addReference(this);
8339 }
8340 if (this.variable !== null &&
8341 this.variable instanceof LocalVariable &&
8342 this.variable.additionalInitializers !== null) {
8343 this.variable.consolidateInitializers();
8344 }
8345 }
8346 declare(kind, init) {
8347 let variable;
8348 switch (kind) {
8349 case 'var':
8350 case 'function':
8351 variable = this.scope.addDeclaration(this, this.context, init, true);
8352 break;
8353 case 'let':
8354 case 'const':
8355 case 'class':
8356 variable = this.scope.addDeclaration(this, this.context, init, false);
8357 break;
8358 case 'parameter':
8359 variable = this.scope.addParameterDeclaration(this);
8360 break;
8361 default:
8362 throw new Error(`Unexpected identifier kind ${kind}.`);
8363 }
8364 return [(this.variable = variable)];
8365 }
8366 deoptimizePath(path) {
8367 if (!this.bound)
8368 this.bind();
8369 if (this.variable !== null) {
8370 if (path.length === 0 &&
8371 this.name in this.context.importDescriptions &&
8372 !this.scope.contains(this.name)) {
8373 this.disallowImportReassignment();
8374 }
8375 this.variable.deoptimizePath(path);
8376 }
8377 }
8378 getLiteralValueAtPath(path, recursionTracker, origin) {
8379 if (!this.bound)
8380 this.bind();
8381 if (this.variable !== null) {
8382 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
8383 }
8384 return UNKNOWN_VALUE;
8385 }
8386 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
8387 if (!this.bound)
8388 this.bind();
8389 if (this.variable !== null) {
8390 return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
8391 }
8392 return UNKNOWN_EXPRESSION;
8393 }
8394 hasEffectsWhenAccessedAtPath(path, options) {
8395 return this.variable !== null && this.variable.hasEffectsWhenAccessedAtPath(path, options);
8396 }
8397 hasEffectsWhenAssignedAtPath(path, options) {
8398 return !this.variable || this.variable.hasEffectsWhenAssignedAtPath(path, options);
8399 }
8400 hasEffectsWhenCalledAtPath(path, callOptions, options) {
8401 return !this.variable || this.variable.hasEffectsWhenCalledAtPath(path, callOptions, options);
8402 }
8403 include() {
8404 if (!this.included) {
8405 this.included = true;
8406 if (this.variable !== null) {
8407 this.context.includeVariable(this.variable);
8408 }
8409 }
8410 }
8411 includeCallArguments(args) {
8412 if (this.variable) {
8413 this.variable.includeCallArguments(args);
8414 }
8415 }
8416 render(code, _options, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
8417 if (this.variable) {
8418 const name = this.variable.getName();
8419 if (name !== this.name) {
8420 code.overwrite(this.start, this.end, name, {
8421 contentOnly: true,
8422 storeName: true
8423 });
8424 if (isShorthandProperty) {
8425 code.prependRight(this.start, `${this.name}: `);
8426 }
8427 }
8428 // In strict mode, any variable named "eval" must be the actual "eval" function
8429 if (name === 'eval' &&
8430 renderedParentType === CallExpression &&
8431 isCalleeOfRenderedParent) {
8432 code.appendRight(this.start, '0, ');
8433 }
8434 }
8435 }
8436 disallowImportReassignment() {
8437 this.context.error({
8438 code: 'ILLEGAL_REASSIGNMENT',
8439 message: `Illegal reassignment to import '${this.name}'`
8440 }, this.start);
8441 }
8442}
8443
8444class RestElement extends NodeBase {
8445 constructor() {
8446 super(...arguments);
8447 this.declarationInit = null;
8448 }
8449 addExportedVariables(variables) {
8450 this.argument.addExportedVariables(variables);
8451 }
8452 bind() {
8453 super.bind();
8454 if (this.declarationInit !== null) {
8455 this.declarationInit.deoptimizePath([UNKNOWN_KEY, UNKNOWN_KEY]);
8456 }
8457 }
8458 declare(kind, init) {
8459 this.declarationInit = init;
8460 return this.argument.declare(kind, UNKNOWN_EXPRESSION);
8461 }
8462 deoptimizePath(path) {
8463 path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
8464 }
8465 hasEffectsWhenAssignedAtPath(path, options) {
8466 return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options);
8467 }
8468}
8469
8470class FunctionNode extends NodeBase {
8471 constructor() {
8472 super(...arguments);
8473 this.isPrototypeDeoptimized = false;
8474 }
8475 createScope(parentScope) {
8476 this.scope = new FunctionScope(parentScope, this.context);
8477 }
8478 deoptimizePath(path) {
8479 if (path.length === 1) {
8480 if (path[0] === 'prototype') {
8481 this.isPrototypeDeoptimized = true;
8482 }
8483 else if (path[0] === UNKNOWN_KEY) {
8484 this.isPrototypeDeoptimized = true;
8485 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
8486 // which means the return expression needs to be reassigned as well
8487 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
8488 }
8489 }
8490 }
8491 getReturnExpressionWhenCalledAtPath(path) {
8492 return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
8493 }
8494 hasEffects(options) {
8495 return this.id !== null && this.id.hasEffects(options);
8496 }
8497 hasEffectsWhenAccessedAtPath(path) {
8498 if (path.length <= 1) {
8499 return false;
8500 }
8501 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
8502 }
8503 hasEffectsWhenAssignedAtPath(path) {
8504 if (path.length <= 1) {
8505 return false;
8506 }
8507 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
8508 }
8509 hasEffectsWhenCalledAtPath(path, callOptions, options) {
8510 if (path.length > 0) {
8511 return true;
8512 }
8513 const innerOptions = this.scope.getOptionsWhenCalledWith(callOptions, options);
8514 for (const param of this.params) {
8515 if (param.hasEffects(innerOptions))
8516 return true;
8517 }
8518 return this.body.hasEffects(innerOptions);
8519 }
8520 include(includeChildrenRecursively) {
8521 this.included = true;
8522 this.body.include(includeChildrenRecursively);
8523 if (this.id) {
8524 this.id.include();
8525 }
8526 const hasArguments = this.scope.argumentsVariable.included;
8527 for (const param of this.params) {
8528 if (!(param instanceof Identifier$1) || hasArguments) {
8529 param.include(includeChildrenRecursively);
8530 }
8531 }
8532 }
8533 includeCallArguments(args) {
8534 this.scope.includeCallArguments(args);
8535 }
8536 initialise() {
8537 if (this.id !== null) {
8538 this.id.declare('function', this);
8539 }
8540 this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
8541 this.body.addImplicitReturnExpressionToScope();
8542 }
8543 parseNode(esTreeNode) {
8544 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
8545 super.parseNode(esTreeNode);
8546 }
8547}
8548FunctionNode.prototype.preventChildBlockScope = true;
8549
8550class FunctionDeclaration extends FunctionNode {
8551 initialise() {
8552 super.initialise();
8553 if (this.id !== null) {
8554 this.id.variable.isId = true;
8555 }
8556 }
8557 parseNode(esTreeNode) {
8558 if (esTreeNode.id !== null) {
8559 this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope
8560 .parent);
8561 }
8562 super.parseNode(esTreeNode);
8563 }
8564}
8565
8566const WHITESPACE = /\s/;
8567// The header ends at the first non-white-space after "default"
8568function getDeclarationStart(code, start = 0) {
8569 start = findFirstOccurrenceOutsideComment(code, 'default', start) + 7;
8570 while (WHITESPACE.test(code[start]))
8571 start++;
8572 return start;
8573}
8574function getIdInsertPosition(code, declarationKeyword, start = 0) {
8575 const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
8576 code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '{', declarationEnd));
8577 const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
8578 if (generatorStarPos === -1) {
8579 return declarationEnd;
8580 }
8581 return declarationEnd + generatorStarPos + 1;
8582}
8583class ExportDefaultDeclaration extends NodeBase {
8584 include(includeChildrenRecursively) {
8585 super.include(includeChildrenRecursively);
8586 if (includeChildrenRecursively) {
8587 this.context.includeVariable(this.variable);
8588 }
8589 }
8590 initialise() {
8591 const declaration = this.declaration;
8592 this.declarationName =
8593 (declaration.id && declaration.id.name) || this.declaration.name;
8594 this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
8595 this.context.addExport(this);
8596 }
8597 render(code, options, { start, end } = BLANK) {
8598 const declarationStart = getDeclarationStart(code.original, this.start);
8599 if (this.declaration instanceof FunctionDeclaration) {
8600 this.renderNamedDeclaration(code, declarationStart, 'function', this.declaration.id === null, options);
8601 }
8602 else if (this.declaration instanceof ClassDeclaration) {
8603 this.renderNamedDeclaration(code, declarationStart, 'class', this.declaration.id === null, options);
8604 }
8605 else if (this.variable.getOriginalVariable() !== this.variable) {
8606 // Remove altogether to prevent re-declaring the same variable
8607 if (options.format === 'system' && this.variable.exportName) {
8608 code.overwrite(start, end, `exports('${this.variable.exportName}', ${this.variable.getName()});`);
8609 }
8610 else {
8611 treeshakeNode(this, code, start, end);
8612 }
8613 return;
8614 }
8615 else if (this.variable.included) {
8616 this.renderVariableDeclaration(code, declarationStart, options);
8617 }
8618 else {
8619 code.remove(this.start, declarationStart);
8620 this.declaration.render(code, options, {
8621 isCalleeOfRenderedParent: false,
8622 renderedParentType: ExpressionStatement
8623 });
8624 if (code.original[this.end - 1] !== ';') {
8625 code.appendLeft(this.end, ';');
8626 }
8627 return;
8628 }
8629 this.declaration.render(code, options);
8630 }
8631 renderNamedDeclaration(code, declarationStart, declarationKeyword, needsId, options) {
8632 const name = this.variable.getName();
8633 // Remove `export default`
8634 code.remove(this.start, declarationStart);
8635 if (needsId) {
8636 code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, declarationStart), ` ${name}`);
8637 }
8638 if (options.format === 'system' &&
8639 this.declaration instanceof ClassDeclaration &&
8640 this.variable.exportName) {
8641 code.appendLeft(this.end, ` exports('${this.variable.exportName}', ${name});`);
8642 }
8643 }
8644 renderVariableDeclaration(code, declarationStart, options) {
8645 const systemBinding = options.format === 'system' && this.variable.exportName
8646 ? `exports('${this.variable.exportName}', `
8647 : '';
8648 code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = ${systemBinding}`);
8649 const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
8650 if (systemBinding) {
8651 code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
8652 }
8653 else if (!hasTrailingSemicolon) {
8654 code.appendLeft(this.end, ';');
8655 }
8656 }
8657}
8658ExportDefaultDeclaration.prototype.needsBoundaries = true;
8659
8660class ExportDefaultVariable extends LocalVariable {
8661 constructor(name, exportDefaultDeclaration, context) {
8662 super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
8663 this.hasId = false;
8664 // Not initialised during construction
8665 this.originalId = null;
8666 this.originalVariable = null;
8667 const declaration = exportDefaultDeclaration.declaration;
8668 if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
8669 declaration.id) {
8670 this.hasId = true;
8671 this.originalId = declaration.id;
8672 }
8673 else if (declaration instanceof Identifier$1) {
8674 this.originalId = declaration;
8675 }
8676 }
8677 addReference(identifier) {
8678 if (!this.hasId) {
8679 this.name = identifier.name;
8680 }
8681 }
8682 getAssignedVariableName() {
8683 return (this.originalId && this.originalId.name) || null;
8684 }
8685 getBaseVariableName() {
8686 const original = this.getOriginalVariable();
8687 if (original === this) {
8688 return super.getBaseVariableName();
8689 }
8690 else {
8691 return original.getBaseVariableName();
8692 }
8693 }
8694 getName() {
8695 const original = this.getOriginalVariable();
8696 if (original === this) {
8697 return super.getName();
8698 }
8699 else {
8700 return original.getName();
8701 }
8702 }
8703 getOriginalVariable() {
8704 if (this.originalVariable === null) {
8705 if (!this.originalId || (!this.hasId && this.originalId.variable.isReassigned)) {
8706 this.originalVariable = this;
8707 }
8708 else {
8709 const assignedOriginal = this.originalId.variable;
8710 this.originalVariable =
8711 assignedOriginal instanceof ExportDefaultVariable
8712 ? assignedOriginal.getOriginalVariable()
8713 : assignedOriginal;
8714 }
8715 }
8716 return this.originalVariable;
8717 }
8718 setRenderNames(baseName, name) {
8719 const original = this.getOriginalVariable();
8720 if (original === this) {
8721 super.setRenderNames(baseName, name);
8722 }
8723 else {
8724 original.setRenderNames(baseName, name);
8725 }
8726 }
8727 setSafeName(name) {
8728 const original = this.getOriginalVariable();
8729 if (original === this) {
8730 super.setSafeName(name);
8731 }
8732 else {
8733 original.setSafeName(name);
8734 }
8735 }
8736}
8737
8738const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
8739const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
8740const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
8741
8742class ExportShimVariable extends Variable {
8743 constructor(module) {
8744 super(MISSING_EXPORT_SHIM_VARIABLE);
8745 this.module = module;
8746 }
8747}
8748
8749const pureFunctions = [
8750 'Array.isArray',
8751 'Error',
8752 'EvalError',
8753 'InternalError',
8754 'RangeError',
8755 'ReferenceError',
8756 'SyntaxError',
8757 'TypeError',
8758 'URIError',
8759 'isFinite',
8760 'isNaN',
8761 'parseFloat',
8762 'parseInt',
8763 'decodeURI',
8764 'decodeURIComponent',
8765 'encodeURI',
8766 'encodeURIComponent',
8767 'escape',
8768 'unescape',
8769 'Object',
8770 'Object.create',
8771 'Object.getNotifier',
8772 'Object.getOwn',
8773 'Object.getOwnPropertyDescriptor',
8774 'Object.getOwnPropertyNames',
8775 'Object.getOwnPropertySymbols',
8776 'Object.getPrototypeOf',
8777 'Object.is',
8778 'Object.isExtensible',
8779 'Object.isFrozen',
8780 'Object.isSealed',
8781 'Object.keys',
8782 'Boolean',
8783 'Number',
8784 'Number.isFinite',
8785 'Number.isInteger',
8786 'Number.isNaN',
8787 'Number.isSafeInteger',
8788 'Number.parseFloat',
8789 'Number.parseInt',
8790 'Symbol',
8791 'Symbol.for',
8792 'Symbol.keyFor',
8793 'Math.abs',
8794 'Math.acos',
8795 'Math.acosh',
8796 'Math.asin',
8797 'Math.asinh',
8798 'Math.atan',
8799 'Math.atan2',
8800 'Math.atanh',
8801 'Math.cbrt',
8802 'Math.ceil',
8803 'Math.clz32',
8804 'Math.cos',
8805 'Math.cosh',
8806 'Math.exp',
8807 'Math.expm1',
8808 'Math.floor',
8809 'Math.fround',
8810 'Math.hypot',
8811 'Math.imul',
8812 'Math.log',
8813 'Math.log10',
8814 'Math.log1p',
8815 'Math.log2',
8816 'Math.max',
8817 'Math.min',
8818 'Math.pow',
8819 'Math.random',
8820 'Math.round',
8821 'Math.sign',
8822 'Math.sin',
8823 'Math.sinh',
8824 'Math.sqrt',
8825 'Math.tan',
8826 'Math.tanh',
8827 'Math.trunc',
8828 'Date',
8829 'Date.UTC',
8830 'Date.now',
8831 'Date.parse',
8832 'String',
8833 'String.fromCharCode',
8834 'String.fromCodePoint',
8835 'String.raw',
8836 'RegExp',
8837 'Map',
8838 'Set',
8839 'WeakMap',
8840 'WeakSet',
8841 'ArrayBuffer',
8842 'ArrayBuffer.isView',
8843 'DataView',
8844 'Promise.all',
8845 'Promise.race',
8846 'Promise.resolve',
8847 'Intl.Collator',
8848 'Intl.Collator.supportedLocalesOf',
8849 'Intl.DateTimeFormat',
8850 'Intl.DateTimeFormat.supportedLocalesOf',
8851 'Intl.NumberFormat',
8852 'Intl.NumberFormat.supportedLocalesOf'
8853];
8854const arrayTypes = 'Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split(' ');
8855for (const type of arrayTypes) {
8856 pureFunctions.push(type, `${type}.from`, `${type}.of`);
8857}
8858const simdTypes = 'Int8x16 Int16x8 Int32x4 Float32x4 Float64x2'.split(' ');
8859const 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(' ');
8860for (const type of simdTypes) {
8861 const typeString = `SIMD.${type}`;
8862 pureFunctions.push(typeString);
8863 for (const method of simdMethods) {
8864 pureFunctions.push(`${typeString}.${method}`);
8865 }
8866}
8867// TODO add others to this list from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
8868var pureFunctions$1 = new Set(pureFunctions);
8869
8870class GlobalVariable extends Variable {
8871 hasEffectsWhenAccessedAtPath(path) {
8872 // path.length == 0 can also have an effect but we postpone this for now
8873 return (path.length > 0 &&
8874 !this.isPureFunctionMember(path) &&
8875 !(this.name === 'Reflect' && path.length === 1));
8876 }
8877 hasEffectsWhenCalledAtPath(path) {
8878 return !pureFunctions$1.has([this.name, ...path].join('.'));
8879 }
8880 isPureFunctionMember(path) {
8881 return (pureFunctions$1.has([this.name, ...path].join('.')) ||
8882 (path.length >= 1 && pureFunctions$1.has([this.name, ...path.slice(0, -1)].join('.'))) ||
8883 (path.length >= 2 &&
8884 pureFunctions$1.has([this.name, ...path.slice(0, -2)].join('.')) &&
8885 path[path.length - 2] === 'prototype'));
8886 }
8887}
8888
8889class NamespaceVariable extends Variable {
8890 constructor(context) {
8891 super(context.getModuleName());
8892 this.memberVariables = Object.create(null);
8893 this.containsExternalNamespace = false;
8894 this.referencedEarly = false;
8895 this.references = [];
8896 this.context = context;
8897 this.module = context.module;
8898 for (const name of this.context.getExports().concat(this.context.getReexports())) {
8899 if (name[0] === '*' && name.length > 1)
8900 this.containsExternalNamespace = true;
8901 this.memberVariables[name] = this.context.traceExport(name);
8902 }
8903 }
8904 addReference(identifier) {
8905 this.references.push(identifier);
8906 this.name = identifier.name;
8907 }
8908 // This is only called if "UNKNOWN_PATH" is reassigned as in all other situations, either the
8909 // build fails due to an illegal namespace reassignment or MemberExpression already forwards
8910 // the reassignment to the right variable. This means we lost track of this variable and thus
8911 // need to reassign all exports.
8912 deoptimizePath() {
8913 for (const key in this.memberVariables) {
8914 this.memberVariables[key].deoptimizePath(UNKNOWN_PATH);
8915 }
8916 }
8917 include() {
8918 if (!this.included) {
8919 if (this.containsExternalNamespace) {
8920 this.context.error({
8921 code: 'NAMESPACE_CANNOT_CONTAIN_EXTERNAL',
8922 id: this.module.id,
8923 message: `Cannot create an explicit namespace object for module "${this.context.getModuleName()}" because it contains a reexported external namespace`
8924 }, undefined);
8925 }
8926 this.included = true;
8927 for (const identifier of this.references) {
8928 if (identifier.context.getModuleExecIndex() <= this.context.getModuleExecIndex()) {
8929 this.referencedEarly = true;
8930 break;
8931 }
8932 }
8933 if (this.context.preserveModules) {
8934 for (const memberName of Object.keys(this.memberVariables))
8935 this.memberVariables[memberName].include();
8936 }
8937 else {
8938 for (const memberName of Object.keys(this.memberVariables))
8939 this.context.includeVariable(this.memberVariables[memberName]);
8940 }
8941 }
8942 }
8943 renderBlock(options) {
8944 const _ = options.compact ? '' : ' ';
8945 const n = options.compact ? '' : '\n';
8946 const t = options.indent;
8947 const members = Object.keys(this.memberVariables).map(name => {
8948 const original = this.memberVariables[name];
8949 if (this.referencedEarly || original.isReassigned) {
8950 return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${options.compact ? '' : ';'}${_}}`;
8951 }
8952 const safeName = RESERVED_NAMES[name] ? `'${name}'` : name;
8953 return `${t}${safeName}: ${original.getName()}`;
8954 });
8955 const name = this.getName();
8956 const callee = options.freeze ? `/*#__PURE__*/Object.freeze` : '';
8957 let output = `${options.varOrConst} ${name} = ${options.namespaceToStringTag
8958 ? `{${n}${members.join(`,${n}`)}${n}};`
8959 : `${callee}({${n}${members.join(`,${n}`)}${n}});`}`;
8960 if (options.namespaceToStringTag) {
8961 output += `${n}if${_}(typeof Symbol${_}!==${_}'undefined'${_}&&${_}Symbol.toStringTag)${n}`;
8962 output += `${t}Object.defineProperty(${name},${_}Symbol.toStringTag,${_}{${_}value:${_}'Module'${_}});${n}`;
8963 output += `else${n || ' '}`;
8964 output += `${t}Object.defineProperty(${name},${_}'toString',${_}{${_}value:${_}function${_}()${_}{${_}return${_}'[object Module]'${options.compact ? ';' : ''}${_}}${_}});${n}`;
8965 output += `${callee}(${name});`;
8966 }
8967 if (options.format === 'system' && this.exportName) {
8968 output += `${n}exports('${this.exportName}',${_}${name});`;
8969 }
8970 return output;
8971 }
8972 renderFirst() {
8973 return this.referencedEarly;
8974 }
8975}
8976NamespaceVariable.prototype.isNamespace = true;
8977
8978const esModuleExport = `Object.defineProperty(exports, '__esModule', { value: true });`;
8979const compactEsModuleExport = `Object.defineProperty(exports,'__esModule',{value:true});`;
8980
8981function getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, mechanism = 'return ') {
8982 const _ = compact ? '' : ' ';
8983 const n = compact ? '' : '\n';
8984 if (!namedExportsMode) {
8985 let local;
8986 exports.some(expt => {
8987 if (expt.exported === 'default') {
8988 local = expt.local;
8989 return true;
8990 }
8991 return false;
8992 });
8993 // search for reexported default otherwise
8994 if (!local) {
8995 dependencies.some(dep => {
8996 if (!dep.reexports)
8997 return false;
8998 return dep.reexports.some(expt => {
8999 if (expt.reexported === 'default') {
9000 local = dep.namedExportsMode ? `${dep.name}.${expt.imported}` : dep.name;
9001 return true;
9002 }
9003 return false;
9004 });
9005 });
9006 }
9007 return `${mechanism}${local};`;
9008 }
9009 let exportBlock = '';
9010 // star exports must always output first for precedence
9011 dependencies.forEach(({ name, reexports }) => {
9012 if (reexports && namedExportsMode) {
9013 reexports.forEach(specifier => {
9014 if (specifier.reexported === '*') {
9015 if (!compact && exportBlock)
9016 exportBlock += '\n';
9017 if (specifier.needsLiveBinding) {
9018 exportBlock +=
9019 `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
9020 `${t}if${_}(k${_}!==${_}'default')${_}Object.defineProperty(exports,${_}k,${_}{${n}` +
9021 `${t}${t}enumerable:${_}true,${n}` +
9022 `${t}${t}get:${_}function${_}()${_}{${n}` +
9023 `${t}${t}${t}return ${name}[k];${n}` +
9024 `${t}${t}}${n}${t}});${n}});`;
9025 }
9026 else {
9027 exportBlock +=
9028 `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
9029 `${t}if${_}(k${_}!==${_}'default')${_}exports[k]${_}=${_}${name}[k];${n}});`;
9030 }
9031 }
9032 });
9033 }
9034 });
9035 dependencies.forEach(({ name, imports, reexports, isChunk, namedExportsMode: depNamedExportsMode }) => {
9036 if (reexports && namedExportsMode) {
9037 reexports.forEach(specifier => {
9038 if (specifier.imported === 'default' && !isChunk) {
9039 const exportsNamesOrNamespace = (imports && imports.some(specifier => specifier.imported !== 'default')) ||
9040 (reexports &&
9041 reexports.some(specifier => specifier.imported !== 'default' && specifier.imported !== '*'));
9042 const reexportsDefaultAsDefault = reexports &&
9043 reexports.some(specifier => specifier.imported === 'default' && specifier.reexported === 'default');
9044 if (exportBlock && !compact)
9045 exportBlock += '\n';
9046 if (exportsNamesOrNamespace || reexportsDefaultAsDefault)
9047 exportBlock += `exports.${specifier.reexported}${_}=${_}${name}${interop !== false ? '__default' : '.default'};`;
9048 else
9049 exportBlock += `exports.${specifier.reexported}${_}=${_}${name};`;
9050 }
9051 else if (specifier.imported !== '*') {
9052 if (exportBlock && !compact)
9053 exportBlock += '\n';
9054 const importName = specifier.imported === 'default' && !depNamedExportsMode
9055 ? name
9056 : `${name}.${specifier.imported}`;
9057 exportBlock += specifier.needsLiveBinding
9058 ? `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
9059 `${t}enumerable:${_}true,${n}` +
9060 `${t}get:${_}function${_}()${_}{${n}` +
9061 `${t}${t}return ${importName};${n}${t}}${n}});`
9062 : `exports.${specifier.reexported}${_}=${_}${importName};`;
9063 }
9064 else if (specifier.reexported !== '*') {
9065 if (exportBlock && !compact)
9066 exportBlock += '\n';
9067 exportBlock += `exports.${specifier.reexported}${_}=${_}${name};`;
9068 }
9069 });
9070 }
9071 });
9072 exports.forEach(expt => {
9073 const lhs = `exports.${expt.exported}`;
9074 const rhs = expt.local;
9075 if (lhs === rhs) {
9076 return;
9077 }
9078 if (exportBlock && !compact)
9079 exportBlock += '\n';
9080 exportBlock += `${lhs}${_}=${_}${rhs};`;
9081 });
9082 return exportBlock;
9083}
9084
9085function getInteropBlock(dependencies, options, varOrConst) {
9086 return dependencies
9087 .map(({ name, exportsNames, exportsDefault, namedExportsMode }) => {
9088 if (!namedExportsMode)
9089 return;
9090 if (!exportsDefault || options.interop === false)
9091 return null;
9092 if (exportsNames) {
9093 if (options.compact)
9094 return `${varOrConst} ${name}__default='default'in ${name}?${name}['default']:${name};`;
9095 return `${varOrConst} ${name}__default = 'default' in ${name} ? ${name}['default'] : ${name};`;
9096 }
9097 if (options.compact)
9098 return `${name}=${name}&&${name}.hasOwnProperty('default')?${name}['default']:${name};`;
9099 return `${name} = ${name} && ${name}.hasOwnProperty('default') ? ${name}['default'] : ${name};`;
9100 })
9101 .filter(Boolean)
9102 .join(options.compact ? '' : '\n');
9103}
9104
9105function copyPropertyLiveBinding(_, n, t, i) {
9106 return (`${i}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
9107 `${i}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
9108 `${i}${t}enumerable:${_}true,${n}` +
9109 `${i}${t}get:${_}function${_}()${_}{${n}` +
9110 `${i}${t}${t}return e[k];${n}` +
9111 `${i}${t}}${n}` +
9112 `${i}});${n}`);
9113}
9114function copyPropertyStatic(_, n, _t, i) {
9115 return `${i}n[k]${_}=e${_}[k];${n}`;
9116}
9117function getInteropNamespace(_, n, t, liveBindings) {
9118 return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
9119 `${t}if${_}(e${_}&&${_}e.__esModule)${_}{${_}return e;${_}}${_}else${_}{${n}` +
9120 `${t}${t}var n${_}=${_}{};${n}` +
9121 `${t}${t}if${_}(e)${_}{${n}` +
9122 `${t}${t}${t}Object.keys(e).forEach(function${_}(k)${_}{${n}` +
9123 (liveBindings ? copyPropertyLiveBinding : copyPropertyStatic)(_, n, t, t + t + t + t) +
9124 `${t}${t}${t}});${n}` +
9125 `${t}${t}}${n}` +
9126 `${t}${t}n['default']${_}=${_}e;${n}` +
9127 `${t}${t}return n;${n}` +
9128 `${t}}${n}` +
9129 `}${n}${n}`);
9130}
9131
9132const builtins$1 = {
9133 assert: true,
9134 buffer: true,
9135 console: true,
9136 constants: true,
9137 domain: true,
9138 events: true,
9139 http: true,
9140 https: true,
9141 os: true,
9142 path: true,
9143 process: true,
9144 punycode: true,
9145 querystring: true,
9146 stream: true,
9147 string_decoder: true,
9148 timers: true,
9149 tty: true,
9150 url: true,
9151 util: true,
9152 vm: true,
9153 zlib: true
9154};
9155// Creating a browser chunk that depends on Node.js built-in modules ('util'). You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins
9156function warnOnBuiltins(warn, dependencies) {
9157 const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins$1);
9158 if (!externalBuiltins.length)
9159 return;
9160 const detail = externalBuiltins.length === 1
9161 ? `module ('${externalBuiltins[0]}')`
9162 : `modules (${externalBuiltins
9163 .slice(0, -1)
9164 .map(name => `'${name}'`)
9165 .join(', ')} and '${externalBuiltins.slice(-1)}')`;
9166 warn({
9167 code: 'MISSING_NODE_BUILTINS',
9168 message: `Creating a browser bundle that depends on Node.js built-in ${detail}. You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins`,
9169 modules: externalBuiltins
9170 });
9171}
9172
9173// AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
9174// The assumption is that this makes sense for all relative ids:
9175// https://requirejs.org/docs/api.html#jsfiles
9176function removeExtensionFromRelativeAmdId(id) {
9177 if (id[0] === '.' && id.endsWith('.js')) {
9178 return id.slice(0, -3);
9179 }
9180 return id;
9181}
9182function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryModuleFacade, namedExportsMode, outro, varOrConst, warn }, options) {
9183 warnOnBuiltins(warn, dependencies);
9184 const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
9185 const args = dependencies.map(m => m.name);
9186 const n = options.compact ? '' : '\n';
9187 const _ = options.compact ? '' : ' ';
9188 if (namedExportsMode && hasExports) {
9189 args.unshift(`exports`);
9190 deps.unshift(`'exports'`);
9191 }
9192 if (accessedGlobals.has('require')) {
9193 args.unshift('require');
9194 deps.unshift(`'require'`);
9195 }
9196 if (accessedGlobals.has('module')) {
9197 args.unshift('module');
9198 deps.unshift(`'module'`);
9199 }
9200 const amdOptions = options.amd || {};
9201 const params = (amdOptions.id ? `'${amdOptions.id}',${_}` : ``) +
9202 (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
9203 const useStrict = options.strict !== false ? `${_}'use strict';` : ``;
9204 const define = amdOptions.define || 'define';
9205 const wrapperStart = `${define}(${params}function${_}(${args.join(`,${_}`)})${_}{${useStrict}${n}${n}`;
9206 // var foo__default = 'default' in foo ? foo['default'] : foo;
9207 const interopBlock = getInteropBlock(dependencies, options, varOrConst);
9208 if (interopBlock) {
9209 magicString.prepend(interopBlock + n + n);
9210 }
9211 if (accessedGlobals.has(INTEROP_NAMESPACE_VARIABLE)) {
9212 magicString.prepend(getInteropNamespace(_, n, t, options.externalLiveBindings !== false));
9213 }
9214 if (intro)
9215 magicString.prepend(intro);
9216 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
9217 if (exportBlock)
9218 magicString.append(n + n + exportBlock);
9219 if (namedExportsMode && hasExports && isEntryModuleFacade && options.esModule)
9220 magicString.append(`${n}${n}${options.compact ? compactEsModuleExport : esModuleExport}`);
9221 if (outro)
9222 magicString.append(outro);
9223 return magicString
9224 .indent(t)
9225 .append(n + n + '});')
9226 .prepend(wrapperStart);
9227}
9228
9229function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryModuleFacade, namedExportsMode, outro, varOrConst }, options) {
9230 const n = options.compact ? '' : '\n';
9231 const _ = options.compact ? '' : ' ';
9232 intro =
9233 (options.strict === false ? intro : `'use strict';${n}${n}${intro}`) +
9234 (namedExportsMode && hasExports && isEntryModuleFacade && options.esModule
9235 ? `${options.compact ? compactEsModuleExport : esModuleExport}${n}${n}`
9236 : '');
9237 let needsInterop = false;
9238 const interop = options.interop !== false;
9239 let importBlock;
9240 let definingVariable = false;
9241 importBlock = '';
9242 for (const { id, namedExportsMode, isChunk, name, reexports, imports, exportsNames, exportsDefault } of dependencies) {
9243 if (!reexports && !imports) {
9244 if (importBlock) {
9245 importBlock += !options.compact || definingVariable ? `;${n}` : ',';
9246 }
9247 definingVariable = false;
9248 importBlock += `require('${id}')`;
9249 }
9250 else {
9251 importBlock +=
9252 options.compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${varOrConst} `;
9253 definingVariable = true;
9254 if (!interop || isChunk || !exportsDefault || !namedExportsMode) {
9255 importBlock += `${name}${_}=${_}require('${id}')`;
9256 }
9257 else {
9258 needsInterop = true;
9259 if (exportsNames)
9260 importBlock += `${name}${_}=${_}require('${id}')${options.compact ? ',' : `;\n${varOrConst} `}${name}__default${_}=${_}${INTEROP_DEFAULT_VARIABLE}(${name})`;
9261 else
9262 importBlock += `${name}${_}=${_}${INTEROP_DEFAULT_VARIABLE}(require('${id}'))`;
9263 }
9264 }
9265 }
9266 if (importBlock)
9267 importBlock += ';';
9268 if (needsInterop) {
9269 const ex = options.compact ? 'e' : 'ex';
9270 intro +=
9271 `function ${INTEROP_DEFAULT_VARIABLE}${_}(${ex})${_}{${_}return${_}` +
9272 `(${ex}${_}&&${_}(typeof ${ex}${_}===${_}'object')${_}&&${_}'default'${_}in ${ex})${_}` +
9273 `?${_}${ex}['default']${_}:${_}${ex}${options.compact ? '' : '; '}}${n}${n}`;
9274 }
9275 if (accessedGlobals.has(INTEROP_NAMESPACE_VARIABLE)) {
9276 intro += getInteropNamespace(_, n, t, options.externalLiveBindings !== false);
9277 }
9278 if (importBlock)
9279 intro += importBlock + n + n;
9280 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t, `module.exports${_}=${_}`);
9281 magicString.prepend(intro);
9282 if (exportBlock)
9283 magicString.append(n + n + exportBlock);
9284 if (outro)
9285 magicString.append(outro);
9286 return magicString;
9287}
9288
9289function esm(magicString, { intro, outro, dependencies, exports }, options) {
9290 const _ = options.compact ? '' : ' ';
9291 const n = options.compact ? '' : '\n';
9292 const importBlock = dependencies
9293 .map(({ id, reexports, imports, name }) => {
9294 if (!reexports && !imports) {
9295 return `import${_}'${id}';`;
9296 }
9297 let output = '';
9298 if (imports) {
9299 const defaultImport = imports.find(specifier => specifier.imported === 'default');
9300 const starImport = imports.find(specifier => specifier.imported === '*');
9301 if (starImport) {
9302 output += `import${_}*${_}as ${starImport.local} from${_}'${id}';`;
9303 if (imports.length > 1)
9304 output += n;
9305 }
9306 if (defaultImport && imports.length === 1) {
9307 output += `import ${defaultImport.local} from${_}'${id}';`;
9308 }
9309 else if (!starImport || imports.length > 1) {
9310 output += `import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${imports
9311 .filter(specifier => specifier !== defaultImport && specifier !== starImport)
9312 .map(specifier => {
9313 if (specifier.imported === specifier.local) {
9314 return specifier.imported;
9315 }
9316 else {
9317 return `${specifier.imported} as ${specifier.local}`;
9318 }
9319 })
9320 .join(`,${_}`)}${_}}${_}from${_}'${id}';`;
9321 }
9322 }
9323 if (reexports) {
9324 if (imports)
9325 output += n;
9326 const starExport = reexports.find(specifier => specifier.reexported === '*');
9327 const namespaceReexport = reexports.find(specifier => specifier.imported === '*' && specifier.reexported !== '*');
9328 if (starExport) {
9329 output += `export${_}*${_}from${_}'${id}';`;
9330 if (reexports.length === 1) {
9331 return output;
9332 }
9333 output += n;
9334 }
9335 if (namespaceReexport) {
9336 if (!imports ||
9337 !imports.some(specifier => specifier.imported === '*' && specifier.local === name))
9338 output += `import${_}*${_}as ${name} from${_}'${id}';${n}`;
9339 output += `export${_}{${_}${name === namespaceReexport.reexported
9340 ? name
9341 : `${name} as ${namespaceReexport.reexported}`} };`;
9342 if (reexports.length === (starExport ? 2 : 1)) {
9343 return output;
9344 }
9345 output += n;
9346 }
9347 output += `export${_}{${_}${reexports
9348 .filter(specifier => specifier !== starExport && specifier !== namespaceReexport)
9349 .map(specifier => {
9350 if (specifier.imported === specifier.reexported) {
9351 return specifier.imported;
9352 }
9353 else {
9354 return `${specifier.imported} as ${specifier.reexported}`;
9355 }
9356 })
9357 .join(`,${_}`)}${_}}${_}from${_}'${id}';`;
9358 }
9359 return output;
9360 })
9361 .join(n);
9362 if (importBlock)
9363 intro += importBlock + n + n;
9364 if (intro)
9365 magicString.prepend(intro);
9366 const exportBlock = [];
9367 const exportDeclaration = [];
9368 exports.forEach(specifier => {
9369 if (specifier.exported === 'default') {
9370 exportBlock.push(`export default ${specifier.local};`);
9371 }
9372 else {
9373 exportDeclaration.push(specifier.exported === specifier.local
9374 ? specifier.local
9375 : `${specifier.local} as ${specifier.exported}`);
9376 }
9377 });
9378 if (exportDeclaration.length) {
9379 exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
9380 }
9381 if (exportBlock.length)
9382 magicString.append(n + n + exportBlock.join(n).trim());
9383 if (outro)
9384 magicString.append(outro);
9385 return magicString.trim();
9386}
9387
9388function spaces(i) {
9389 let result = '';
9390 while (i--)
9391 result += ' ';
9392 return result;
9393}
9394function tabsToSpaces(str) {
9395 return str.replace(/^\t+/, match => match.split('\t').join(' '));
9396}
9397function getCodeFrame(source, line, column) {
9398 let lines = source.split('\n');
9399 const frameStart = Math.max(0, line - 3);
9400 let frameEnd = Math.min(line + 2, lines.length);
9401 lines = lines.slice(frameStart, frameEnd);
9402 while (!/\S/.test(lines[lines.length - 1])) {
9403 lines.pop();
9404 frameEnd -= 1;
9405 }
9406 const digits = String(frameEnd).length;
9407 return lines
9408 .map((str, i) => {
9409 const isErrorLine = frameStart + i + 1 === line;
9410 let lineNum = String(i + frameStart + 1);
9411 while (lineNum.length < digits)
9412 lineNum = ` ${lineNum}`;
9413 if (isErrorLine) {
9414 const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
9415 return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
9416 }
9417 return `${lineNum}: ${tabsToSpaces(str)}`;
9418 })
9419 .join('\n');
9420}
9421
9422function error(base, props) {
9423 if (!(base instanceof Error))
9424 base = Object.assign(new Error(base.message), base);
9425 if (props)
9426 Object.assign(base, props);
9427 throw base;
9428}
9429function augmentCodeLocation(object, pos, source, id) {
9430 if (typeof pos === 'object') {
9431 const { line, column } = pos;
9432 object.loc = { file: id, line, column };
9433 }
9434 else {
9435 object.pos = pos;
9436 const { line, column } = locate(source, pos, { offsetLine: 1 });
9437 object.loc = { file: id, line, column };
9438 }
9439 if (object.frame === undefined) {
9440 const { line, column } = object.loc;
9441 object.frame = getCodeFrame(source, line, column);
9442 }
9443}
9444var Errors;
9445(function (Errors) {
9446 Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
9447 Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
9448 Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
9449 Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
9450 Errors["BAD_LOADER"] = "BAD_LOADER";
9451 Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
9452 Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
9453 Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
9454 Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
9455 Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
9456 Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
9457 Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
9458 Errors["INVALID_OPTION"] = "INVALID_OPTION";
9459 Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
9460 Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
9461 Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
9462 Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
9463 Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
9464 Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
9465 Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
9466})(Errors || (Errors = {}));
9467function errAssetNotFinalisedForFileName(name) {
9468 return {
9469 code: Errors.ASSET_NOT_FINALISED,
9470 message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
9471 };
9472}
9473function errCannotEmitFromOptionsHook() {
9474 return {
9475 code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
9476 message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
9477 };
9478}
9479function errChunkNotGeneratedForFileName(name) {
9480 return {
9481 code: Errors.CHUNK_NOT_GENERATED,
9482 message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
9483 };
9484}
9485function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
9486 return {
9487 code: Errors.ASSET_NOT_FOUND,
9488 message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
9489 };
9490}
9491function errAssetSourceAlreadySet(name) {
9492 return {
9493 code: Errors.ASSET_SOURCE_ALREADY_SET,
9494 message: `Unable to set the source for asset "${name}", source already set.`
9495 };
9496}
9497function errNoAssetSourceSet(assetName) {
9498 return {
9499 code: Errors.ASSET_SOURCE_MISSING,
9500 message: `Plugin error creating asset "${assetName}" - no asset source set.`
9501 };
9502}
9503function errBadLoader(id) {
9504 return {
9505 code: Errors.BAD_LOADER,
9506 message: `Error loading ${index.relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
9507 };
9508}
9509function errDeprecation(deprecation) {
9510 return Object.assign({ code: Errors.DEPRECATED_FEATURE }, (typeof deprecation === 'string' ? { message: deprecation } : deprecation));
9511}
9512function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
9513 return {
9514 code: Errors.FILE_NOT_FOUND,
9515 message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
9516 };
9517}
9518function errFileNameConflict(fileName) {
9519 return {
9520 code: Errors.FILE_NAME_CONFLICT,
9521 message: `Could not emit file "${fileName}" as it conflicts with an already emitted file.`
9522 };
9523}
9524function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
9525 return {
9526 code: Errors.INVALID_CHUNK,
9527 message: `Cannot assign ${index.relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
9528 };
9529}
9530function errInternalIdCannotBeExternal(source, importer) {
9531 return {
9532 code: Errors.INVALID_EXTERNAL_ID,
9533 message: `'${source}' is imported as an external by ${index.relativeId(importer)}, but is already an existing non-external module id.`
9534 };
9535}
9536function errInvalidOption(option, explanation) {
9537 return {
9538 code: Errors.INVALID_OPTION,
9539 message: `Invalid value for option "${option}" - ${explanation}.`
9540 };
9541}
9542function errInvalidRollupPhaseForAddWatchFile() {
9543 return {
9544 code: Errors.INVALID_ROLLUP_PHASE,
9545 message: `Cannot call addWatchFile after the build has finished.`
9546 };
9547}
9548function errInvalidRollupPhaseForChunkEmission() {
9549 return {
9550 code: Errors.INVALID_ROLLUP_PHASE,
9551 message: `Cannot emit chunks after module loading has finished.`
9552 };
9553}
9554function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
9555 return {
9556 code: Errors.NAMESPACE_CONFLICT,
9557 message: `Conflicting namespaces: ${index.relativeId(reexportingModule.id)} re-exports '${name}' from both ${index.relativeId(reexportingModule.exportsAll[name])} and ${index.relativeId(additionalExportAllModule.exportsAll[name])} (will be ignored)`,
9558 name,
9559 reexporter: reexportingModule.id,
9560 sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
9561 };
9562}
9563function errEntryCannotBeExternal(unresolvedId) {
9564 return {
9565 code: Errors.UNRESOLVED_ENTRY,
9566 message: `Entry module cannot be external (${index.relativeId(unresolvedId)}).`
9567 };
9568}
9569function errUnresolvedEntry(unresolvedId) {
9570 return {
9571 code: Errors.UNRESOLVED_ENTRY,
9572 message: `Could not resolve entry module (${index.relativeId(unresolvedId)}).`
9573 };
9574}
9575function errUnresolvedImport(source, importer) {
9576 return {
9577 code: Errors.UNRESOLVED_IMPORT,
9578 message: `Could not resolve '${source}' from ${index.relativeId(importer)}`
9579 };
9580}
9581function errUnresolvedImportTreatedAsExternal(source, importer) {
9582 return {
9583 code: Errors.UNRESOLVED_IMPORT,
9584 importer: index.relativeId(importer),
9585 message: `'${source}' is imported by ${index.relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
9586 source,
9587 url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
9588 };
9589}
9590function errFailedValidation(message) {
9591 return {
9592 code: Errors.VALIDATION_ERROR,
9593 message
9594 };
9595}
9596
9597// Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
9598// if the property name isn't trivial
9599const shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
9600function property(prop) {
9601 return shouldUseDot.test(prop) ? `.${prop}` : `['${prop}']`;
9602}
9603function keypath(keypath) {
9604 return keypath
9605 .split('.')
9606 .map(property)
9607 .join('');
9608}
9609
9610function setupNamespace(name, root, globals, compact) {
9611 const parts = name.split('.');
9612 if (globals) {
9613 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
9614 }
9615 const _ = compact ? '' : ' ';
9616 parts.pop();
9617 let acc = root;
9618 return (parts
9619 .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}${compact ? '' : ';'}`))
9620 .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
9621}
9622function assignToDeepVariable(deepName, root, globals, compact, assignment) {
9623 const _ = compact ? '' : ' ';
9624 const parts = deepName.split('.');
9625 if (globals) {
9626 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
9627 }
9628 const last = parts.pop();
9629 let acc = root;
9630 let deepAssignment = parts
9631 .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`))
9632 .concat(`${acc}${property(last)}`)
9633 .join(`,${_}`)
9634 .concat(`${_}=${_}${assignment}`);
9635 if (parts.length > 0) {
9636 deepAssignment = `(${deepAssignment})`;
9637 }
9638 return deepAssignment;
9639}
9640
9641function trimEmptyImports(dependencies) {
9642 let i = dependencies.length;
9643 while (i--) {
9644 const dependency = dependencies[i];
9645 if (dependency.exportsDefault || dependency.exportsNames) {
9646 return dependencies.slice(0, i + 1);
9647 }
9648 }
9649 return [];
9650}
9651
9652const thisProp = (name) => `this${keypath(name)}`;
9653function iife(magicString, { dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, options) {
9654 const _ = options.compact ? '' : ' ';
9655 const n = options.compact ? '' : '\n';
9656 const { extend, name } = options;
9657 const isNamespaced = name && name.indexOf('.') !== -1;
9658 const useVariableAssignment = !extend && !isNamespaced;
9659 if (name && useVariableAssignment && !isLegal(name)) {
9660 error({
9661 code: 'ILLEGAL_IDENTIFIER_AS_NAME',
9662 message: `Given name (${name}) is not legal JS identifier. If you need this you can try --extend option`
9663 });
9664 }
9665 warnOnBuiltins(warn, dependencies);
9666 const external = trimEmptyImports(dependencies);
9667 const deps = external.map(dep => dep.globalName || 'null');
9668 const args = external.map(m => m.name);
9669 if (hasExports && !name) {
9670 error({
9671 code: 'INVALID_OPTION',
9672 message: `You must supply "output.name" for IIFE bundles.`
9673 });
9674 }
9675 if (namedExportsMode && hasExports) {
9676 if (extend) {
9677 deps.unshift(`${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{}`);
9678 args.unshift('exports');
9679 }
9680 else {
9681 deps.unshift('{}');
9682 args.unshift('exports');
9683 }
9684 }
9685 const useStrict = options.strict !== false ? `${t}'use strict';${n}${n}` : ``;
9686 let wrapperIntro = `(function${_}(${args.join(`,${_}`)})${_}{${n}${useStrict}`;
9687 if (hasExports && (!extend || !namedExportsMode)) {
9688 wrapperIntro =
9689 (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name)) +
9690 `${_}=${_}${wrapperIntro}`;
9691 }
9692 if (isNamespaced && hasExports) {
9693 wrapperIntro =
9694 setupNamespace(name, 'this', options.globals, options.compact) + wrapperIntro;
9695 }
9696 let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`;
9697 if (!extend && namedExportsMode && hasExports) {
9698 wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
9699 }
9700 // var foo__default = 'default' in foo ? foo['default'] : foo;
9701 const interopBlock = getInteropBlock(dependencies, options, varOrConst);
9702 if (interopBlock)
9703 magicString.prepend(interopBlock + n + n);
9704 if (intro)
9705 magicString.prepend(intro);
9706 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
9707 if (exportBlock)
9708 magicString.append(n + n + exportBlock);
9709 if (outro)
9710 magicString.append(outro);
9711 return magicString
9712 .indent(t)
9713 .prepend(wrapperIntro)
9714 .append(wrapperOutro);
9715}
9716
9717function getStarExcludes({ dependencies, exports }) {
9718 const starExcludes = new Set(exports.map(expt => expt.exported));
9719 if (!starExcludes.has('default'))
9720 starExcludes.add('default');
9721 // also include reexport names
9722 dependencies.forEach(({ reexports }) => {
9723 if (reexports)
9724 reexports.forEach(reexport => {
9725 if (reexport.imported !== '*' && !starExcludes.has(reexport.reexported))
9726 starExcludes.add(reexport.reexported);
9727 });
9728 });
9729 return starExcludes;
9730}
9731const getStarExcludesBlock = (starExcludes, varOrConst, _, t, n) => starExcludes
9732 ? `${n}${t}${varOrConst} _starExcludes${_}=${_}{${_}${Array.from(starExcludes).join(`:${_}1,${_}`)}${starExcludes.size ? `:${_}1` : ''}${_}};`
9733 : '';
9734const getImportBindingsBlock = (importBindings, _, t, n) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
9735function getExportsBlock(exports, _, t, n) {
9736 if (exports.length === 0) {
9737 return '';
9738 }
9739 if (exports.length === 1) {
9740 return `${t}${t}${t}exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
9741 }
9742 return (`${t}${t}${t}exports({${n}` +
9743 exports.map(({ name, value }) => `${t}${t}${t}${t}${name}:${_}${value}`).join(`,${n}`) +
9744 `${n}${t}${t}${t}});${n}${n}`);
9745}
9746const getHoistedExportsBlock = (exports, _, t, n) => getExportsBlock(exports
9747 .filter(expt => expt.hoisted || expt.uninitialized)
9748 .map(expt => ({ name: expt.exported, value: expt.uninitialized ? 'void 0' : expt.local })), _, t, n);
9749const getMissingExportsBlock = (exports, _, t, n) => getExportsBlock(exports
9750 .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
9751 .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), _, t, n);
9752function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, outro, usesTopLevelAwait, varOrConst }, options) {
9753 const n = options.compact ? '' : '\n';
9754 const _ = options.compact ? '' : ' ';
9755 const dependencyIds = dependencies.map(m => `'${m.id}'`);
9756 const importBindings = [];
9757 let starExcludes;
9758 const setters = [];
9759 dependencies.forEach(({ imports, reexports }) => {
9760 const setter = [];
9761 if (imports) {
9762 imports.forEach(specifier => {
9763 importBindings.push(specifier.local);
9764 if (specifier.imported === '*') {
9765 setter.push(`${specifier.local}${_}=${_}module;`);
9766 }
9767 else {
9768 setter.push(`${specifier.local}${_}=${_}module.${specifier.imported};`);
9769 }
9770 });
9771 }
9772 if (reexports) {
9773 let createdSetter = false;
9774 // bulk-reexport form
9775 if (reexports.length > 1 ||
9776 (reexports.length === 1 &&
9777 (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
9778 // star reexports
9779 reexports.forEach(specifier => {
9780 if (specifier.reexported !== '*')
9781 return;
9782 // need own exports list for deduping in star export case
9783 if (!starExcludes) {
9784 starExcludes = getStarExcludes({ dependencies, exports });
9785 }
9786 if (!createdSetter) {
9787 setter.push(`${varOrConst} _setter${_}=${_}{};`);
9788 createdSetter = true;
9789 }
9790 setter.push(`for${_}(var _$p${_}in${_}module)${_}{`);
9791 setter.push(`${t}if${_}(!_starExcludes[_$p])${_}_setter[_$p]${_}=${_}module[_$p];`);
9792 setter.push('}');
9793 });
9794 // star import reexport
9795 reexports.forEach(specifier => {
9796 if (specifier.imported !== '*' || specifier.reexported === '*')
9797 return;
9798 setter.push(`exports('${specifier.reexported}',${_}module);`);
9799 });
9800 // reexports
9801 reexports.forEach(specifier => {
9802 if (specifier.reexported === '*' || specifier.imported === '*')
9803 return;
9804 if (!createdSetter) {
9805 setter.push(`${varOrConst} _setter${_}=${_}{};`);
9806 createdSetter = true;
9807 }
9808 setter.push(`_setter.${specifier.reexported}${_}=${_}module.${specifier.imported};`);
9809 });
9810 if (createdSetter) {
9811 setter.push('exports(_setter);');
9812 }
9813 }
9814 else {
9815 // single reexport
9816 reexports.forEach(specifier => {
9817 setter.push(`exports('${specifier.reexported}',${_}module.${specifier.imported});`);
9818 });
9819 }
9820 }
9821 setters.push(setter.join(`${n}${t}${t}${t}`));
9822 });
9823 const registeredName = options.name ? `'${options.name}',${_}` : '';
9824 const wrapperParams = accessedGlobals.has('module')
9825 ? `exports,${_}module`
9826 : hasExports
9827 ? 'exports'
9828 : '';
9829 let wrapperStart = `System.register(${registeredName}[` +
9830 dependencyIds.join(`,${_}`) +
9831 `],${_}function${_}(${wrapperParams})${_}{${n}${t}'use strict';` +
9832 getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
9833 getImportBindingsBlock(importBindings, _, t, n) +
9834 `${n}${t}return${_}{${setters.length
9835 ? `${n}${t}${t}setters:${_}[${setters
9836 .map(s => s
9837 ? `function${_}(module)${_}{${n}${t}${t}${t}${s}${n}${t}${t}}`
9838 : `function${_}()${_}{}`)
9839 .join(`,${_}`)}],`
9840 : ''}${n}`;
9841 wrapperStart +=
9842 `${t}${t}execute:${_}${usesTopLevelAwait ? `async${_}` : ''}function${_}()${_}{${n}${n}` +
9843 getHoistedExportsBlock(exports, _, t, n);
9844 const wrapperEnd = `${n}${n}` +
9845 getMissingExportsBlock(exports, _, t, n) +
9846 `${t}${t}}${n}${t}}${options.compact ? '' : ';'}${n}});`;
9847 if (intro)
9848 magicString.prepend(intro);
9849 if (outro)
9850 magicString.append(outro);
9851 return magicString
9852 .indent(`${t}${t}${t}`)
9853 .append(wrapperEnd)
9854 .prepend(wrapperStart);
9855}
9856
9857function globalProp(name, globalVar) {
9858 if (!name)
9859 return 'null';
9860 return `${globalVar}${keypath(name)}`;
9861}
9862function safeAccess(name, globalVar, _) {
9863 const parts = name.split('.');
9864 let acc = globalVar;
9865 return parts.map(part => ((acc += property(part)), acc)).join(`${_}&&${_}`);
9866}
9867function umd(magicString, { dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, options) {
9868 const _ = options.compact ? '' : ' ';
9869 const n = options.compact ? '' : '\n';
9870 const factoryVar = options.compact ? 'f' : 'factory';
9871 const globalVar = options.compact ? 'g' : 'global';
9872 if (hasExports && !options.name) {
9873 error({
9874 code: 'INVALID_OPTION',
9875 message: 'You must supply "output.name" for UMD bundles.'
9876 });
9877 }
9878 warnOnBuiltins(warn, dependencies);
9879 const amdDeps = dependencies.map(m => `'${m.id}'`);
9880 const cjsDeps = dependencies.map(m => `require('${m.id}')`);
9881 const trimmedImports = trimEmptyImports(dependencies);
9882 const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar));
9883 const factoryArgs = trimmedImports.map(m => m.name);
9884 if (namedExportsMode && (hasExports || options.noConflict === true)) {
9885 amdDeps.unshift(`'exports'`);
9886 cjsDeps.unshift(`exports`);
9887 globalDeps.unshift(assignToDeepVariable(options.name, globalVar, options.globals, options.compact, `${options.extend ? `${globalProp(options.name, globalVar)}${_}||${_}` : ''}{}`));
9888 factoryArgs.unshift('exports');
9889 }
9890 const amdOptions = options.amd || {};
9891 const amdParams = (amdOptions.id ? `'${amdOptions.id}',${_}` : ``) +
9892 (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
9893 const define = amdOptions.define || 'define';
9894 const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
9895 const useStrict = options.strict !== false ? `${_}'use strict';${n}` : ``;
9896 let iifeExport;
9897 if (options.noConflict === true) {
9898 const noConflictExportsVar = options.compact ? 'e' : 'exports';
9899 let factory;
9900 if (!namedExportsMode && hasExports) {
9901 factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(options.name, globalVar, options.globals, options.compact, `${factoryVar}(${globalDeps.join(`,${_}`)})`)};`;
9902 }
9903 else if (namedExportsMode) {
9904 const module = globalDeps.shift();
9905 factory =
9906 `var ${noConflictExportsVar}${_}=${_}${module};${n}` +
9907 `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
9908 }
9909 iifeExport =
9910 `(function${_}()${_}{${n}` +
9911 `${t}${t}var current${_}=${_}${safeAccess(options.name, globalVar, _)};${n}` +
9912 `${t}${t}${factory}${n}` +
9913 `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` +
9914 `${globalProp(options.name, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${options.compact ? '' : '; '}};${n}` +
9915 `${t}}())`;
9916 }
9917 else {
9918 iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
9919 if (!namedExportsMode && hasExports) {
9920 iifeExport = assignToDeepVariable(options.name, globalVar, options.globals, options.compact, iifeExport);
9921 }
9922 }
9923 const iifeNeedsGlobal = hasExports || (options.noConflict === true && namedExportsMode) || globalDeps.length > 0;
9924 const globalParam = iifeNeedsGlobal ? `${globalVar},${_}` : '';
9925 const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
9926 const iifeStart = iifeNeedsGlobal ? `(${globalVar}${_}=${_}${globalVar}${_}||${_}self,${_}` : '';
9927 const iifeEnd = iifeNeedsGlobal ? ')' : '';
9928 const cjsIntro = iifeNeedsGlobal
9929 ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
9930 `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
9931 : '';
9932 const wrapperIntro = `(function${_}(${globalParam}${factoryVar})${_}{${n}` +
9933 cjsIntro +
9934 `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
9935 `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
9936 `}(${globalArg}function${_}(${factoryArgs.join(', ')})${_}{${useStrict}${n}`;
9937 const wrapperOutro = n + n + '}));';
9938 // var foo__default = 'default' in foo ? foo['default'] : foo;
9939 const interopBlock = getInteropBlock(dependencies, options, varOrConst);
9940 if (interopBlock)
9941 magicString.prepend(interopBlock + n + n);
9942 if (intro)
9943 magicString.prepend(intro);
9944 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
9945 if (exportBlock)
9946 magicString.append(n + n + exportBlock);
9947 if (namedExportsMode && hasExports && options.esModule)
9948 magicString.append(n + n + (options.compact ? compactEsModuleExport : esModuleExport));
9949 if (outro)
9950 magicString.append(outro);
9951 return magicString
9952 .trim()
9953 .indent(t)
9954 .append(wrapperOutro)
9955 .prepend(wrapperIntro);
9956}
9957
9958var finalisers = { system, amd, cjs, es: esm, iife, umd };
9959
9960const extractors = {
9961 ArrayPattern(names, param) {
9962 for (const element of param.elements) {
9963 if (element)
9964 extractors[element.type](names, element);
9965 }
9966 },
9967 AssignmentPattern(names, param) {
9968 extractors[param.left.type](names, param.left);
9969 },
9970 Identifier(names, param) {
9971 names.push(param.name);
9972 },
9973 MemberExpression() { },
9974 ObjectPattern(names, param) {
9975 for (const prop of param.properties) {
9976 if (prop.type === 'RestElement') {
9977 extractors.RestElement(names, prop);
9978 }
9979 else {
9980 extractors[prop.value.type](names, prop.value);
9981 }
9982 }
9983 },
9984 RestElement(names, param) {
9985 extractors[param.argument.type](names, param.argument);
9986 }
9987};
9988const extractAssignedNames = function extractAssignedNames(param) {
9989 const names = [];
9990 extractors[param.type](names, param);
9991 return names;
9992};
9993
9994class ArrayExpression extends NodeBase {
9995 bind() {
9996 super.bind();
9997 for (const element of this.elements) {
9998 if (element !== null)
9999 element.deoptimizePath(UNKNOWN_PATH);
10000 }
10001 }
10002 getReturnExpressionWhenCalledAtPath(path) {
10003 if (path.length !== 1)
10004 return UNKNOWN_EXPRESSION;
10005 return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
10006 }
10007 hasEffectsWhenAccessedAtPath(path) {
10008 return path.length > 1;
10009 }
10010 hasEffectsWhenCalledAtPath(path, callOptions, options) {
10011 if (path.length === 1) {
10012 return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, options);
10013 }
10014 return true;
10015 }
10016}
10017
10018class ArrayPattern extends NodeBase {
10019 addExportedVariables(variables) {
10020 for (const element of this.elements) {
10021 if (element !== null) {
10022 element.addExportedVariables(variables);
10023 }
10024 }
10025 }
10026 declare(kind, _init) {
10027 const variables = [];
10028 for (const element of this.elements) {
10029 if (element !== null) {
10030 variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
10031 }
10032 }
10033 return variables;
10034 }
10035 deoptimizePath(path) {
10036 if (path.length === 0) {
10037 for (const element of this.elements) {
10038 if (element !== null) {
10039 element.deoptimizePath(path);
10040 }
10041 }
10042 }
10043 }
10044 hasEffectsWhenAssignedAtPath(path, options) {
10045 if (path.length > 0)
10046 return true;
10047 for (const element of this.elements) {
10048 if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))
10049 return true;
10050 }
10051 return false;
10052 }
10053}
10054
10055class BlockScope extends ChildScope {
10056 addDeclaration(identifier, context, init = null, isHoisted = false) {
10057 if (isHoisted) {
10058 return this.parent.addDeclaration(identifier, context, UNKNOWN_EXPRESSION, true);
10059 }
10060 else {
10061 return super.addDeclaration(identifier, context, init, false);
10062 }
10063 }
10064}
10065
10066class BlockStatement$1 extends NodeBase {
10067 addImplicitReturnExpressionToScope() {
10068 const lastStatement = this.body[this.body.length - 1];
10069 if (!lastStatement || lastStatement.type !== ReturnStatement) {
10070 this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
10071 }
10072 }
10073 createScope(parentScope) {
10074 this.scope = this.parent.preventChildBlockScope
10075 ? parentScope
10076 : new BlockScope(parentScope);
10077 }
10078 hasEffects(options) {
10079 for (const node of this.body) {
10080 if (node.hasEffects(options))
10081 return true;
10082 }
10083 return false;
10084 }
10085 include(includeChildrenRecursively) {
10086 this.included = true;
10087 for (const node of this.body) {
10088 if (includeChildrenRecursively || node.shouldBeIncluded())
10089 node.include(includeChildrenRecursively);
10090 }
10091 }
10092 render(code, options) {
10093 if (this.body.length) {
10094 renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
10095 }
10096 else {
10097 super.render(code, options);
10098 }
10099 }
10100}
10101
10102class ArrowFunctionExpression extends NodeBase {
10103 createScope(parentScope) {
10104 this.scope = new ReturnValueScope(parentScope, this.context);
10105 }
10106 deoptimizePath(path) {
10107 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
10108 // which means the return expression needs to be reassigned
10109 if (path.length === 1 && path[0] === UNKNOWN_KEY) {
10110 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
10111 }
10112 }
10113 getReturnExpressionWhenCalledAtPath(path) {
10114 return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
10115 }
10116 hasEffects(_options) {
10117 return false;
10118 }
10119 hasEffectsWhenAccessedAtPath(path, _options) {
10120 return path.length > 1;
10121 }
10122 hasEffectsWhenAssignedAtPath(path, _options) {
10123 return path.length > 1;
10124 }
10125 hasEffectsWhenCalledAtPath(path, _callOptions, options) {
10126 if (path.length > 0) {
10127 return true;
10128 }
10129 for (const param of this.params) {
10130 if (param.hasEffects(options))
10131 return true;
10132 }
10133 return this.body.hasEffects(options);
10134 }
10135 include(includeChildrenRecursively) {
10136 this.included = true;
10137 this.body.include(includeChildrenRecursively);
10138 for (const param of this.params) {
10139 if (!(param instanceof Identifier$1)) {
10140 param.include(includeChildrenRecursively);
10141 }
10142 }
10143 }
10144 includeCallArguments(args) {
10145 this.scope.includeCallArguments(args);
10146 }
10147 initialise() {
10148 this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
10149 if (this.body instanceof BlockStatement$1) {
10150 this.body.addImplicitReturnExpressionToScope();
10151 }
10152 else {
10153 this.scope.addReturnExpression(this.body);
10154 }
10155 }
10156 parseNode(esTreeNode) {
10157 if (esTreeNode.body.type === BlockStatement) {
10158 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
10159 }
10160 super.parseNode(esTreeNode);
10161 }
10162}
10163ArrowFunctionExpression.prototype.preventChildBlockScope = true;
10164
10165function getSystemExportStatement(exportedVariables) {
10166 if (exportedVariables.length === 1) {
10167 return `exports('${exportedVariables[0].safeExportName ||
10168 exportedVariables[0].exportName}', ${exportedVariables[0].getName()});`;
10169 }
10170 else {
10171 return `exports({${exportedVariables
10172 .map(variable => `${variable.safeExportName || variable.exportName}: ${variable.getName()}`)
10173 .join(', ')}});`;
10174 }
10175}
10176
10177class AssignmentExpression extends NodeBase {
10178 bind() {
10179 super.bind();
10180 this.left.deoptimizePath(EMPTY_PATH);
10181 // We cannot propagate mutations of the new binding to the old binding with certainty
10182 this.right.deoptimizePath(UNKNOWN_PATH);
10183 }
10184 hasEffects(options) {
10185 return (this.right.hasEffects(options) ||
10186 this.left.hasEffects(options) ||
10187 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options));
10188 }
10189 hasEffectsWhenAccessedAtPath(path, options) {
10190 return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, options);
10191 }
10192 render(code, options) {
10193 this.left.render(code, options);
10194 this.right.render(code, options);
10195 if (options.format === 'system') {
10196 if (this.left.variable && this.left.variable.exportName) {
10197 code.prependLeft(code.original.indexOf('=', this.left.end) + 1, ` exports('${this.left.variable.exportName}',`);
10198 code.appendLeft(this.right.end, `)`);
10199 }
10200 else if ('addExportedVariables' in this.left) {
10201 const systemPatternExports = [];
10202 this.left.addExportedVariables(systemPatternExports);
10203 if (systemPatternExports.length > 0) {
10204 code.prependRight(this.start, `function (v) {${getSystemExportStatement(systemPatternExports)} return v;} (`);
10205 code.appendLeft(this.end, ')');
10206 }
10207 }
10208 }
10209 }
10210}
10211
10212class AssignmentPattern extends NodeBase {
10213 addExportedVariables(variables) {
10214 this.left.addExportedVariables(variables);
10215 }
10216 bind() {
10217 super.bind();
10218 this.left.deoptimizePath(EMPTY_PATH);
10219 this.right.deoptimizePath(UNKNOWN_PATH);
10220 }
10221 declare(kind, init) {
10222 return this.left.declare(kind, init);
10223 }
10224 deoptimizePath(path) {
10225 path.length === 0 && this.left.deoptimizePath(path);
10226 }
10227 hasEffectsWhenAssignedAtPath(path, options) {
10228 return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options);
10229 }
10230 render(code, options, { isShorthandProperty } = BLANK) {
10231 this.left.render(code, options, { isShorthandProperty });
10232 this.right.render(code, options);
10233 }
10234}
10235
10236class AwaitExpression extends NodeBase {
10237 hasEffects(options) {
10238 return super.hasEffects(options) || !options.ignoreReturnAwaitYield();
10239 }
10240 include(includeChildrenRecursively) {
10241 checkTopLevelAwait: if (!this.included && !this.context.usesTopLevelAwait) {
10242 let parent = this.parent;
10243 do {
10244 if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
10245 break checkTopLevelAwait;
10246 } while ((parent = parent.parent));
10247 this.context.usesTopLevelAwait = true;
10248 }
10249 super.include(includeChildrenRecursively);
10250 }
10251 render(code, options) {
10252 super.render(code, options);
10253 }
10254}
10255
10256const RESULT_KEY$1 = {};
10257class ImmutableEntityPathTracker {
10258 constructor(existingEntityPaths = Immutable.Map()) {
10259 this.entityPaths = existingEntityPaths;
10260 }
10261 isTracked(entity, path) {
10262 return this.entityPaths.getIn([entity, ...path, RESULT_KEY$1]);
10263 }
10264 track(entity, path) {
10265 return new ImmutableEntityPathTracker(this.entityPaths.setIn([entity, ...path, RESULT_KEY$1], true));
10266 }
10267}
10268const EMPTY_IMMUTABLE_TRACKER = new ImmutableEntityPathTracker();
10269
10270class ExpressionStatement$1 extends NodeBase {
10271 initialise() {
10272 if (this.directive &&
10273 this.directive !== 'use strict' &&
10274 this.parent.type === Program) {
10275 this.context.warn(
10276 // This is necessary, because either way (deleting or not) can lead to errors.
10277 {
10278 code: 'MODULE_LEVEL_DIRECTIVE',
10279 message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
10280 }, this.start);
10281 }
10282 }
10283 render(code, options) {
10284 super.render(code, options);
10285 if (this.included)
10286 this.insertSemicolon(code);
10287 }
10288 shouldBeIncluded() {
10289 if (this.directive && this.directive !== 'use strict')
10290 return this.parent.type !== Program;
10291 return super.shouldBeIncluded();
10292 }
10293}
10294
10295const binaryOperators = {
10296 '!=': (left, right) => left != right,
10297 '!==': (left, right) => left !== right,
10298 '%': (left, right) => left % right,
10299 '&': (left, right) => left & right,
10300 '*': (left, right) => left * right,
10301 // At the moment, "**" will be transpiled to Math.pow
10302 '**': (left, right) => Math.pow(left, right),
10303 '+': (left, right) => left + right,
10304 '-': (left, right) => left - right,
10305 '/': (left, right) => left / right,
10306 '<': (left, right) => left < right,
10307 '<<': (left, right) => left << right,
10308 '<=': (left, right) => left <= right,
10309 '==': (left, right) => left == right,
10310 '===': (left, right) => left === right,
10311 '>': (left, right) => left > right,
10312 '>=': (left, right) => left >= right,
10313 '>>': (left, right) => left >> right,
10314 '>>>': (left, right) => left >>> right,
10315 '^': (left, right) => left ^ right,
10316 in: () => UNKNOWN_VALUE,
10317 instanceof: () => UNKNOWN_VALUE,
10318 '|': (left, right) => left | right
10319};
10320class BinaryExpression extends NodeBase {
10321 deoptimizeCache() { }
10322 getLiteralValueAtPath(path, recursionTracker, origin) {
10323 if (path.length > 0)
10324 return UNKNOWN_VALUE;
10325 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
10326 if (leftValue === UNKNOWN_VALUE)
10327 return UNKNOWN_VALUE;
10328 const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
10329 if (rightValue === UNKNOWN_VALUE)
10330 return UNKNOWN_VALUE;
10331 const operatorFn = binaryOperators[this.operator];
10332 if (!operatorFn)
10333 return UNKNOWN_VALUE;
10334 return operatorFn(leftValue, rightValue);
10335 }
10336 hasEffects(options) {
10337 // support some implicit type coercion runtime errors
10338 if (this.operator === '+' &&
10339 this.parent instanceof ExpressionStatement$1 &&
10340 this.left.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this) === '') {
10341 return true;
10342 }
10343 return super.hasEffects(options);
10344 }
10345 hasEffectsWhenAccessedAtPath(path, _options) {
10346 return path.length > 1;
10347 }
10348}
10349
10350class BreakStatement extends NodeBase {
10351 hasEffects(options) {
10352 return (super.hasEffects(options) ||
10353 !options.ignoreBreakStatements() ||
10354 (this.label !== null && !options.ignoreLabel(this.label.name)));
10355 }
10356}
10357
10358class CallExpression$1 extends NodeBase {
10359 constructor() {
10360 super(...arguments);
10361 // We collect deoptimization information if returnExpression !== UNKNOWN_EXPRESSION
10362 this.expressionsToBeDeoptimized = [];
10363 this.returnExpression = null;
10364 }
10365 bind() {
10366 super.bind();
10367 if (this.callee instanceof Identifier$1) {
10368 const variable = this.scope.findVariable(this.callee.name);
10369 if (variable.isNamespace) {
10370 this.context.error({
10371 code: 'CANNOT_CALL_NAMESPACE',
10372 message: `Cannot call a namespace ('${this.callee.name}')`
10373 }, this.start);
10374 }
10375 if (this.callee.name === 'eval') {
10376 this.context.warn({
10377 code: 'EVAL',
10378 message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
10379 url: 'https://rollupjs.org/guide/en/#avoiding-eval'
10380 }, this.start);
10381 }
10382 }
10383 if (this.returnExpression === null) {
10384 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
10385 }
10386 for (const argument of this.arguments) {
10387 // This will make sure all properties of parameters behave as "unknown"
10388 argument.deoptimizePath(UNKNOWN_PATH);
10389 }
10390 }
10391 deoptimizeCache() {
10392 if (this.returnExpression !== UNKNOWN_EXPRESSION) {
10393 this.returnExpression = UNKNOWN_EXPRESSION;
10394 for (const expression of this.expressionsToBeDeoptimized) {
10395 expression.deoptimizeCache();
10396 }
10397 }
10398 }
10399 deoptimizePath(path) {
10400 if (path.length > 0 && !this.context.deoptimizationTracker.track(this, path)) {
10401 if (this.returnExpression === null) {
10402 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
10403 }
10404 this.returnExpression.deoptimizePath(path);
10405 }
10406 }
10407 getLiteralValueAtPath(path, recursionTracker, origin) {
10408 if (this.returnExpression === null) {
10409 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this);
10410 }
10411 if (this.returnExpression === UNKNOWN_EXPRESSION ||
10412 recursionTracker.isTracked(this.returnExpression, path)) {
10413 return UNKNOWN_VALUE;
10414 }
10415 this.expressionsToBeDeoptimized.push(origin);
10416 return this.returnExpression.getLiteralValueAtPath(path, recursionTracker.track(this.returnExpression, path), origin);
10417 }
10418 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
10419 if (this.returnExpression === null) {
10420 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this);
10421 }
10422 if (this.returnExpression === UNKNOWN_EXPRESSION ||
10423 recursionTracker.isTracked(this.returnExpression, path)) {
10424 return UNKNOWN_EXPRESSION;
10425 }
10426 this.expressionsToBeDeoptimized.push(origin);
10427 return this.returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker.track(this.returnExpression, path), origin);
10428 }
10429 hasEffects(options) {
10430 for (const argument of this.arguments) {
10431 if (argument.hasEffects(options))
10432 return true;
10433 }
10434 if (this.context.annotations && this.annotatedPure)
10435 return false;
10436 return (this.callee.hasEffects(options) ||
10437 this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, options.getHasEffectsWhenCalledOptions()));
10438 }
10439 hasEffectsWhenAccessedAtPath(path, options) {
10440 return (path.length > 0 &&
10441 !options.hasReturnExpressionBeenAccessedAtPath(path, this) &&
10442 this.returnExpression.hasEffectsWhenAccessedAtPath(path, options.addAccessedReturnExpressionAtPath(path, this)));
10443 }
10444 hasEffectsWhenAssignedAtPath(path, options) {
10445 return (path.length === 0 ||
10446 (!options.hasReturnExpressionBeenAssignedAtPath(path, this) &&
10447 this.returnExpression.hasEffectsWhenAssignedAtPath(path, options.addAssignedReturnExpressionAtPath(path, this))));
10448 }
10449 hasEffectsWhenCalledAtPath(path, callOptions, options) {
10450 if (options.hasReturnExpressionBeenCalledAtPath(path, this))
10451 return false;
10452 return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, options.addCalledReturnExpressionAtPath(path, this));
10453 }
10454 include(includeChildrenRecursively) {
10455 if (includeChildrenRecursively) {
10456 super.include(includeChildrenRecursively);
10457 if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
10458 this.callee instanceof Identifier$1 &&
10459 this.callee.variable) {
10460 this.callee.variable.markCalledFromTryStatement();
10461 }
10462 }
10463 else {
10464 this.included = true;
10465 this.callee.include(false);
10466 }
10467 this.callee.includeCallArguments(this.arguments);
10468 if (!this.returnExpression.included) {
10469 this.returnExpression.include(false);
10470 }
10471 }
10472 initialise() {
10473 this.callOptions = CallOptions.create({
10474 args: this.arguments,
10475 callIdentifier: this,
10476 withNew: false
10477 });
10478 }
10479 render(code, options, { renderedParentType } = BLANK) {
10480 this.callee.render(code, options);
10481 if (this.arguments.length > 0) {
10482 if (this.arguments[this.arguments.length - 1].included) {
10483 for (const arg of this.arguments) {
10484 arg.render(code, options);
10485 }
10486 }
10487 else {
10488 let lastIncludedIndex = this.arguments.length - 2;
10489 while (lastIncludedIndex >= 0 && !this.arguments[lastIncludedIndex].included) {
10490 lastIncludedIndex--;
10491 }
10492 if (lastIncludedIndex >= 0) {
10493 for (let index = 0; index <= lastIncludedIndex; index++) {
10494 this.arguments[index].render(code, options);
10495 }
10496 code.remove(findFirstOccurrenceOutsideComment(code.original, ',', this.arguments[lastIncludedIndex].end), this.end - 1);
10497 }
10498 else {
10499 code.remove(findFirstOccurrenceOutsideComment(code.original, '(', this.callee.end) + 1, this.end - 1);
10500 }
10501 }
10502 }
10503 if (renderedParentType === ExpressionStatement &&
10504 this.callee.type === FunctionExpression) {
10505 code.appendRight(this.start, '(');
10506 code.prependLeft(this.end, ')');
10507 }
10508 }
10509}
10510
10511class CatchScope extends ParameterScope {
10512 addDeclaration(identifier, context, init = null, isHoisted = false) {
10513 if (isHoisted) {
10514 return this.parent.addDeclaration(identifier, context, init, true);
10515 }
10516 else {
10517 return super.addDeclaration(identifier, context, init, false);
10518 }
10519 }
10520}
10521
10522class CatchClause extends NodeBase {
10523 createScope(parentScope) {
10524 this.scope = new CatchScope(parentScope, this.context);
10525 }
10526 initialise() {
10527 if (this.param) {
10528 this.param.declare('parameter', UNKNOWN_EXPRESSION);
10529 }
10530 }
10531 parseNode(esTreeNode) {
10532 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope);
10533 super.parseNode(esTreeNode);
10534 }
10535}
10536CatchClause.prototype.preventChildBlockScope = true;
10537
10538class ClassBody extends NodeBase {
10539 hasEffectsWhenCalledAtPath(path, callOptions, options) {
10540 if (path.length > 0) {
10541 return true;
10542 }
10543 return (this.classConstructor !== null &&
10544 this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, options));
10545 }
10546 initialise() {
10547 for (const method of this.body) {
10548 if (method.kind === 'constructor') {
10549 this.classConstructor = method;
10550 return;
10551 }
10552 }
10553 this.classConstructor = null;
10554 }
10555}
10556
10557class ClassExpression extends ClassNode {
10558}
10559
10560class MultiExpression {
10561 constructor(expressions) {
10562 this.included = false;
10563 this.expressions = expressions;
10564 }
10565 deoptimizePath(path) {
10566 for (const expression of this.expressions) {
10567 expression.deoptimizePath(path);
10568 }
10569 }
10570 getLiteralValueAtPath() {
10571 return UNKNOWN_VALUE;
10572 }
10573 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
10574 return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)));
10575 }
10576 hasEffectsWhenAccessedAtPath(path, options) {
10577 for (const expression of this.expressions) {
10578 if (expression.hasEffectsWhenAccessedAtPath(path, options))
10579 return true;
10580 }
10581 return false;
10582 }
10583 hasEffectsWhenAssignedAtPath(path, options) {
10584 for (const expression of this.expressions) {
10585 if (expression.hasEffectsWhenAssignedAtPath(path, options))
10586 return true;
10587 }
10588 return false;
10589 }
10590 hasEffectsWhenCalledAtPath(path, callOptions, options) {
10591 for (const expression of this.expressions) {
10592 if (expression.hasEffectsWhenCalledAtPath(path, callOptions, options))
10593 return true;
10594 }
10595 return false;
10596 }
10597 include() { }
10598 includeCallArguments(args) {
10599 for (const expression of this.expressions) {
10600 expression.includeCallArguments(args);
10601 }
10602 }
10603}
10604
10605class ConditionalExpression extends NodeBase {
10606 constructor() {
10607 super(...arguments);
10608 // We collect deoptimization information if usedBranch !== null
10609 this.expressionsToBeDeoptimized = [];
10610 this.isBranchResolutionAnalysed = false;
10611 this.unusedBranch = null;
10612 this.usedBranch = null;
10613 }
10614 bind() {
10615 super.bind();
10616 if (!this.isBranchResolutionAnalysed)
10617 this.analyseBranchResolution();
10618 }
10619 deoptimizeCache() {
10620 if (this.usedBranch !== null) {
10621 // We did not track if there were reassignments to the previous branch.
10622 // Also, the return value might need to be reassigned.
10623 this.usedBranch = null;
10624 this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
10625 for (const expression of this.expressionsToBeDeoptimized) {
10626 expression.deoptimizeCache();
10627 }
10628 }
10629 }
10630 deoptimizePath(path) {
10631 if (path.length > 0) {
10632 if (!this.isBranchResolutionAnalysed)
10633 this.analyseBranchResolution();
10634 if (this.usedBranch === null) {
10635 this.consequent.deoptimizePath(path);
10636 this.alternate.deoptimizePath(path);
10637 }
10638 else {
10639 this.usedBranch.deoptimizePath(path);
10640 }
10641 }
10642 }
10643 getLiteralValueAtPath(path, recursionTracker, origin) {
10644 if (!this.isBranchResolutionAnalysed)
10645 this.analyseBranchResolution();
10646 if (this.usedBranch === null)
10647 return UNKNOWN_VALUE;
10648 this.expressionsToBeDeoptimized.push(origin);
10649 return this.usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
10650 }
10651 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
10652 if (!this.isBranchResolutionAnalysed)
10653 this.analyseBranchResolution();
10654 if (this.usedBranch === null)
10655 return new MultiExpression([
10656 this.consequent.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
10657 this.alternate.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
10658 ]);
10659 this.expressionsToBeDeoptimized.push(origin);
10660 return this.usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
10661 }
10662 hasEffects(options) {
10663 if (this.test.hasEffects(options))
10664 return true;
10665 if (this.usedBranch === null) {
10666 return this.consequent.hasEffects(options) || this.alternate.hasEffects(options);
10667 }
10668 return this.usedBranch.hasEffects(options);
10669 }
10670 hasEffectsWhenAccessedAtPath(path, options) {
10671 if (path.length === 0)
10672 return false;
10673 if (this.usedBranch === null) {
10674 return (this.consequent.hasEffectsWhenAccessedAtPath(path, options) ||
10675 this.alternate.hasEffectsWhenAccessedAtPath(path, options));
10676 }
10677 return this.usedBranch.hasEffectsWhenAccessedAtPath(path, options);
10678 }
10679 hasEffectsWhenAssignedAtPath(path, options) {
10680 if (path.length === 0)
10681 return true;
10682 if (this.usedBranch === null) {
10683 return (this.consequent.hasEffectsWhenAssignedAtPath(path, options) ||
10684 this.alternate.hasEffectsWhenAssignedAtPath(path, options));
10685 }
10686 return this.usedBranch.hasEffectsWhenAssignedAtPath(path, options);
10687 }
10688 hasEffectsWhenCalledAtPath(path, callOptions, options) {
10689 if (this.usedBranch === null) {
10690 return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, options) ||
10691 this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, options));
10692 }
10693 return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, options);
10694 }
10695 include(includeChildrenRecursively) {
10696 this.included = true;
10697 if (includeChildrenRecursively || this.usedBranch === null || this.test.shouldBeIncluded()) {
10698 this.test.include(includeChildrenRecursively);
10699 this.consequent.include(includeChildrenRecursively);
10700 this.alternate.include(includeChildrenRecursively);
10701 }
10702 else {
10703 this.usedBranch.include(includeChildrenRecursively);
10704 }
10705 }
10706 render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) {
10707 if (!this.test.included) {
10708 const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
10709 if (this.consequent.included) {
10710 const questionmarkPos = findFirstOccurrenceOutsideComment(code.original, '?', this.test.end);
10711 code.remove(this.start, questionmarkPos + 1);
10712 code.remove(colonPos, this.end);
10713 }
10714 else {
10715 code.remove(this.start, colonPos + 1);
10716 }
10717 removeAnnotations(this, code);
10718 this.usedBranch.render(code, options, {
10719 isCalleeOfRenderedParent: renderedParentType
10720 ? isCalleeOfRenderedParent
10721 : this.parent.callee === this,
10722 renderedParentType: renderedParentType || this.parent.type
10723 });
10724 }
10725 else {
10726 super.render(code, options);
10727 }
10728 }
10729 analyseBranchResolution() {
10730 this.isBranchResolutionAnalysed = true;
10731 const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
10732 if (testValue !== UNKNOWN_VALUE) {
10733 if (testValue) {
10734 this.usedBranch = this.consequent;
10735 this.unusedBranch = this.alternate;
10736 }
10737 else {
10738 this.usedBranch = this.alternate;
10739 this.unusedBranch = this.consequent;
10740 }
10741 }
10742 }
10743}
10744
10745class DoWhileStatement extends NodeBase {
10746 hasEffects(options) {
10747 return (this.test.hasEffects(options) || this.body.hasEffects(options.setIgnoreBreakStatements()));
10748 }
10749}
10750
10751class EmptyStatement extends NodeBase {
10752 hasEffects() {
10753 return false;
10754 }
10755}
10756
10757class ExportAllDeclaration$1 extends NodeBase {
10758 hasEffects() {
10759 return false;
10760 }
10761 initialise() {
10762 this.context.addExport(this);
10763 }
10764 render(code, _options, { start, end } = BLANK) {
10765 code.remove(start, end);
10766 }
10767}
10768ExportAllDeclaration$1.prototype.needsBoundaries = true;
10769
10770class ExportNamedDeclaration extends NodeBase {
10771 bind() {
10772 // Do not bind specifiers
10773 if (this.declaration !== null)
10774 this.declaration.bind();
10775 }
10776 hasEffects(options) {
10777 return this.declaration !== null && this.declaration.hasEffects(options);
10778 }
10779 initialise() {
10780 this.context.addExport(this);
10781 }
10782 render(code, options, { start, end } = BLANK) {
10783 if (this.declaration === null) {
10784 code.remove(start, end);
10785 }
10786 else {
10787 code.remove(this.start, this.declaration.start);
10788 this.declaration.render(code, options, { start, end });
10789 }
10790 }
10791}
10792ExportNamedDeclaration.prototype.needsBoundaries = true;
10793
10794class ForInStatement extends NodeBase {
10795 bind() {
10796 this.left.bind();
10797 this.left.deoptimizePath(EMPTY_PATH);
10798 this.right.bind();
10799 this.body.bind();
10800 }
10801 createScope(parentScope) {
10802 this.scope = new BlockScope(parentScope);
10803 }
10804 hasEffects(options) {
10805 return ((this.left &&
10806 (this.left.hasEffects(options) ||
10807 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))) ||
10808 (this.right && this.right.hasEffects(options)) ||
10809 this.body.hasEffects(options.setIgnoreBreakStatements()));
10810 }
10811 include(includeChildrenRecursively) {
10812 this.included = true;
10813 this.left.includeWithAllDeclaredVariables(includeChildrenRecursively);
10814 this.left.deoptimizePath(EMPTY_PATH);
10815 this.right.include(includeChildrenRecursively);
10816 this.body.include(includeChildrenRecursively);
10817 }
10818 render(code, options) {
10819 this.left.render(code, options, NO_SEMICOLON);
10820 this.right.render(code, options, NO_SEMICOLON);
10821 this.body.render(code, options);
10822 }
10823}
10824
10825class ForOfStatement extends NodeBase {
10826 bind() {
10827 this.left.bind();
10828 this.left.deoptimizePath(EMPTY_PATH);
10829 this.right.bind();
10830 this.body.bind();
10831 }
10832 createScope(parentScope) {
10833 this.scope = new BlockScope(parentScope);
10834 }
10835 hasEffects(options) {
10836 return ((this.left &&
10837 (this.left.hasEffects(options) ||
10838 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))) ||
10839 (this.right && this.right.hasEffects(options)) ||
10840 this.body.hasEffects(options.setIgnoreBreakStatements()));
10841 }
10842 include(includeChildrenRecursively) {
10843 this.included = true;
10844 this.left.includeWithAllDeclaredVariables(includeChildrenRecursively);
10845 this.left.deoptimizePath(EMPTY_PATH);
10846 this.right.include(includeChildrenRecursively);
10847 this.body.include(includeChildrenRecursively);
10848 }
10849 render(code, options) {
10850 this.left.render(code, options, NO_SEMICOLON);
10851 this.right.render(code, options, NO_SEMICOLON);
10852 this.body.render(code, options);
10853 }
10854}
10855
10856class ForStatement extends NodeBase {
10857 createScope(parentScope) {
10858 this.scope = new BlockScope(parentScope);
10859 }
10860 hasEffects(options) {
10861 return ((this.init && this.init.hasEffects(options)) ||
10862 (this.test && this.test.hasEffects(options)) ||
10863 (this.update && this.update.hasEffects(options)) ||
10864 this.body.hasEffects(options.setIgnoreBreakStatements()));
10865 }
10866 render(code, options) {
10867 if (this.init)
10868 this.init.render(code, options, NO_SEMICOLON);
10869 if (this.test)
10870 this.test.render(code, options, NO_SEMICOLON);
10871 if (this.update)
10872 this.update.render(code, options, NO_SEMICOLON);
10873 this.body.render(code, options);
10874 }
10875}
10876
10877class FunctionExpression$1 extends FunctionNode {
10878}
10879
10880class IfStatement extends NodeBase {
10881 constructor() {
10882 super(...arguments);
10883 this.isTestValueAnalysed = false;
10884 }
10885 bind() {
10886 super.bind();
10887 if (!this.isTestValueAnalysed) {
10888 this.testValue = UNKNOWN_VALUE;
10889 this.isTestValueAnalysed = true;
10890 this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
10891 }
10892 }
10893 deoptimizeCache() {
10894 this.testValue = UNKNOWN_VALUE;
10895 }
10896 hasEffects(options) {
10897 if (this.test.hasEffects(options))
10898 return true;
10899 if (this.testValue === UNKNOWN_VALUE) {
10900 return (this.consequent.hasEffects(options) ||
10901 (this.alternate !== null && this.alternate.hasEffects(options)));
10902 }
10903 return this.testValue
10904 ? this.consequent.hasEffects(options)
10905 : this.alternate !== null && this.alternate.hasEffects(options);
10906 }
10907 include(includeChildrenRecursively) {
10908 this.included = true;
10909 if (includeChildrenRecursively) {
10910 this.test.include(includeChildrenRecursively);
10911 this.consequent.include(includeChildrenRecursively);
10912 if (this.alternate !== null) {
10913 this.alternate.include(includeChildrenRecursively);
10914 }
10915 return;
10916 }
10917 const hasUnknownTest = this.testValue === UNKNOWN_VALUE;
10918 if (hasUnknownTest || this.test.shouldBeIncluded()) {
10919 this.test.include(false);
10920 }
10921 if ((hasUnknownTest || this.testValue) && this.consequent.shouldBeIncluded()) {
10922 this.consequent.include(false);
10923 }
10924 if (this.alternate !== null &&
10925 ((hasUnknownTest || !this.testValue) && this.alternate.shouldBeIncluded())) {
10926 this.alternate.include(false);
10927 }
10928 }
10929 render(code, options) {
10930 // Note that unknown test values are always included
10931 if (!this.test.included &&
10932 (this.testValue
10933 ? this.alternate === null || !this.alternate.included
10934 : !this.consequent.included)) {
10935 const singleRetainedBranch = (this.testValue
10936 ? this.consequent
10937 : this.alternate);
10938 code.remove(this.start, singleRetainedBranch.start);
10939 code.remove(singleRetainedBranch.end, this.end);
10940 removeAnnotations(this, code);
10941 singleRetainedBranch.render(code, options);
10942 }
10943 else {
10944 if (this.test.included) {
10945 this.test.render(code, options);
10946 }
10947 else {
10948 code.overwrite(this.test.start, this.test.end, this.testValue ? 'true' : 'false');
10949 }
10950 if (this.consequent.included) {
10951 this.consequent.render(code, options);
10952 }
10953 else {
10954 code.overwrite(this.consequent.start, this.consequent.end, ';');
10955 }
10956 if (this.alternate !== null) {
10957 if (this.alternate.included) {
10958 this.alternate.render(code, options);
10959 }
10960 else {
10961 code.remove(this.consequent.end, this.alternate.end);
10962 }
10963 }
10964 }
10965 }
10966}
10967
10968class Import extends NodeBase {
10969 constructor() {
10970 super(...arguments);
10971 this.exportMode = 'auto';
10972 }
10973 include() {
10974 if (!this.included) {
10975 this.included = true;
10976 this.context.includeDynamicImport(this);
10977 }
10978 }
10979 initialise() {
10980 this.context.addDynamicImport(this);
10981 }
10982 render(code, options) {
10983 if (this.inlineNamespace) {
10984 const _ = options.compact ? '' : ' ';
10985 const s = options.compact ? '' : ';';
10986 code.overwrite(this.parent.start, this.parent.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`);
10987 return;
10988 }
10989 const importMechanism = this.getDynamicImportMechanism(options);
10990 if (importMechanism) {
10991 code.overwrite(this.parent.start, findFirstOccurrenceOutsideComment(code.original, '(', this.parent.callee.end) + 1, importMechanism.left);
10992 code.overwrite(this.parent.end - 1, this.parent.end, importMechanism.right);
10993 }
10994 }
10995 renderFinalResolution(code, resolution, format) {
10996 if (this.included) {
10997 if (format === 'amd' && resolution.startsWith("'.") && resolution.endsWith(".js'")) {
10998 resolution = resolution.slice(0, -4) + "'";
10999 }
11000 code.overwrite(this.parent.arguments[0].start, this.parent.arguments[0].end, resolution);
11001 }
11002 }
11003 setResolution(exportMode, inlineNamespace) {
11004 this.exportMode = exportMode;
11005 if (inlineNamespace) {
11006 this.inlineNamespace = inlineNamespace;
11007 }
11008 else {
11009 this.scope.addAccessedGlobalsByFormat({
11010 amd: ['require'],
11011 cjs: ['require'],
11012 system: ['module']
11013 });
11014 if (exportMode === 'auto') {
11015 this.scope.addAccessedGlobalsByFormat({
11016 amd: [INTEROP_NAMESPACE_VARIABLE],
11017 cjs: [INTEROP_NAMESPACE_VARIABLE]
11018 });
11019 }
11020 }
11021 }
11022 getDynamicImportMechanism(options) {
11023 switch (options.format) {
11024 case 'cjs': {
11025 const _ = options.compact ? '' : ' ';
11026 const resolve = options.compact ? 'c' : 'resolve';
11027 switch (this.exportMode) {
11028 case 'default':
11029 return {
11030 left: `new Promise(function${_}(${resolve})${_}{${_}${resolve}({${_}'default':${_}require(`,
11031 right: `)${_}});${_}})`
11032 };
11033 case 'auto':
11034 return {
11035 left: `new Promise(function${_}(${resolve})${_}{${_}${resolve}(${INTEROP_NAMESPACE_VARIABLE}(require(`,
11036 right: `)));${_}})`
11037 };
11038 default:
11039 return {
11040 left: `new Promise(function${_}(${resolve})${_}{${_}${resolve}(require(`,
11041 right: `));${_}})`
11042 };
11043 }
11044 }
11045 case 'amd': {
11046 const _ = options.compact ? '' : ' ';
11047 const resolve = options.compact ? 'c' : 'resolve';
11048 const reject = options.compact ? 'e' : 'reject';
11049 const resolveNamespace = this.exportMode === 'default'
11050 ? `function${_}(m)${_}{${_}${resolve}({${_}'default':${_}m${_}});${_}}`
11051 : this.exportMode === 'auto'
11052 ? `function${_}(m)${_}{${_}${resolve}(${INTEROP_NAMESPACE_VARIABLE}(m));${_}}`
11053 : resolve;
11054 return {
11055 left: `new Promise(function${_}(${resolve},${_}${reject})${_}{${_}require([`,
11056 right: `],${_}${resolveNamespace},${_}${reject})${_}})`
11057 };
11058 }
11059 case 'system':
11060 return {
11061 left: 'module.import(',
11062 right: ')'
11063 };
11064 case 'es':
11065 if (options.dynamicImportFunction) {
11066 return {
11067 left: `${options.dynamicImportFunction}(`,
11068 right: ')'
11069 };
11070 }
11071 }
11072 return null;
11073 }
11074}
11075
11076class ImportDeclaration extends NodeBase {
11077 bind() { }
11078 hasEffects() {
11079 return false;
11080 }
11081 initialise() {
11082 this.context.addImport(this);
11083 }
11084 render(code, _options, { start, end } = BLANK) {
11085 code.remove(start, end);
11086 }
11087}
11088ImportDeclaration.prototype.needsBoundaries = true;
11089
11090class LabeledStatement extends NodeBase {
11091 hasEffects(options) {
11092 return this.body.hasEffects(options.setIgnoreLabel(this.label.name).setIgnoreBreakStatements());
11093 }
11094}
11095
11096class Literal extends NodeBase {
11097 getLiteralValueAtPath(path) {
11098 if (path.length > 0 ||
11099 // unknown literals can also be null but do not start with an "n"
11100 (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
11101 typeof this.value === 'bigint' ||
11102 // to support shims for regular expressions
11103 this.context.code.charCodeAt(this.start) === 47) {
11104 return UNKNOWN_VALUE;
11105 }
11106 return this.value;
11107 }
11108 getReturnExpressionWhenCalledAtPath(path) {
11109 if (path.length !== 1)
11110 return UNKNOWN_EXPRESSION;
11111 return getMemberReturnExpressionWhenCalled(this.members, path[0]);
11112 }
11113 hasEffectsWhenAccessedAtPath(path) {
11114 if (this.value === null) {
11115 return path.length > 0;
11116 }
11117 return path.length > 1;
11118 }
11119 hasEffectsWhenAssignedAtPath(path) {
11120 return path.length > 0;
11121 }
11122 hasEffectsWhenCalledAtPath(path, callOptions, options) {
11123 if (path.length === 1) {
11124 return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, options);
11125 }
11126 return true;
11127 }
11128 initialise() {
11129 this.members = getLiteralMembersForValue(this.value);
11130 }
11131 render(code, _options) {
11132 if (typeof this.value === 'string') {
11133 code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
11134 }
11135 }
11136}
11137
11138class LogicalExpression extends NodeBase {
11139 constructor() {
11140 super(...arguments);
11141 // We collect deoptimization information if usedBranch !== null
11142 this.expressionsToBeDeoptimized = [];
11143 this.isBranchResolutionAnalysed = false;
11144 this.unusedBranch = null;
11145 this.usedBranch = null;
11146 }
11147 bind() {
11148 super.bind();
11149 if (!this.isBranchResolutionAnalysed)
11150 this.analyseBranchResolution();
11151 }
11152 deoptimizeCache() {
11153 if (this.usedBranch !== null) {
11154 // We did not track if there were reassignments to any of the branches.
11155 // Also, the return values might need reassignment.
11156 this.usedBranch = null;
11157 this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
11158 for (const expression of this.expressionsToBeDeoptimized) {
11159 expression.deoptimizeCache();
11160 }
11161 }
11162 }
11163 deoptimizePath(path) {
11164 if (path.length > 0) {
11165 if (!this.isBranchResolutionAnalysed)
11166 this.analyseBranchResolution();
11167 if (this.usedBranch === null) {
11168 this.left.deoptimizePath(path);
11169 this.right.deoptimizePath(path);
11170 }
11171 else {
11172 this.usedBranch.deoptimizePath(path);
11173 }
11174 }
11175 }
11176 getLiteralValueAtPath(path, recursionTracker, origin) {
11177 if (!this.isBranchResolutionAnalysed)
11178 this.analyseBranchResolution();
11179 if (this.usedBranch === null)
11180 return UNKNOWN_VALUE;
11181 this.expressionsToBeDeoptimized.push(origin);
11182 return this.usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
11183 }
11184 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
11185 if (!this.isBranchResolutionAnalysed)
11186 this.analyseBranchResolution();
11187 if (this.usedBranch === null)
11188 return new MultiExpression([
11189 this.left.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
11190 this.right.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
11191 ]);
11192 this.expressionsToBeDeoptimized.push(origin);
11193 return this.usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
11194 }
11195 hasEffects(options) {
11196 if (this.usedBranch === null) {
11197 return this.left.hasEffects(options) || this.right.hasEffects(options);
11198 }
11199 return this.usedBranch.hasEffects(options);
11200 }
11201 hasEffectsWhenAccessedAtPath(path, options) {
11202 if (path.length === 0)
11203 return false;
11204 if (this.usedBranch === null) {
11205 return (this.left.hasEffectsWhenAccessedAtPath(path, options) ||
11206 this.right.hasEffectsWhenAccessedAtPath(path, options));
11207 }
11208 return this.usedBranch.hasEffectsWhenAccessedAtPath(path, options);
11209 }
11210 hasEffectsWhenAssignedAtPath(path, options) {
11211 if (path.length === 0)
11212 return true;
11213 if (this.usedBranch === null) {
11214 return (this.left.hasEffectsWhenAssignedAtPath(path, options) ||
11215 this.right.hasEffectsWhenAssignedAtPath(path, options));
11216 }
11217 return this.usedBranch.hasEffectsWhenAssignedAtPath(path, options);
11218 }
11219 hasEffectsWhenCalledAtPath(path, callOptions, options) {
11220 if (this.usedBranch === null) {
11221 return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, options) ||
11222 this.right.hasEffectsWhenCalledAtPath(path, callOptions, options));
11223 }
11224 return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, options);
11225 }
11226 include(includeChildrenRecursively) {
11227 this.included = true;
11228 if (includeChildrenRecursively ||
11229 this.usedBranch === null ||
11230 this.unusedBranch.shouldBeIncluded()) {
11231 this.left.include(includeChildrenRecursively);
11232 this.right.include(includeChildrenRecursively);
11233 }
11234 else {
11235 this.usedBranch.include(includeChildrenRecursively);
11236 }
11237 }
11238 render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) {
11239 if (!this.left.included || !this.right.included) {
11240 const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
11241 if (this.right.included) {
11242 code.remove(this.start, operatorPos + 2);
11243 }
11244 else {
11245 code.remove(operatorPos, this.end);
11246 }
11247 removeAnnotations(this, code);
11248 this.usedBranch.render(code, options, {
11249 isCalleeOfRenderedParent: renderedParentType
11250 ? isCalleeOfRenderedParent
11251 : this.parent.callee === this,
11252 renderedParentType: renderedParentType || this.parent.type
11253 });
11254 }
11255 else {
11256 super.render(code, options);
11257 }
11258 }
11259 analyseBranchResolution() {
11260 this.isBranchResolutionAnalysed = true;
11261 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
11262 if (leftValue !== UNKNOWN_VALUE) {
11263 if (this.operator === '||' ? leftValue : !leftValue) {
11264 this.usedBranch = this.left;
11265 this.unusedBranch = this.right;
11266 }
11267 else {
11268 this.usedBranch = this.right;
11269 this.unusedBranch = this.left;
11270 }
11271 }
11272 }
11273}
11274
11275function getResolvablePropertyKey(memberExpression) {
11276 return memberExpression.computed
11277 ? getResolvableComputedPropertyKey(memberExpression.property)
11278 : memberExpression.property.name;
11279}
11280function getResolvableComputedPropertyKey(propertyKey) {
11281 if (propertyKey instanceof Literal) {
11282 return String(propertyKey.value);
11283 }
11284 return null;
11285}
11286function getPathIfNotComputed(memberExpression) {
11287 const nextPathKey = memberExpression.propertyKey;
11288 const object = memberExpression.object;
11289 if (typeof nextPathKey === 'string') {
11290 if (object instanceof Identifier$1) {
11291 return [
11292 { key: object.name, pos: object.start },
11293 { key: nextPathKey, pos: memberExpression.property.start }
11294 ];
11295 }
11296 if (object instanceof MemberExpression) {
11297 const parentPath = getPathIfNotComputed(object);
11298 return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
11299 }
11300 }
11301 return null;
11302}
11303function getStringFromPath(path) {
11304 let pathString = path[0].key;
11305 for (let index = 1; index < path.length; index++) {
11306 pathString += '.' + path[index].key;
11307 }
11308 return pathString;
11309}
11310class MemberExpression extends NodeBase {
11311 constructor() {
11312 super(...arguments);
11313 this.variable = null;
11314 this.bound = false;
11315 this.expressionsToBeDeoptimized = [];
11316 this.replacement = null;
11317 }
11318 addExportedVariables() { }
11319 bind() {
11320 if (this.bound)
11321 return;
11322 this.bound = true;
11323 const path = getPathIfNotComputed(this);
11324 const baseVariable = path && this.scope.findVariable(path[0].key);
11325 if (baseVariable && baseVariable.isNamespace) {
11326 const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
11327 if (!resolvedVariable) {
11328 super.bind();
11329 }
11330 else if (typeof resolvedVariable === 'string') {
11331 this.replacement = resolvedVariable;
11332 }
11333 else {
11334 if (resolvedVariable instanceof ExternalVariable && resolvedVariable.module) {
11335 resolvedVariable.module.suggestName(path[0].key);
11336 }
11337 this.variable = resolvedVariable;
11338 this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
11339 }
11340 }
11341 else {
11342 super.bind();
11343 if (this.propertyKey === null)
11344 this.analysePropertyKey();
11345 }
11346 }
11347 deoptimizeCache() {
11348 for (const expression of this.expressionsToBeDeoptimized) {
11349 expression.deoptimizeCache();
11350 }
11351 }
11352 deoptimizePath(path) {
11353 if (!this.bound)
11354 this.bind();
11355 if (path.length === 0)
11356 this.disallowNamespaceReassignment();
11357 if (this.variable) {
11358 this.variable.deoptimizePath(path);
11359 }
11360 else {
11361 if (this.propertyKey === null)
11362 this.analysePropertyKey();
11363 this.object.deoptimizePath([this.propertyKey, ...path]);
11364 }
11365 }
11366 getLiteralValueAtPath(path, recursionTracker, origin) {
11367 if (!this.bound)
11368 this.bind();
11369 if (this.variable !== null) {
11370 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
11371 }
11372 if (this.propertyKey === null)
11373 this.analysePropertyKey();
11374 this.expressionsToBeDeoptimized.push(origin);
11375 return this.object.getLiteralValueAtPath([this.propertyKey, ...path], recursionTracker, origin);
11376 }
11377 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
11378 if (!this.bound)
11379 this.bind();
11380 if (this.variable !== null) {
11381 return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
11382 }
11383 if (this.propertyKey === null)
11384 this.analysePropertyKey();
11385 this.expressionsToBeDeoptimized.push(origin);
11386 return this.object.getReturnExpressionWhenCalledAtPath([this.propertyKey, ...path], recursionTracker, origin);
11387 }
11388 hasEffects(options) {
11389 return (this.property.hasEffects(options) ||
11390 this.object.hasEffects(options) ||
11391 (this.context.propertyReadSideEffects &&
11392 this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], options)));
11393 }
11394 hasEffectsWhenAccessedAtPath(path, options) {
11395 if (path.length === 0) {
11396 return false;
11397 }
11398 if (this.variable !== null) {
11399 return this.variable.hasEffectsWhenAccessedAtPath(path, options);
11400 }
11401 return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey, ...path], options);
11402 }
11403 hasEffectsWhenAssignedAtPath(path, options) {
11404 if (this.variable !== null) {
11405 return this.variable.hasEffectsWhenAssignedAtPath(path, options);
11406 }
11407 return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey, ...path], options);
11408 }
11409 hasEffectsWhenCalledAtPath(path, callOptions, options) {
11410 if (this.variable !== null) {
11411 return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, options);
11412 }
11413 return this.object.hasEffectsWhenCalledAtPath([this.propertyKey, ...path], callOptions, options);
11414 }
11415 include(includeChildrenRecursively) {
11416 if (!this.included) {
11417 this.included = true;
11418 if (this.variable !== null) {
11419 this.context.includeVariable(this.variable);
11420 }
11421 }
11422 this.object.include(includeChildrenRecursively);
11423 this.property.include(includeChildrenRecursively);
11424 }
11425 includeCallArguments(args) {
11426 if (this.variable) {
11427 this.variable.includeCallArguments(args);
11428 }
11429 else {
11430 super.includeCallArguments(args);
11431 }
11432 }
11433 initialise() {
11434 this.propertyKey = getResolvablePropertyKey(this);
11435 }
11436 render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) {
11437 const isCalleeOfDifferentParent = renderedParentType === CallExpression && isCalleeOfRenderedParent;
11438 if (this.variable || this.replacement) {
11439 let replacement = this.variable ? this.variable.getName() : this.replacement;
11440 if (isCalleeOfDifferentParent)
11441 replacement = '0, ' + replacement;
11442 code.overwrite(this.start, this.end, replacement, {
11443 contentOnly: true,
11444 storeName: true
11445 });
11446 }
11447 else {
11448 if (isCalleeOfDifferentParent) {
11449 code.appendRight(this.start, '0, ');
11450 }
11451 super.render(code, options);
11452 }
11453 }
11454 analysePropertyKey() {
11455 this.propertyKey = UNKNOWN_KEY;
11456 const value = this.property.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
11457 this.propertyKey = value === UNKNOWN_VALUE ? UNKNOWN_KEY : String(value);
11458 }
11459 disallowNamespaceReassignment() {
11460 if (this.object instanceof Identifier$1 &&
11461 this.scope.findVariable(this.object.name).isNamespace) {
11462 this.context.error({
11463 code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
11464 message: `Illegal reassignment to import '${this.object.name}'`
11465 }, this.start);
11466 }
11467 }
11468 resolveNamespaceVariables(baseVariable, path) {
11469 if (path.length === 0)
11470 return baseVariable;
11471 if (!baseVariable.isNamespace)
11472 return null;
11473 const exportName = path[0].key;
11474 const variable = baseVariable instanceof ExternalVariable
11475 ? baseVariable.module.getVariableForExportName(exportName)
11476 : baseVariable.context.traceExport(exportName);
11477 if (!variable) {
11478 const fileName = baseVariable instanceof ExternalVariable
11479 ? baseVariable.module.id
11480 : baseVariable.context.fileName;
11481 this.context.warn({
11482 code: 'MISSING_EXPORT',
11483 exporter: index.relativeId(fileName),
11484 importer: index.relativeId(this.context.fileName),
11485 message: `'${exportName}' is not exported by '${index.relativeId(fileName)}'`,
11486 missing: exportName,
11487 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module-`
11488 }, path[0].pos);
11489 return 'undefined';
11490 }
11491 return this.resolveNamespaceVariables(variable, path.slice(1));
11492 }
11493}
11494
11495const readFile = (file) => new Promise((fulfil, reject) => fs.readFile(file, 'utf-8', (err, contents) => (err ? reject(err) : fulfil(contents))));
11496function mkdirpath(path$1) {
11497 const dir = path.dirname(path$1);
11498 try {
11499 fs.readdirSync(dir);
11500 }
11501 catch (err) {
11502 mkdirpath(dir);
11503 try {
11504 fs.mkdirSync(dir);
11505 }
11506 catch (err2) {
11507 if (err2.code !== 'EEXIST') {
11508 throw err2;
11509 }
11510 }
11511 }
11512}
11513function writeFile(dest, data) {
11514 return new Promise((fulfil, reject) => {
11515 mkdirpath(dest);
11516 fs.writeFile(dest, data, err => {
11517 if (err) {
11518 reject(err);
11519 }
11520 else {
11521 fulfil();
11522 }
11523 });
11524 });
11525}
11526
11527function getRollupDefaultPlugin(preserveSymlinks) {
11528 return {
11529 name: 'Rollup Core',
11530 resolveId: createResolveId(preserveSymlinks),
11531 load(id) {
11532 return readFile(id);
11533 },
11534 resolveFileUrl({ relativePath, format }) {
11535 return relativeUrlMechanisms[format](relativePath);
11536 },
11537 resolveImportMeta(prop, { chunkId, format }) {
11538 const mechanism = importMetaMechanisms[format] && importMetaMechanisms[format](prop, chunkId);
11539 if (mechanism) {
11540 return mechanism;
11541 }
11542 }
11543 };
11544}
11545function findFile(file, preserveSymlinks) {
11546 try {
11547 const stats = fs.lstatSync(file);
11548 if (!preserveSymlinks && stats.isSymbolicLink())
11549 return findFile(fs.realpathSync(file), preserveSymlinks);
11550 if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
11551 // check case
11552 const name = path.basename(file);
11553 const files = fs.readdirSync(path.dirname(file));
11554 if (files.indexOf(name) !== -1)
11555 return file;
11556 }
11557 }
11558 catch (err) {
11559 // suppress
11560 }
11561}
11562function addJsExtensionIfNecessary(file, preserveSymlinks) {
11563 let found = findFile(file, preserveSymlinks);
11564 if (found)
11565 return found;
11566 found = findFile(file + '.mjs', preserveSymlinks);
11567 if (found)
11568 return found;
11569 found = findFile(file + '.js', preserveSymlinks);
11570 return found;
11571}
11572function createResolveId(preserveSymlinks) {
11573 return function (source, importer) {
11574 if (typeof process === 'undefined') {
11575 error({
11576 code: 'MISSING_PROCESS',
11577 message: `It looks like you're using Rollup in a non-Node.js environment. This means you must supply a plugin with custom resolveId and load functions`,
11578 url: 'https://rollupjs.org/guide/en/#a-simple-example'
11579 });
11580 }
11581 // external modules (non-entry modules that start with neither '.' or '/')
11582 // are skipped at this stage.
11583 if (importer !== undefined && !index.isAbsolute(source) && source[0] !== '.')
11584 return null;
11585 // `resolve` processes paths from right to left, prepending them until an
11586 // absolute path is created. Absolute importees therefore shortcircuit the
11587 // resolve call and require no special handing on our part.
11588 // See https://nodejs.org/api/path.html#path_path_resolve_paths
11589 return addJsExtensionIfNecessary(path.resolve(importer ? path.dirname(importer) : path.resolve(), source), preserveSymlinks);
11590 };
11591}
11592const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
11593const getUrlFromDocument = (chunkId) => `(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
11594const getGenericImportMetaMechanism = (getUrl) => (prop, chunkId) => {
11595 const urlMechanism = getUrl(chunkId);
11596 return prop === null ? `({ url: ${urlMechanism} })` : prop === 'url' ? urlMechanism : 'undefined';
11597};
11598const importMetaMechanisms = {
11599 amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
11600 cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
11601 iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
11602 system: prop => (prop === null ? `module.meta` : `module.meta.${prop}`),
11603 umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`)
11604};
11605const getRelativeUrlFromDocument = (relativePath) => getResolveUrl(`'${relativePath}', document.currentScript && document.currentScript.src || document.baseURI`);
11606const relativeUrlMechanisms = {
11607 amd: relativePath => {
11608 if (relativePath[0] !== '.')
11609 relativePath = './' + relativePath;
11610 return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
11611 },
11612 cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
11613 es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
11614 iife: relativePath => getRelativeUrlFromDocument(relativePath),
11615 system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
11616 umd: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`
11617};
11618const accessedMetaUrlGlobals = {
11619 amd: ['document', 'module', 'URL'],
11620 cjs: ['document', 'require', 'URL'],
11621 iife: ['document', 'URL'],
11622 system: ['module'],
11623 umd: ['document', 'require', 'URL']
11624};
11625const accessedFileUrlGlobals = {
11626 amd: ['document', 'require', 'URL'],
11627 cjs: ['document', 'require', 'URL'],
11628 iife: ['document', 'URL'],
11629 system: ['module', 'URL'],
11630 umd: ['document', 'require', 'URL']
11631};
11632
11633const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
11634const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
11635const FILE_PREFIX = 'ROLLUP_FILE_URL_';
11636class MetaProperty extends NodeBase {
11637 hasEffectsWhenAccessedAtPath(path) {
11638 return path.length > 1;
11639 }
11640 include() {
11641 if (!this.included) {
11642 this.included = true;
11643 const parent = this.parent;
11644 const metaProperty = (this.metaProperty =
11645 parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
11646 ? parent.propertyKey
11647 : null);
11648 if (metaProperty) {
11649 if (metaProperty === 'url') {
11650 this.scope.addAccessedGlobalsByFormat(accessedMetaUrlGlobals);
11651 }
11652 else if (metaProperty.startsWith(FILE_PREFIX) ||
11653 metaProperty.startsWith(ASSET_PREFIX) ||
11654 metaProperty.startsWith(CHUNK_PREFIX)) {
11655 this.scope.addAccessedGlobalsByFormat(accessedFileUrlGlobals);
11656 }
11657 }
11658 }
11659 }
11660 initialise() {
11661 if (this.meta.name === 'import') {
11662 this.context.addImportMeta(this);
11663 }
11664 }
11665 renderFinalMechanism(code, chunkId, format, pluginDriver) {
11666 if (!this.included)
11667 return;
11668 const parent = this.parent;
11669 const metaProperty = this.metaProperty;
11670 if (metaProperty &&
11671 (metaProperty.startsWith(FILE_PREFIX) ||
11672 metaProperty.startsWith(ASSET_PREFIX) ||
11673 metaProperty.startsWith(CHUNK_PREFIX))) {
11674 let referenceId = null;
11675 let assetReferenceId = null;
11676 let chunkReferenceId = null;
11677 let fileName;
11678 if (metaProperty.startsWith(FILE_PREFIX)) {
11679 referenceId = metaProperty.substr(FILE_PREFIX.length);
11680 fileName = this.context.getFileName(referenceId);
11681 }
11682 else if (metaProperty.startsWith(ASSET_PREFIX)) {
11683 this.context.warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, false);
11684 assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
11685 fileName = this.context.getFileName(assetReferenceId);
11686 }
11687 else {
11688 this.context.warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, false);
11689 chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
11690 fileName = this.context.getFileName(chunkReferenceId);
11691 }
11692 const relativePath = index.normalize(path.relative(path.dirname(chunkId), fileName));
11693 let replacement;
11694 if (assetReferenceId !== null) {
11695 replacement = pluginDriver.hookFirstSync('resolveAssetUrl', [
11696 {
11697 assetFileName: fileName,
11698 chunkId,
11699 format,
11700 moduleId: this.context.module.id,
11701 relativeAssetPath: relativePath
11702 }
11703 ]);
11704 }
11705 if (!replacement) {
11706 replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
11707 {
11708 assetReferenceId,
11709 chunkId,
11710 chunkReferenceId,
11711 fileName,
11712 format,
11713 moduleId: this.context.module.id,
11714 referenceId: referenceId || assetReferenceId || chunkReferenceId,
11715 relativePath
11716 }
11717 ]);
11718 }
11719 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
11720 return;
11721 }
11722 const replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
11723 metaProperty,
11724 {
11725 chunkId,
11726 format,
11727 moduleId: this.context.module.id
11728 }
11729 ]);
11730 if (typeof replacement === 'string') {
11731 if (parent instanceof MemberExpression) {
11732 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
11733 }
11734 else {
11735 code.overwrite(this.start, this.end, replacement, { contentOnly: true });
11736 }
11737 }
11738 }
11739}
11740
11741class MethodDefinition extends NodeBase {
11742 hasEffects(options) {
11743 return this.key.hasEffects(options);
11744 }
11745 hasEffectsWhenCalledAtPath(path, callOptions, options) {
11746 return (path.length > 0 || this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, options));
11747 }
11748}
11749
11750class NewExpression extends NodeBase {
11751 bind() {
11752 super.bind();
11753 for (const argument of this.arguments) {
11754 // This will make sure all properties of parameters behave as "unknown"
11755 argument.deoptimizePath(UNKNOWN_PATH);
11756 }
11757 }
11758 hasEffects(options) {
11759 for (const argument of this.arguments) {
11760 if (argument.hasEffects(options))
11761 return true;
11762 }
11763 if (this.annotatedPure)
11764 return false;
11765 return this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, options.getHasEffectsWhenCalledOptions());
11766 }
11767 hasEffectsWhenAccessedAtPath(path, _options) {
11768 return path.length > 1;
11769 }
11770 initialise() {
11771 this.callOptions = CallOptions.create({
11772 args: this.arguments,
11773 callIdentifier: this,
11774 withNew: true
11775 });
11776 }
11777}
11778
11779class SpreadElement extends NodeBase {
11780 bind() {
11781 super.bind();
11782 // Only properties of properties of the argument could become subject to reassignment
11783 // This will also reassign the return values of iterators
11784 this.argument.deoptimizePath([UNKNOWN_KEY, UNKNOWN_KEY]);
11785 }
11786}
11787
11788class ObjectExpression extends NodeBase {
11789 constructor() {
11790 super(...arguments);
11791 this.deoptimizedPaths = new Set();
11792 // We collect deoptimization information if we can resolve a computed property access
11793 this.expressionsToBeDeoptimized = new Map();
11794 this.hasUnknownDeoptimizedProperty = false;
11795 this.propertyMap = null;
11796 this.unmatchablePropertiesRead = [];
11797 this.unmatchablePropertiesWrite = [];
11798 }
11799 bind() {
11800 super.bind();
11801 if (this.propertyMap === null)
11802 this.buildPropertyMap();
11803 }
11804 // We could also track this per-property but this would quickly become much more complex
11805 deoptimizeCache() {
11806 if (!this.hasUnknownDeoptimizedProperty)
11807 this.deoptimizeAllProperties();
11808 }
11809 deoptimizePath(path) {
11810 if (this.hasUnknownDeoptimizedProperty)
11811 return;
11812 if (this.propertyMap === null)
11813 this.buildPropertyMap();
11814 if (path.length === 0) {
11815 this.deoptimizeAllProperties();
11816 return;
11817 }
11818 const key = path[0];
11819 if (path.length === 1) {
11820 if (typeof key !== 'string') {
11821 this.deoptimizeAllProperties();
11822 return;
11823 }
11824 if (!this.deoptimizedPaths.has(key)) {
11825 this.deoptimizedPaths.add(key);
11826 // we only deoptimizeCache exact matches as in all other cases,
11827 // we do not return a literal value or return expression
11828 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
11829 if (expressionsToBeDeoptimized) {
11830 for (const expression of expressionsToBeDeoptimized) {
11831 expression.deoptimizeCache();
11832 }
11833 }
11834 }
11835 }
11836 const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
11837 for (const property of typeof key === 'string'
11838 ? this.propertyMap[key]
11839 ? this.propertyMap[key].propertiesRead
11840 : []
11841 : this.properties) {
11842 property.deoptimizePath(subPath);
11843 }
11844 }
11845 getLiteralValueAtPath(path, recursionTracker, origin) {
11846 if (this.propertyMap === null)
11847 this.buildPropertyMap();
11848 const key = path[0];
11849 if (path.length === 0 ||
11850 this.hasUnknownDeoptimizedProperty ||
11851 typeof key !== 'string' ||
11852 this.deoptimizedPaths.has(key))
11853 return UNKNOWN_VALUE;
11854 if (path.length === 1 &&
11855 !this.propertyMap[key] &&
11856 !objectMembers[key] &&
11857 (this.unmatchablePropertiesRead).length === 0) {
11858 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
11859 if (expressionsToBeDeoptimized) {
11860 expressionsToBeDeoptimized.push(origin);
11861 }
11862 else {
11863 this.expressionsToBeDeoptimized.set(key, [origin]);
11864 }
11865 return undefined;
11866 }
11867 if (!this.propertyMap[key] ||
11868 this.propertyMap[key].exactMatchRead === null ||
11869 this.propertyMap[key].propertiesRead.length > 1) {
11870 return UNKNOWN_VALUE;
11871 }
11872 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
11873 if (expressionsToBeDeoptimized) {
11874 expressionsToBeDeoptimized.push(origin);
11875 }
11876 else {
11877 this.expressionsToBeDeoptimized.set(key, [origin]);
11878 }
11879 return this.propertyMap[key]
11880 .exactMatchRead.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
11881 }
11882 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
11883 if (this.propertyMap === null)
11884 this.buildPropertyMap();
11885 const key = path[0];
11886 if (path.length === 0 ||
11887 this.hasUnknownDeoptimizedProperty ||
11888 typeof key !== 'string' ||
11889 this.deoptimizedPaths.has(key))
11890 return UNKNOWN_EXPRESSION;
11891 if (path.length === 1 &&
11892 objectMembers[key] &&
11893 this.unmatchablePropertiesRead.length === 0 &&
11894 (!this.propertyMap[key] ||
11895 this.propertyMap[key].exactMatchRead === null))
11896 return getMemberReturnExpressionWhenCalled(objectMembers, key);
11897 if (!this.propertyMap[key] ||
11898 this.propertyMap[key].exactMatchRead === null ||
11899 this.propertyMap[key].propertiesRead.length > 1)
11900 return UNKNOWN_EXPRESSION;
11901 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
11902 if (expressionsToBeDeoptimized) {
11903 expressionsToBeDeoptimized.push(origin);
11904 }
11905 else {
11906 this.expressionsToBeDeoptimized.set(key, [origin]);
11907 }
11908 return this.propertyMap[key]
11909 .exactMatchRead.getReturnExpressionWhenCalledAtPath(path.slice(1), recursionTracker, origin);
11910 }
11911 hasEffectsWhenAccessedAtPath(path, options) {
11912 if (path.length === 0)
11913 return false;
11914 const key = path[0];
11915 if (path.length > 1 &&
11916 (this.hasUnknownDeoptimizedProperty ||
11917 typeof key !== 'string' ||
11918 this.deoptimizedPaths.has(key) ||
11919 !this.propertyMap[key] ||
11920 this.propertyMap[key].exactMatchRead === null))
11921 return true;
11922 const subPath = path.slice(1);
11923 for (const property of typeof key !== 'string'
11924 ? this.properties
11925 : this.propertyMap[key]
11926 ? this.propertyMap[key].propertiesRead
11927 : []) {
11928 if (property.hasEffectsWhenAccessedAtPath(subPath, options))
11929 return true;
11930 }
11931 return false;
11932 }
11933 hasEffectsWhenAssignedAtPath(path, options) {
11934 if (path.length === 0)
11935 return false;
11936 const key = path[0];
11937 if (path.length > 1 &&
11938 (this.hasUnknownDeoptimizedProperty ||
11939 typeof key !== 'string' ||
11940 this.deoptimizedPaths.has(key) ||
11941 !this.propertyMap[key] ||
11942 this.propertyMap[key].exactMatchRead === null))
11943 return true;
11944 const subPath = path.slice(1);
11945 for (const property of typeof key !== 'string'
11946 ? this.properties
11947 : path.length > 1
11948 ? this.propertyMap[key].propertiesRead
11949 : this.propertyMap[key]
11950 ? this.propertyMap[key].propertiesSet
11951 : []) {
11952 if (property.hasEffectsWhenAssignedAtPath(subPath, options))
11953 return true;
11954 }
11955 return false;
11956 }
11957 hasEffectsWhenCalledAtPath(path, callOptions, options) {
11958 const key = path[0];
11959 if (path.length === 0 ||
11960 this.hasUnknownDeoptimizedProperty ||
11961 typeof key !== 'string' ||
11962 this.deoptimizedPaths.has(key) ||
11963 (this.propertyMap[key]
11964 ? !this.propertyMap[key].exactMatchRead
11965 : path.length > 1 || !objectMembers[key]))
11966 return true;
11967 const subPath = path.slice(1);
11968 for (const property of this.propertyMap[key]
11969 ? this.propertyMap[key].propertiesRead
11970 : []) {
11971 if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, options))
11972 return true;
11973 }
11974 if (path.length === 1 && objectMembers[key])
11975 return hasMemberEffectWhenCalled(objectMembers, key, this.included, callOptions, options);
11976 return false;
11977 }
11978 render(code, options, { renderedParentType } = BLANK) {
11979 super.render(code, options);
11980 if (renderedParentType === ExpressionStatement) {
11981 code.appendRight(this.start, '(');
11982 code.prependLeft(this.end, ')');
11983 }
11984 }
11985 buildPropertyMap() {
11986 this.propertyMap = Object.create(null);
11987 for (let index = this.properties.length - 1; index >= 0; index--) {
11988 const property = this.properties[index];
11989 if (property instanceof SpreadElement) {
11990 this.unmatchablePropertiesRead.push(property);
11991 continue;
11992 }
11993 const isWrite = property.kind !== 'get';
11994 const isRead = property.kind !== 'set';
11995 let key;
11996 if (property.computed) {
11997 const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
11998 if (keyValue === UNKNOWN_VALUE) {
11999 if (isRead) {
12000 this.unmatchablePropertiesRead.push(property);
12001 }
12002 else {
12003 this.unmatchablePropertiesWrite.push(property);
12004 }
12005 continue;
12006 }
12007 key = String(keyValue);
12008 }
12009 else if (property.key instanceof Identifier$1) {
12010 key = property.key.name;
12011 }
12012 else {
12013 key = String(property.key.value);
12014 }
12015 const propertyMapProperty = this.propertyMap[key];
12016 if (!propertyMapProperty) {
12017 this.propertyMap[key] = {
12018 exactMatchRead: isRead ? property : null,
12019 exactMatchWrite: isWrite ? property : null,
12020 propertiesRead: isRead ? [property, ...this.unmatchablePropertiesRead] : [],
12021 propertiesSet: isWrite && !isRead ? [property, ...this.unmatchablePropertiesWrite] : []
12022 };
12023 continue;
12024 }
12025 if (isRead && propertyMapProperty.exactMatchRead === null) {
12026 propertyMapProperty.exactMatchRead = property;
12027 propertyMapProperty.propertiesRead.push(property, ...this.unmatchablePropertiesRead);
12028 }
12029 if (isWrite && !isRead && propertyMapProperty.exactMatchWrite === null) {
12030 propertyMapProperty.exactMatchWrite = property;
12031 propertyMapProperty.propertiesSet.push(property, ...this.unmatchablePropertiesWrite);
12032 }
12033 }
12034 }
12035 deoptimizeAllProperties() {
12036 this.hasUnknownDeoptimizedProperty = true;
12037 for (const property of this.properties) {
12038 property.deoptimizePath(UNKNOWN_PATH);
12039 }
12040 for (const expressionsToBeDeoptimized of this.expressionsToBeDeoptimized.values()) {
12041 for (const expression of expressionsToBeDeoptimized) {
12042 expression.deoptimizeCache();
12043 }
12044 }
12045 }
12046}
12047
12048class ObjectPattern extends NodeBase {
12049 addExportedVariables(variables) {
12050 for (const property of this.properties) {
12051 if (property.type === Property) {
12052 property.value.addExportedVariables(variables);
12053 }
12054 else {
12055 property.argument.addExportedVariables(variables);
12056 }
12057 }
12058 }
12059 declare(kind, init) {
12060 const variables = [];
12061 for (const property of this.properties) {
12062 variables.push(...property.declare(kind, init));
12063 }
12064 return variables;
12065 }
12066 deoptimizePath(path) {
12067 if (path.length === 0) {
12068 for (const property of this.properties) {
12069 property.deoptimizePath(path);
12070 }
12071 }
12072 }
12073 hasEffectsWhenAssignedAtPath(path, options) {
12074 if (path.length > 0)
12075 return true;
12076 for (const property of this.properties) {
12077 if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))
12078 return true;
12079 }
12080 return false;
12081 }
12082}
12083
12084class Program$1 extends NodeBase {
12085 hasEffects(options) {
12086 for (const node of this.body) {
12087 if (node.hasEffects(options))
12088 return true;
12089 }
12090 return false;
12091 }
12092 include(includeChildrenRecursively) {
12093 this.included = true;
12094 for (const node of this.body) {
12095 if (includeChildrenRecursively || node.shouldBeIncluded()) {
12096 node.include(includeChildrenRecursively);
12097 }
12098 }
12099 }
12100 render(code, options) {
12101 if (this.body.length) {
12102 renderStatementList(this.body, code, this.start, this.end, options);
12103 }
12104 else {
12105 super.render(code, options);
12106 }
12107 }
12108}
12109
12110class Property$1 extends NodeBase {
12111 constructor() {
12112 super(...arguments);
12113 this.declarationInit = null;
12114 this.returnExpression = null;
12115 }
12116 bind() {
12117 super.bind();
12118 if (this.kind === 'get' && this.returnExpression === null)
12119 this.updateReturnExpression();
12120 if (this.declarationInit !== null) {
12121 this.declarationInit.deoptimizePath([UNKNOWN_KEY, UNKNOWN_KEY]);
12122 }
12123 }
12124 declare(kind, init) {
12125 this.declarationInit = init;
12126 return this.value.declare(kind, UNKNOWN_EXPRESSION);
12127 }
12128 deoptimizeCache() {
12129 // As getter properties directly receive their values from function expressions that always
12130 // have a fixed return value, there is no known situation where a getter is deoptimized.
12131 throw new Error('Unexpected deoptimization');
12132 }
12133 deoptimizePath(path) {
12134 if (this.kind === 'get') {
12135 if (path.length > 0) {
12136 if (this.returnExpression === null)
12137 this.updateReturnExpression();
12138 this.returnExpression.deoptimizePath(path);
12139 }
12140 }
12141 else if (this.kind !== 'set') {
12142 this.value.deoptimizePath(path);
12143 }
12144 }
12145 getLiteralValueAtPath(path, recursionTracker, origin) {
12146 if (this.kind === 'set') {
12147 return UNKNOWN_VALUE;
12148 }
12149 if (this.kind === 'get') {
12150 if (this.returnExpression === null)
12151 this.updateReturnExpression();
12152 return this.returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
12153 }
12154 return this.value.getLiteralValueAtPath(path, recursionTracker, origin);
12155 }
12156 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
12157 if (this.kind === 'set') {
12158 return UNKNOWN_EXPRESSION;
12159 }
12160 if (this.kind === 'get') {
12161 if (this.returnExpression === null)
12162 this.updateReturnExpression();
12163 return this.returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
12164 }
12165 return this.value.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
12166 }
12167 hasEffects(options) {
12168 return this.key.hasEffects(options) || this.value.hasEffects(options);
12169 }
12170 hasEffectsWhenAccessedAtPath(path, options) {
12171 if (this.kind === 'get') {
12172 return (this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, options.getHasEffectsWhenCalledOptions()) ||
12173 (path.length > 0 &&
12174 this.returnExpression.hasEffectsWhenAccessedAtPath(path, options)));
12175 }
12176 return this.value.hasEffectsWhenAccessedAtPath(path, options);
12177 }
12178 hasEffectsWhenAssignedAtPath(path, options) {
12179 if (this.kind === 'get') {
12180 return (path.length === 0 ||
12181 this.returnExpression.hasEffectsWhenAssignedAtPath(path, options));
12182 }
12183 if (this.kind === 'set') {
12184 return (path.length > 0 ||
12185 this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, options.getHasEffectsWhenCalledOptions()));
12186 }
12187 return this.value.hasEffectsWhenAssignedAtPath(path, options);
12188 }
12189 hasEffectsWhenCalledAtPath(path, callOptions, options) {
12190 if (this.kind === 'get') {
12191 return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, options);
12192 }
12193 return this.value.hasEffectsWhenCalledAtPath(path, callOptions, options);
12194 }
12195 initialise() {
12196 this.accessorCallOptions = CallOptions.create({
12197 callIdentifier: this,
12198 withNew: false
12199 });
12200 }
12201 render(code, options) {
12202 if (!this.shorthand) {
12203 this.key.render(code, options);
12204 }
12205 this.value.render(code, options, { isShorthandProperty: this.shorthand });
12206 }
12207 updateReturnExpression() {
12208 this.returnExpression = UNKNOWN_EXPRESSION;
12209 this.returnExpression = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
12210 }
12211}
12212
12213class ReturnStatement$1 extends NodeBase {
12214 hasEffects(options) {
12215 return (!options.ignoreReturnAwaitYield() ||
12216 (this.argument !== null && this.argument.hasEffects(options)));
12217 }
12218 initialise() {
12219 this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
12220 }
12221 render(code, options) {
12222 if (this.argument) {
12223 this.argument.render(code, options);
12224 if (this.argument.start === this.start + 6 /* 'return'.length */) {
12225 code.prependLeft(this.start + 6, ' ');
12226 }
12227 }
12228 }
12229}
12230
12231class SequenceExpression extends NodeBase {
12232 deoptimizePath(path) {
12233 if (path.length > 0)
12234 this.expressions[this.expressions.length - 1].deoptimizePath(path);
12235 }
12236 getLiteralValueAtPath(path, recursionTracker, origin) {
12237 return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
12238 }
12239 hasEffects(options) {
12240 for (const expression of this.expressions) {
12241 if (expression.hasEffects(options))
12242 return true;
12243 }
12244 return false;
12245 }
12246 hasEffectsWhenAccessedAtPath(path, options) {
12247 return (path.length > 0 &&
12248 this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, options));
12249 }
12250 hasEffectsWhenAssignedAtPath(path, options) {
12251 return (path.length === 0 ||
12252 this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, options));
12253 }
12254 hasEffectsWhenCalledAtPath(path, callOptions, options) {
12255 return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, options);
12256 }
12257 include(includeChildrenRecursively) {
12258 this.included = true;
12259 for (let i = 0; i < this.expressions.length - 1; i++) {
12260 const node = this.expressions[i];
12261 if (includeChildrenRecursively || node.shouldBeIncluded())
12262 node.include(includeChildrenRecursively);
12263 }
12264 this.expressions[this.expressions.length - 1].include(includeChildrenRecursively);
12265 }
12266 render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) {
12267 let includedNodes = 0;
12268 for (const { node, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
12269 if (!node.included) {
12270 treeshakeNode(node, code, start, end);
12271 continue;
12272 }
12273 includedNodes++;
12274 if (node === this.expressions[this.expressions.length - 1] && includedNodes === 1) {
12275 node.render(code, options, {
12276 isCalleeOfRenderedParent: renderedParentType
12277 ? isCalleeOfRenderedParent
12278 : this.parent.callee === this,
12279 renderedParentType: renderedParentType || this.parent.type
12280 });
12281 }
12282 else {
12283 node.render(code, options);
12284 }
12285 }
12286 }
12287}
12288
12289class SwitchCase extends NodeBase {
12290 include(includeChildrenRecursively) {
12291 this.included = true;
12292 if (this.test)
12293 this.test.include(includeChildrenRecursively);
12294 for (const node of this.consequent) {
12295 if (includeChildrenRecursively || node.shouldBeIncluded())
12296 node.include(includeChildrenRecursively);
12297 }
12298 }
12299 render(code, options) {
12300 if (this.consequent.length) {
12301 this.test && this.test.render(code, options);
12302 const testEnd = this.test
12303 ? this.test.end
12304 : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
12305 const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
12306 renderStatementList(this.consequent, code, consequentStart, this.end, options);
12307 }
12308 else {
12309 super.render(code, options);
12310 }
12311 }
12312}
12313
12314class SwitchStatement extends NodeBase {
12315 createScope(parentScope) {
12316 this.scope = new BlockScope(parentScope);
12317 }
12318 hasEffects(options) {
12319 return super.hasEffects(options.setIgnoreBreakStatements());
12320 }
12321}
12322
12323class TaggedTemplateExpression extends NodeBase {
12324 bind() {
12325 super.bind();
12326 if (this.tag.type === Identifier) {
12327 const variable = this.scope.findVariable(this.tag.name);
12328 if (variable.isNamespace) {
12329 this.context.error({
12330 code: 'CANNOT_CALL_NAMESPACE',
12331 message: `Cannot call a namespace ('${this.tag.name}')`
12332 }, this.start);
12333 }
12334 if (this.tag.name === 'eval') {
12335 this.context.warn({
12336 code: 'EVAL',
12337 message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
12338 url: 'https://rollupjs.org/guide/en/#avoiding-eval'
12339 }, this.start);
12340 }
12341 }
12342 }
12343 hasEffects(options) {
12344 return (super.hasEffects(options) ||
12345 this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, options.getHasEffectsWhenCalledOptions()));
12346 }
12347 initialise() {
12348 this.callOptions = CallOptions.create({
12349 callIdentifier: this,
12350 withNew: false
12351 });
12352 }
12353}
12354
12355class TemplateElement extends NodeBase {
12356 hasEffects(_options) {
12357 return false;
12358 }
12359}
12360
12361class TemplateLiteral extends NodeBase {
12362 getLiteralValueAtPath(path) {
12363 if (path.length > 0 || this.quasis.length !== 1) {
12364 return UNKNOWN_VALUE;
12365 }
12366 return this.quasis[0].value.cooked;
12367 }
12368 render(code, options) {
12369 code.indentExclusionRanges.push([this.start, this.end]);
12370 super.render(code, options);
12371 }
12372}
12373
12374class ModuleScope extends ChildScope {
12375 constructor(parent, context) {
12376 super(parent);
12377 this.context = context;
12378 this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
12379 }
12380 addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
12381 const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
12382 this.variables.set('default', variable);
12383 return variable;
12384 }
12385 addNamespaceMemberAccess(_name, variable) {
12386 if (variable instanceof GlobalVariable) {
12387 this.accessedOutsideVariables.set(variable.name, variable);
12388 }
12389 }
12390 deconflict(format) {
12391 // all module level variables are already deconflicted when deconflicting the chunk
12392 for (const scope of this.children)
12393 scope.deconflict(format);
12394 }
12395 findLexicalBoundary() {
12396 return this;
12397 }
12398 findVariable(name) {
12399 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
12400 if (knownVariable) {
12401 return knownVariable;
12402 }
12403 const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
12404 if (variable instanceof GlobalVariable) {
12405 this.accessedOutsideVariables.set(name, variable);
12406 }
12407 return variable;
12408 }
12409}
12410
12411class ThisExpression extends NodeBase {
12412 bind() {
12413 super.bind();
12414 this.variable = this.scope.findVariable('this');
12415 }
12416 hasEffectsWhenAccessedAtPath(path, options) {
12417 return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, options);
12418 }
12419 hasEffectsWhenAssignedAtPath(path, options) {
12420 return this.variable.hasEffectsWhenAssignedAtPath(path, options);
12421 }
12422 initialise() {
12423 this.alias =
12424 this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
12425 if (this.alias === 'undefined') {
12426 this.context.warn({
12427 code: 'THIS_IS_UNDEFINED',
12428 message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
12429 url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
12430 }, this.start);
12431 }
12432 }
12433 render(code, _options) {
12434 if (this.alias !== null) {
12435 code.overwrite(this.start, this.end, this.alias, {
12436 contentOnly: false,
12437 storeName: true
12438 });
12439 }
12440 }
12441}
12442
12443class ThrowStatement extends NodeBase {
12444 hasEffects(_options) {
12445 return true;
12446 }
12447}
12448
12449class TryStatement extends NodeBase {
12450 constructor() {
12451 super(...arguments);
12452 this.directlyIncluded = false;
12453 }
12454 hasEffects(options) {
12455 return (this.block.body.length > 0 ||
12456 (this.handler !== null && this.handler.hasEffects(options)) ||
12457 (this.finalizer !== null && this.finalizer.hasEffects(options)));
12458 }
12459 include(includeChildrenRecursively) {
12460 if (!this.directlyIncluded || !this.context.tryCatchDeoptimization) {
12461 this.included = true;
12462 this.directlyIncluded = true;
12463 this.block.include(this.context.tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
12464 }
12465 if (this.handler !== null) {
12466 this.handler.include(includeChildrenRecursively);
12467 }
12468 if (this.finalizer !== null) {
12469 this.finalizer.include(includeChildrenRecursively);
12470 }
12471 }
12472}
12473
12474const unaryOperators = {
12475 '!': value => !value,
12476 '+': value => +value,
12477 '-': value => -value,
12478 delete: () => UNKNOWN_VALUE,
12479 typeof: value => typeof value,
12480 void: () => undefined,
12481 '~': value => ~value
12482};
12483class UnaryExpression extends NodeBase {
12484 bind() {
12485 super.bind();
12486 if (this.operator === 'delete') {
12487 this.argument.deoptimizePath(EMPTY_PATH);
12488 }
12489 }
12490 getLiteralValueAtPath(path, recursionTracker, origin) {
12491 if (path.length > 0)
12492 return UNKNOWN_VALUE;
12493 const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
12494 if (argumentValue === UNKNOWN_VALUE)
12495 return UNKNOWN_VALUE;
12496 return unaryOperators[this.operator](argumentValue);
12497 }
12498 hasEffects(options) {
12499 return (this.argument.hasEffects(options) ||
12500 (this.operator === 'delete' &&
12501 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options)));
12502 }
12503 hasEffectsWhenAccessedAtPath(path, _options) {
12504 if (this.operator === 'void') {
12505 return path.length > 0;
12506 }
12507 return path.length > 1;
12508 }
12509}
12510
12511class UnknownNode extends NodeBase {
12512 hasEffects(_options) {
12513 return true;
12514 }
12515 include() {
12516 super.include(true);
12517 }
12518}
12519
12520class UpdateExpression extends NodeBase {
12521 bind() {
12522 super.bind();
12523 this.argument.deoptimizePath(EMPTY_PATH);
12524 if (this.argument instanceof Identifier$1) {
12525 const variable = this.scope.findVariable(this.argument.name);
12526 variable.isReassigned = true;
12527 }
12528 }
12529 hasEffects(options) {
12530 return (this.argument.hasEffects(options) ||
12531 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options));
12532 }
12533 hasEffectsWhenAccessedAtPath(path, _options) {
12534 return path.length > 1;
12535 }
12536 render(code, options) {
12537 this.argument.render(code, options);
12538 const variable = this.argument.variable;
12539 if (options.format === 'system' && variable && variable.exportName) {
12540 const name = variable.getName();
12541 if (this.prefix) {
12542 code.overwrite(this.start, this.end, `exports('${variable.exportName}', ${this.operator}${name})`);
12543 }
12544 else {
12545 let op;
12546 switch (this.operator) {
12547 case '++':
12548 op = `${name} + 1`;
12549 break;
12550 case '--':
12551 op = `${name} - 1`;
12552 break;
12553 }
12554 code.overwrite(this.start, this.end, `(exports('${variable.exportName}', ${op}), ${name}${this.operator})`);
12555 }
12556 }
12557 }
12558}
12559
12560function isReassignedExportsMember(variable) {
12561 return variable.renderBaseName !== null && variable.exportName !== null && variable.isReassigned;
12562}
12563function areAllDeclarationsIncludedAndNotExported(declarations) {
12564 for (const declarator of declarations) {
12565 if (!declarator.included) {
12566 return false;
12567 }
12568 if (declarator.id.type === Identifier) {
12569 if (declarator.id.variable.exportName)
12570 return false;
12571 }
12572 else {
12573 const exportedVariables = [];
12574 declarator.id.addExportedVariables(exportedVariables);
12575 if (exportedVariables.length > 0)
12576 return false;
12577 }
12578 }
12579 return true;
12580}
12581class VariableDeclaration$1 extends NodeBase {
12582 deoptimizePath(_path) {
12583 for (const declarator of this.declarations) {
12584 declarator.deoptimizePath(EMPTY_PATH);
12585 }
12586 }
12587 hasEffectsWhenAssignedAtPath(_path, _options) {
12588 return false;
12589 }
12590 include(includeChildrenRecursively) {
12591 this.included = true;
12592 for (const declarator of this.declarations) {
12593 if (includeChildrenRecursively || declarator.shouldBeIncluded())
12594 declarator.include(includeChildrenRecursively);
12595 }
12596 }
12597 includeWithAllDeclaredVariables(includeChildrenRecursively) {
12598 this.included = true;
12599 for (const declarator of this.declarations) {
12600 declarator.include(includeChildrenRecursively);
12601 }
12602 }
12603 initialise() {
12604 for (const declarator of this.declarations) {
12605 declarator.declareDeclarator(this.kind);
12606 }
12607 }
12608 render(code, options, nodeRenderOptions = BLANK) {
12609 if (areAllDeclarationsIncludedAndNotExported(this.declarations)) {
12610 for (const declarator of this.declarations) {
12611 declarator.render(code, options);
12612 }
12613 if (!nodeRenderOptions.isNoStatement &&
12614 code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
12615 code.appendLeft(this.end, ';');
12616 }
12617 }
12618 else {
12619 this.renderReplacedDeclarations(code, options, nodeRenderOptions);
12620 }
12621 }
12622 renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, addSemicolon, systemPatternExports) {
12623 if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
12624 code.remove(this.end - 1, this.end);
12625 }
12626 if (addSemicolon) {
12627 separatorString += ';';
12628 }
12629 if (lastSeparatorPos !== null) {
12630 if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
12631 (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
12632 code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
12633 actualContentEnd--;
12634 if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
12635 actualContentEnd--;
12636 }
12637 }
12638 if (actualContentEnd === lastSeparatorPos + 1) {
12639 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
12640 }
12641 else {
12642 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
12643 code.remove(actualContentEnd, renderedContentEnd);
12644 }
12645 }
12646 else {
12647 code.appendLeft(renderedContentEnd, separatorString);
12648 }
12649 if (systemPatternExports.length > 0) {
12650 code.appendLeft(renderedContentEnd, ' ' + getSystemExportStatement(systemPatternExports));
12651 }
12652 }
12653 renderReplacedDeclarations(code, options, { start = this.start, end = this.end, isNoStatement }) {
12654 const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
12655 let actualContentEnd, renderedContentEnd;
12656 if (/\n\s*$/.test(code.slice(this.start, separatedNodes[0].start))) {
12657 renderedContentEnd = this.start + this.kind.length;
12658 }
12659 else {
12660 renderedContentEnd = separatedNodes[0].start;
12661 }
12662 let lastSeparatorPos = renderedContentEnd - 1;
12663 code.remove(this.start, lastSeparatorPos);
12664 let isInDeclaration = false;
12665 let hasRenderedContent = false;
12666 let separatorString = '', leadingString, nextSeparatorString;
12667 const systemPatternExports = [];
12668 for (const { node, start, separator, contentEnd, end } of separatedNodes) {
12669 if (!node.included ||
12670 (node.id instanceof Identifier$1 &&
12671 isReassignedExportsMember(node.id.variable) &&
12672 node.init === null)) {
12673 code.remove(start, end);
12674 continue;
12675 }
12676 leadingString = '';
12677 nextSeparatorString = '';
12678 if (node.id instanceof Identifier$1 &&
12679 isReassignedExportsMember(node.id.variable)) {
12680 if (hasRenderedContent) {
12681 separatorString += ';';
12682 }
12683 isInDeclaration = false;
12684 }
12685 else {
12686 if (options.format === 'system' && node.init !== null) {
12687 if (node.id.type !== Identifier) {
12688 node.id.addExportedVariables(systemPatternExports);
12689 }
12690 else if (node.id.variable.exportName) {
12691 code.prependLeft(code.original.indexOf('=', node.id.end) + 1, ` exports('${node.id.variable.safeExportName ||
12692 node.id.variable.exportName}',`);
12693 nextSeparatorString += ')';
12694 }
12695 }
12696 if (isInDeclaration) {
12697 separatorString += ',';
12698 }
12699 else {
12700 if (hasRenderedContent) {
12701 separatorString += ';';
12702 }
12703 leadingString += `${this.kind} `;
12704 isInDeclaration = true;
12705 }
12706 }
12707 if (renderedContentEnd === lastSeparatorPos + 1) {
12708 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
12709 }
12710 else {
12711 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
12712 code.appendLeft(renderedContentEnd, leadingString);
12713 }
12714 node.render(code, options);
12715 actualContentEnd = contentEnd;
12716 renderedContentEnd = end;
12717 hasRenderedContent = true;
12718 lastSeparatorPos = separator;
12719 separatorString = nextSeparatorString;
12720 }
12721 if (hasRenderedContent) {
12722 this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, !isNoStatement, systemPatternExports);
12723 }
12724 else {
12725 code.remove(start, end);
12726 }
12727 }
12728}
12729
12730class VariableDeclarator extends NodeBase {
12731 declareDeclarator(kind) {
12732 this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
12733 }
12734 deoptimizePath(path) {
12735 this.id.deoptimizePath(path);
12736 }
12737 render(code, options) {
12738 // This can happen for hoisted variables in dead branches
12739 if (this.init !== null && !this.init.included) {
12740 code.remove(this.id.end, this.end);
12741 this.id.render(code, options);
12742 }
12743 else {
12744 super.render(code, options);
12745 }
12746 }
12747}
12748
12749class WhileStatement extends NodeBase {
12750 hasEffects(options) {
12751 return (this.test.hasEffects(options) || this.body.hasEffects(options.setIgnoreBreakStatements()));
12752 }
12753}
12754
12755class YieldExpression extends NodeBase {
12756 bind() {
12757 super.bind();
12758 if (this.argument !== null) {
12759 this.argument.deoptimizePath(UNKNOWN_PATH);
12760 }
12761 }
12762 hasEffects(options) {
12763 return (!options.ignoreReturnAwaitYield() ||
12764 (this.argument !== null && this.argument.hasEffects(options)));
12765 }
12766 render(code, options) {
12767 if (this.argument) {
12768 this.argument.render(code, options);
12769 if (this.argument.start === this.start + 5 /* 'yield'.length */) {
12770 code.prependLeft(this.start + 5, ' ');
12771 }
12772 }
12773 }
12774}
12775
12776const nodeConstructors = {
12777 ArrayExpression,
12778 ArrayPattern,
12779 ArrowFunctionExpression,
12780 AssignmentExpression,
12781 AssignmentPattern,
12782 AwaitExpression,
12783 BinaryExpression,
12784 BlockStatement: BlockStatement$1,
12785 BreakStatement,
12786 CallExpression: CallExpression$1,
12787 CatchClause,
12788 ClassBody,
12789 ClassDeclaration,
12790 ClassExpression,
12791 ConditionalExpression,
12792 DoWhileStatement,
12793 EmptyStatement,
12794 ExportAllDeclaration: ExportAllDeclaration$1,
12795 ExportDefaultDeclaration,
12796 ExportNamedDeclaration,
12797 ExpressionStatement: ExpressionStatement$1,
12798 ForInStatement,
12799 ForOfStatement,
12800 ForStatement,
12801 FunctionDeclaration,
12802 FunctionExpression: FunctionExpression$1,
12803 Identifier: Identifier$1,
12804 IfStatement,
12805 Import,
12806 ImportDeclaration,
12807 LabeledStatement,
12808 Literal,
12809 LogicalExpression,
12810 MemberExpression,
12811 MetaProperty,
12812 MethodDefinition,
12813 NewExpression,
12814 ObjectExpression,
12815 ObjectPattern,
12816 Program: Program$1,
12817 Property: Property$1,
12818 RestElement,
12819 ReturnStatement: ReturnStatement$1,
12820 SequenceExpression,
12821 SpreadElement,
12822 SwitchCase,
12823 SwitchStatement,
12824 TaggedTemplateExpression,
12825 TemplateElement,
12826 TemplateLiteral,
12827 ThisExpression,
12828 ThrowStatement,
12829 TryStatement,
12830 UnaryExpression,
12831 UnknownNode,
12832 UpdateExpression,
12833 VariableDeclaration: VariableDeclaration$1,
12834 VariableDeclarator,
12835 WhileStatement,
12836 YieldExpression
12837};
12838
12839function getOriginalLocation(sourcemapChain, location) {
12840 // This cast is guaranteed. If it were a missing Map, it wouldn't have a mappings.
12841 const filteredSourcemapChain = sourcemapChain.filter(sourcemap => sourcemap.mappings);
12842 while (filteredSourcemapChain.length > 0) {
12843 const sourcemap = filteredSourcemapChain.pop();
12844 const line = sourcemap.mappings[location.line - 1];
12845 let locationFound = false;
12846 if (line !== undefined) {
12847 for (const segment of line) {
12848 if (segment[0] >= location.column) {
12849 if (segment.length === 1)
12850 break;
12851 location = {
12852 column: segment[3],
12853 line: segment[2] + 1,
12854 name: segment.length === 5 ? sourcemap.names[segment[4]] : undefined,
12855 source: sourcemap.sources[segment[1]]
12856 };
12857 locationFound = true;
12858 break;
12859 }
12860 }
12861 }
12862 if (!locationFound) {
12863 throw new Error("Can't resolve original location of error.");
12864 }
12865 }
12866 return location;
12867}
12868
12869// AST walker module for Mozilla Parser API compatible trees
12870
12871function skipThrough(node, st, c) { c(node, st); }
12872function ignore(_node, _st, _c) {}
12873
12874// Node walkers.
12875
12876var base$1 = {};
12877
12878base$1.Program = base$1.BlockStatement = function (node, st, c) {
12879 for (var i = 0, list = node.body; i < list.length; i += 1)
12880 {
12881 var stmt = list[i];
12882
12883 c(stmt, st, "Statement");
12884 }
12885};
12886base$1.Statement = skipThrough;
12887base$1.EmptyStatement = ignore;
12888base$1.ExpressionStatement = base$1.ParenthesizedExpression =
12889 function (node, st, c) { return c(node.expression, st, "Expression"); };
12890base$1.IfStatement = function (node, st, c) {
12891 c(node.test, st, "Expression");
12892 c(node.consequent, st, "Statement");
12893 if (node.alternate) { c(node.alternate, st, "Statement"); }
12894};
12895base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
12896base$1.BreakStatement = base$1.ContinueStatement = ignore;
12897base$1.WithStatement = function (node, st, c) {
12898 c(node.object, st, "Expression");
12899 c(node.body, st, "Statement");
12900};
12901base$1.SwitchStatement = function (node, st, c) {
12902 c(node.discriminant, st, "Expression");
12903 for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
12904 var cs = list$1[i$1];
12905
12906 if (cs.test) { c(cs.test, st, "Expression"); }
12907 for (var i = 0, list = cs.consequent; i < list.length; i += 1)
12908 {
12909 var cons = list[i];
12910
12911 c(cons, st, "Statement");
12912 }
12913 }
12914};
12915base$1.SwitchCase = function (node, st, c) {
12916 if (node.test) { c(node.test, st, "Expression"); }
12917 for (var i = 0, list = node.consequent; i < list.length; i += 1)
12918 {
12919 var cons = list[i];
12920
12921 c(cons, st, "Statement");
12922 }
12923};
12924base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
12925 if (node.argument) { c(node.argument, st, "Expression"); }
12926};
12927base$1.ThrowStatement = base$1.SpreadElement =
12928 function (node, st, c) { return c(node.argument, st, "Expression"); };
12929base$1.TryStatement = function (node, st, c) {
12930 c(node.block, st, "Statement");
12931 if (node.handler) { c(node.handler, st); }
12932 if (node.finalizer) { c(node.finalizer, st, "Statement"); }
12933};
12934base$1.CatchClause = function (node, st, c) {
12935 if (node.param) { c(node.param, st, "Pattern"); }
12936 c(node.body, st, "Statement");
12937};
12938base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
12939 c(node.test, st, "Expression");
12940 c(node.body, st, "Statement");
12941};
12942base$1.ForStatement = function (node, st, c) {
12943 if (node.init) { c(node.init, st, "ForInit"); }
12944 if (node.test) { c(node.test, st, "Expression"); }
12945 if (node.update) { c(node.update, st, "Expression"); }
12946 c(node.body, st, "Statement");
12947};
12948base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
12949 c(node.left, st, "ForInit");
12950 c(node.right, st, "Expression");
12951 c(node.body, st, "Statement");
12952};
12953base$1.ForInit = function (node, st, c) {
12954 if (node.type === "VariableDeclaration") { c(node, st); }
12955 else { c(node, st, "Expression"); }
12956};
12957base$1.DebuggerStatement = ignore;
12958
12959base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
12960base$1.VariableDeclaration = function (node, st, c) {
12961 for (var i = 0, list = node.declarations; i < list.length; i += 1)
12962 {
12963 var decl = list[i];
12964
12965 c(decl, st);
12966 }
12967};
12968base$1.VariableDeclarator = function (node, st, c) {
12969 c(node.id, st, "Pattern");
12970 if (node.init) { c(node.init, st, "Expression"); }
12971};
12972
12973base$1.Function = function (node, st, c) {
12974 if (node.id) { c(node.id, st, "Pattern"); }
12975 for (var i = 0, list = node.params; i < list.length; i += 1)
12976 {
12977 var param = list[i];
12978
12979 c(param, st, "Pattern");
12980 }
12981 c(node.body, st, node.expression ? "Expression" : "Statement");
12982};
12983
12984base$1.Pattern = function (node, st, c) {
12985 if (node.type === "Identifier")
12986 { c(node, st, "VariablePattern"); }
12987 else if (node.type === "MemberExpression")
12988 { c(node, st, "MemberPattern"); }
12989 else
12990 { c(node, st); }
12991};
12992base$1.VariablePattern = ignore;
12993base$1.MemberPattern = skipThrough;
12994base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
12995base$1.ArrayPattern = function (node, st, c) {
12996 for (var i = 0, list = node.elements; i < list.length; i += 1) {
12997 var elt = list[i];
12998
12999 if (elt) { c(elt, st, "Pattern"); }
13000 }
13001};
13002base$1.ObjectPattern = function (node, st, c) {
13003 for (var i = 0, list = node.properties; i < list.length; i += 1) {
13004 var prop = list[i];
13005
13006 if (prop.type === "Property") {
13007 if (prop.computed) { c(prop.key, st, "Expression"); }
13008 c(prop.value, st, "Pattern");
13009 } else if (prop.type === "RestElement") {
13010 c(prop.argument, st, "Pattern");
13011 }
13012 }
13013};
13014
13015base$1.Expression = skipThrough;
13016base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
13017base$1.ArrayExpression = function (node, st, c) {
13018 for (var i = 0, list = node.elements; i < list.length; i += 1) {
13019 var elt = list[i];
13020
13021 if (elt) { c(elt, st, "Expression"); }
13022 }
13023};
13024base$1.ObjectExpression = function (node, st, c) {
13025 for (var i = 0, list = node.properties; i < list.length; i += 1)
13026 {
13027 var prop = list[i];
13028
13029 c(prop, st);
13030 }
13031};
13032base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
13033base$1.SequenceExpression = function (node, st, c) {
13034 for (var i = 0, list = node.expressions; i < list.length; i += 1)
13035 {
13036 var expr = list[i];
13037
13038 c(expr, st, "Expression");
13039 }
13040};
13041base$1.TemplateLiteral = function (node, st, c) {
13042 for (var i = 0, list = node.quasis; i < list.length; i += 1)
13043 {
13044 var quasi = list[i];
13045
13046 c(quasi, st);
13047 }
13048
13049 for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
13050 {
13051 var expr = list$1[i$1];
13052
13053 c(expr, st, "Expression");
13054 }
13055};
13056base$1.TemplateElement = ignore;
13057base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
13058 c(node.argument, st, "Expression");
13059};
13060base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
13061 c(node.left, st, "Expression");
13062 c(node.right, st, "Expression");
13063};
13064base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
13065 c(node.left, st, "Pattern");
13066 c(node.right, st, "Expression");
13067};
13068base$1.ConditionalExpression = function (node, st, c) {
13069 c(node.test, st, "Expression");
13070 c(node.consequent, st, "Expression");
13071 c(node.alternate, st, "Expression");
13072};
13073base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
13074 c(node.callee, st, "Expression");
13075 if (node.arguments)
13076 { for (var i = 0, list = node.arguments; i < list.length; i += 1)
13077 {
13078 var arg = list[i];
13079
13080 c(arg, st, "Expression");
13081 } }
13082};
13083base$1.MemberExpression = function (node, st, c) {
13084 c(node.object, st, "Expression");
13085 if (node.computed) { c(node.property, st, "Expression"); }
13086};
13087base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
13088 if (node.declaration)
13089 { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
13090 if (node.source) { c(node.source, st, "Expression"); }
13091};
13092base$1.ExportAllDeclaration = function (node, st, c) {
13093 c(node.source, st, "Expression");
13094};
13095base$1.ImportDeclaration = function (node, st, c) {
13096 for (var i = 0, list = node.specifiers; i < list.length; i += 1)
13097 {
13098 var spec = list[i];
13099
13100 c(spec, st);
13101 }
13102 c(node.source, st, "Expression");
13103};
13104base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = base$1.Import = ignore;
13105
13106base$1.TaggedTemplateExpression = function (node, st, c) {
13107 c(node.tag, st, "Expression");
13108 c(node.quasi, st, "Expression");
13109};
13110base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
13111base$1.Class = function (node, st, c) {
13112 if (node.id) { c(node.id, st, "Pattern"); }
13113 if (node.superClass) { c(node.superClass, st, "Expression"); }
13114 c(node.body, st);
13115};
13116base$1.ClassBody = function (node, st, c) {
13117 for (var i = 0, list = node.body; i < list.length; i += 1)
13118 {
13119 var elt = list[i];
13120
13121 c(elt, st);
13122 }
13123};
13124base$1.MethodDefinition = base$1.Property = function (node, st, c) {
13125 if (node.computed) { c(node.key, st, "Expression"); }
13126 c(node.value, st, "Expression");
13127};
13128
13129// @ts-ignore
13130function handlePureAnnotationsOfNode(node, state, type = node.type) {
13131 let commentNode = state.commentNodes[state.commentIndex];
13132 while (commentNode && node.start >= commentNode.end) {
13133 markPureNode(node, commentNode);
13134 commentNode = state.commentNodes[++state.commentIndex];
13135 }
13136 if (commentNode && commentNode.end <= node.end) {
13137 base$1[type](node, state, handlePureAnnotationsOfNode);
13138 }
13139}
13140function markPureNode(node, comment) {
13141 if (node.annotations) {
13142 node.annotations.push(comment);
13143 }
13144 else {
13145 node.annotations = [comment];
13146 }
13147 if (node.type === 'ExpressionStatement') {
13148 node = node.expression;
13149 }
13150 if (node.type === 'CallExpression' || node.type === 'NewExpression') {
13151 node.annotatedPure = true;
13152 }
13153}
13154const pureCommentRegex = /[@#]__PURE__/;
13155const isPureComment = (comment) => pureCommentRegex.test(comment.text);
13156function markPureCallExpressions(comments, esTreeAst) {
13157 handlePureAnnotationsOfNode(esTreeAst, {
13158 commentIndex: 0,
13159 commentNodes: comments.filter(isPureComment)
13160 });
13161}
13162
13163// this looks ridiculous, but it prevents sourcemap tooling from mistaking
13164// this for an actual sourceMappingURL
13165let SOURCEMAPPING_URL = 'sourceMa';
13166SOURCEMAPPING_URL += 'ppingURL';
13167const SOURCEMAPPING_URL_RE = new RegExp(`^#\\s+${SOURCEMAPPING_URL}=.+\\n?`);
13168
13169const NOOP = () => { };
13170let getStartTime = () => [0, 0];
13171let getElapsedTime = () => 0;
13172let getMemory = () => 0;
13173let timers = {};
13174const normalizeHrTime = (time) => time[0] * 1e3 + time[1] / 1e6;
13175function setTimeHelpers() {
13176 if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
13177 getStartTime = process.hrtime.bind(process);
13178 getElapsedTime = previous => normalizeHrTime(process.hrtime(previous));
13179 }
13180 else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
13181 getStartTime = () => [performance.now(), 0];
13182 getElapsedTime = previous => performance.now() - previous[0];
13183 }
13184 if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
13185 getMemory = () => process.memoryUsage().heapUsed;
13186 }
13187}
13188function getPersistedLabel(label, level) {
13189 switch (level) {
13190 case 1:
13191 return `# ${label}`;
13192 case 2:
13193 return `## ${label}`;
13194 case 3:
13195 return label;
13196 default:
13197 return `${' '.repeat(level - 4)}- ${label}`;
13198 }
13199}
13200function timeStartImpl(label, level = 3) {
13201 label = getPersistedLabel(label, level);
13202 if (!timers.hasOwnProperty(label)) {
13203 timers[label] = {
13204 memory: 0,
13205 startMemory: undefined,
13206 startTime: undefined,
13207 time: 0,
13208 totalMemory: 0
13209 };
13210 }
13211 const currentMemory = getMemory();
13212 timers[label].startTime = getStartTime();
13213 timers[label].startMemory = currentMemory;
13214}
13215function timeEndImpl(label, level = 3) {
13216 label = getPersistedLabel(label, level);
13217 if (timers.hasOwnProperty(label)) {
13218 const currentMemory = getMemory();
13219 timers[label].time += getElapsedTime(timers[label].startTime);
13220 timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
13221 timers[label].memory += currentMemory - timers[label].startMemory;
13222 }
13223}
13224function getTimings() {
13225 const newTimings = {};
13226 Object.keys(timers).forEach(label => {
13227 newTimings[label] = [timers[label].time, timers[label].memory, timers[label].totalMemory];
13228 });
13229 return newTimings;
13230}
13231let timeStart = NOOP, timeEnd = NOOP;
13232const TIMED_PLUGIN_HOOKS = {
13233 load: true,
13234 ongenerate: true,
13235 onwrite: true,
13236 resolveDynamicImport: true,
13237 resolveId: true,
13238 transform: true,
13239 transformBundle: true
13240};
13241function getPluginWithTimers(plugin, index) {
13242 const timedPlugin = {};
13243 for (const hook of Object.keys(plugin)) {
13244 if (TIMED_PLUGIN_HOOKS[hook] === true) {
13245 let timerLabel = `plugin ${index}`;
13246 if (plugin.name) {
13247 timerLabel += ` (${plugin.name})`;
13248 }
13249 timerLabel += ` - ${hook}`;
13250 timedPlugin[hook] = function () {
13251 timeStart(timerLabel, 4);
13252 const result = plugin[hook].apply(this === timedPlugin ? plugin : this, arguments);
13253 timeEnd(timerLabel, 4);
13254 if (result && typeof result.then === 'function') {
13255 timeStart(`${timerLabel} (async)`, 4);
13256 result.then(() => timeEnd(`${timerLabel} (async)`, 4));
13257 }
13258 return result;
13259 };
13260 }
13261 else {
13262 timedPlugin[hook] = plugin[hook];
13263 }
13264 }
13265 return timedPlugin;
13266}
13267function initialiseTimers(inputOptions) {
13268 if (inputOptions.perf) {
13269 timers = {};
13270 setTimeHelpers();
13271 timeStart = timeStartImpl;
13272 timeEnd = timeEndImpl;
13273 inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
13274 }
13275 else {
13276 timeStart = NOOP;
13277 timeEnd = NOOP;
13278 }
13279}
13280
13281const defaultAcornOptions = {
13282 ecmaVersion: 2019,
13283 preserveParens: false,
13284 sourceType: 'module'
13285};
13286function tryParse(module, Parser, acornOptions) {
13287 try {
13288 return Parser.parse(module.code, Object.assign({}, defaultAcornOptions, acornOptions, { onComment: (block, text, start, end) => module.comments.push({ block, text, start, end }) }));
13289 }
13290 catch (err) {
13291 let message = err.message.replace(/ \(\d+:\d+\)$/, '');
13292 if (module.id.endsWith('.json')) {
13293 message += ' (Note that you need rollup-plugin-json to import JSON files)';
13294 }
13295 else if (!module.id.endsWith('.js')) {
13296 message += ' (Note that you need plugins to import files that are not JavaScript)';
13297 }
13298 module.error({
13299 code: 'PARSE_ERROR',
13300 message
13301 }, err.pos);
13302 }
13303}
13304function handleMissingExport(exportName, importingModule, importedModule, importerStart) {
13305 importingModule.error({
13306 code: 'MISSING_EXPORT',
13307 message: `'${exportName}' is not exported by ${index.relativeId(importedModule)}`,
13308 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module-`
13309 }, importerStart);
13310}
13311const MISSING_EXPORT_SHIM_DESCRIPTION = {
13312 identifier: null,
13313 localName: MISSING_EXPORT_SHIM_VARIABLE
13314};
13315class Module {
13316 constructor(graph, id, moduleSideEffects, isEntry) {
13317 this.chunkFileNames = new Set();
13318 this.chunkName = null;
13319 this.comments = [];
13320 this.dependencies = [];
13321 this.dynamicallyImportedBy = [];
13322 this.dynamicDependencies = [];
13323 this.dynamicImports = [];
13324 this.entryPointsHash = new Uint8Array(10);
13325 this.execIndex = Infinity;
13326 this.exportAllModules = null;
13327 this.exportAllSources = [];
13328 this.exports = Object.create(null);
13329 this.exportsAll = Object.create(null);
13330 this.exportShimVariable = new ExportShimVariable(this);
13331 this.facadeChunk = null;
13332 this.importDescriptions = Object.create(null);
13333 this.importMetas = [];
13334 this.imports = new Set();
13335 this.isExecuted = false;
13336 this.isUserDefinedEntryPoint = false;
13337 this.manualChunkAlias = null;
13338 this.reexports = Object.create(null);
13339 this.sources = [];
13340 this.userChunkNames = new Set();
13341 this.usesTopLevelAwait = false;
13342 this.namespaceVariable = undefined;
13343 this.transformDependencies = null;
13344 this.id = id;
13345 this.graph = graph;
13346 this.excludeFromSourcemap = /\0/.test(id);
13347 this.context = graph.getModuleContext(id);
13348 this.moduleSideEffects = moduleSideEffects;
13349 this.isEntryPoint = isEntry;
13350 }
13351 basename() {
13352 const base = path.basename(this.id);
13353 const ext = path.extname(this.id);
13354 return makeLegal(ext ? base.slice(0, -ext.length) : base);
13355 }
13356 bindReferences() {
13357 this.ast.bind();
13358 }
13359 error(props, pos) {
13360 if (pos !== undefined) {
13361 props.pos = pos;
13362 let location = locate(this.code, pos, { offsetLine: 1 });
13363 try {
13364 location = getOriginalLocation(this.sourcemapChain, location);
13365 }
13366 catch (e) {
13367 this.warn({
13368 code: 'SOURCEMAP_ERROR',
13369 loc: {
13370 column: location.column,
13371 file: this.id,
13372 line: location.line
13373 },
13374 message: `Error when using sourcemap for reporting an error: ${e.message}`,
13375 pos
13376 }, undefined);
13377 }
13378 props.loc = {
13379 column: location.column,
13380 file: this.id,
13381 line: location.line
13382 };
13383 props.frame = getCodeFrame(this.originalCode, location.line, location.column);
13384 }
13385 error(props);
13386 }
13387 getAllExportNames() {
13388 if (this.allExportNames) {
13389 return this.allExportNames;
13390 }
13391 const allExportNames = (this.allExportNames = new Set());
13392 for (const name of Object.keys(this.exports)) {
13393 allExportNames.add(name);
13394 }
13395 for (const name of Object.keys(this.reexports)) {
13396 allExportNames.add(name);
13397 }
13398 for (const module of this.exportAllModules) {
13399 if (module instanceof ExternalModule) {
13400 allExportNames.add(`*${module.id}`);
13401 continue;
13402 }
13403 for (const name of module.getAllExportNames()) {
13404 if (name !== 'default')
13405 allExportNames.add(name);
13406 }
13407 }
13408 return allExportNames;
13409 }
13410 getDynamicImportExpressions() {
13411 return this.dynamicImports.map(({ node }) => {
13412 const importArgument = node.parent.arguments[0];
13413 if (importArgument instanceof TemplateLiteral &&
13414 importArgument.quasis.length === 1 &&
13415 importArgument.quasis[0].value.cooked) {
13416 return importArgument.quasis[0].value.cooked;
13417 }
13418 if (importArgument instanceof Literal && typeof importArgument.value === 'string') {
13419 return importArgument.value;
13420 }
13421 return importArgument;
13422 });
13423 }
13424 getExportNamesByVariable() {
13425 const exportNamesByVariable = new Map();
13426 for (const exportName of this.getAllExportNames()) {
13427 const tracedVariable = this.getVariableForExportName(exportName);
13428 if (!tracedVariable ||
13429 !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
13430 continue;
13431 }
13432 const existingExportNames = exportNamesByVariable.get(tracedVariable);
13433 if (existingExportNames) {
13434 existingExportNames.push(exportName);
13435 }
13436 else {
13437 exportNamesByVariable.set(tracedVariable, [exportName]);
13438 }
13439 }
13440 return exportNamesByVariable;
13441 }
13442 getExports() {
13443 return Object.keys(this.exports);
13444 }
13445 getOrCreateNamespace() {
13446 return (this.namespaceVariable || (this.namespaceVariable = new NamespaceVariable(this.astContext)));
13447 }
13448 getReexports() {
13449 if (this.transitiveReexports) {
13450 return this.transitiveReexports;
13451 }
13452 // to avoid infinite recursion when using circular `export * from X`
13453 this.transitiveReexports = [];
13454 const reexports = new Set();
13455 for (const name in this.reexports) {
13456 reexports.add(name);
13457 }
13458 for (const module of this.exportAllModules) {
13459 if (module instanceof ExternalModule) {
13460 reexports.add(`*${module.id}`);
13461 }
13462 else {
13463 for (const name of module.getExports().concat(module.getReexports())) {
13464 if (name !== 'default')
13465 reexports.add(name);
13466 }
13467 }
13468 }
13469 return (this.transitiveReexports = Array.from(reexports));
13470 }
13471 getRenderedExports() {
13472 // only direct exports are counted here, not reexports at all
13473 const renderedExports = [];
13474 const removedExports = [];
13475 for (const exportName in this.exports) {
13476 const variable = this.getVariableForExportName(exportName);
13477 (variable && variable.included ? renderedExports : removedExports).push(exportName);
13478 }
13479 return { renderedExports, removedExports };
13480 }
13481 getTransitiveDependencies() {
13482 return this.dependencies.concat(this.getReexports().map(exportName => this.getVariableForExportName(exportName).module));
13483 }
13484 getVariableForExportName(name, isExportAllSearch) {
13485 if (name[0] === '*') {
13486 if (name.length === 1) {
13487 return this.getOrCreateNamespace();
13488 }
13489 else {
13490 // export * from 'external'
13491 const module = this.graph.moduleById.get(name.slice(1));
13492 return module.getVariableForExportName('*');
13493 }
13494 }
13495 // export { foo } from './other'
13496 const reexportDeclaration = this.reexports[name];
13497 if (reexportDeclaration) {
13498 const declaration = reexportDeclaration.module.getVariableForExportName(reexportDeclaration.localName);
13499 if (!declaration) {
13500 handleMissingExport(reexportDeclaration.localName, this, reexportDeclaration.module.id, reexportDeclaration.start);
13501 }
13502 return declaration;
13503 }
13504 const exportDeclaration = this.exports[name];
13505 if (exportDeclaration) {
13506 if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
13507 return this.exportShimVariable;
13508 }
13509 const name = exportDeclaration.localName;
13510 return this.traceVariable(name) || this.graph.scope.findVariable(name);
13511 }
13512 if (name !== 'default') {
13513 for (const module of this.exportAllModules) {
13514 const declaration = module.getVariableForExportName(name, true);
13515 if (declaration)
13516 return declaration;
13517 }
13518 }
13519 // we don't want to create shims when we are just
13520 // probing export * modules for exports
13521 if (this.graph.shimMissingExports && !isExportAllSearch) {
13522 this.shimMissingExport(name);
13523 return this.exportShimVariable;
13524 }
13525 return undefined;
13526 }
13527 include() {
13528 if (this.ast.shouldBeIncluded())
13529 this.ast.include(false);
13530 }
13531 includeAllExports() {
13532 if (!this.isExecuted) {
13533 this.graph.needsTreeshakingPass = true;
13534 markModuleAndImpureDependenciesAsExecuted(this);
13535 }
13536 for (const exportName of this.getExports()) {
13537 const variable = this.getVariableForExportName(exportName);
13538 variable.deoptimizePath(UNKNOWN_PATH);
13539 if (!variable.included) {
13540 variable.include();
13541 this.graph.needsTreeshakingPass = true;
13542 }
13543 }
13544 for (const name of this.getReexports()) {
13545 const variable = this.getVariableForExportName(name);
13546 variable.deoptimizePath(UNKNOWN_PATH);
13547 if (!variable.included) {
13548 variable.include();
13549 this.graph.needsTreeshakingPass = true;
13550 }
13551 if (variable instanceof ExternalVariable) {
13552 variable.module.reexported = true;
13553 }
13554 }
13555 }
13556 includeAllInBundle() {
13557 this.ast.include(true);
13558 }
13559 isIncluded() {
13560 return this.ast.included || (this.namespaceVariable && this.namespaceVariable.included);
13561 }
13562 linkDependencies() {
13563 for (const source of this.sources) {
13564 const id = this.resolvedIds[source].id;
13565 if (id) {
13566 const module = this.graph.moduleById.get(id);
13567 this.dependencies.push(module);
13568 }
13569 }
13570 for (const { resolution } of this.dynamicImports) {
13571 if (resolution instanceof Module || resolution instanceof ExternalModule) {
13572 this.dynamicDependencies.push(resolution);
13573 }
13574 }
13575 this.addModulesToSpecifiers(this.importDescriptions);
13576 this.addModulesToSpecifiers(this.reexports);
13577 this.exportAllModules = this.exportAllSources
13578 .map(source => {
13579 const id = this.resolvedIds[source].id;
13580 return this.graph.moduleById.get(id);
13581 })
13582 .sort((moduleA, moduleB) => {
13583 const aExternal = moduleA instanceof ExternalModule;
13584 const bExternal = moduleB instanceof ExternalModule;
13585 return aExternal === bExternal ? 0 : aExternal ? 1 : -1;
13586 });
13587 }
13588 render(options) {
13589 const magicString = this.magicString.clone();
13590 this.ast.render(magicString, options);
13591 this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
13592 return magicString;
13593 }
13594 setSource({ ast, code, customTransformCache, moduleSideEffects, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles }) {
13595 this.code = code;
13596 this.originalCode = originalCode;
13597 this.originalSourcemap = originalSourcemap;
13598 this.sourcemapChain = sourcemapChain;
13599 if (transformFiles) {
13600 this.transformFiles = transformFiles;
13601 }
13602 this.transformDependencies = transformDependencies;
13603 this.customTransformCache = customTransformCache;
13604 if (typeof moduleSideEffects === 'boolean') {
13605 this.moduleSideEffects = moduleSideEffects;
13606 }
13607 timeStart('generate ast', 3);
13608 this.esTreeAst = ast || tryParse(this, this.graph.acornParser, this.graph.acornOptions);
13609 markPureCallExpressions(this.comments, this.esTreeAst);
13610 timeEnd('generate ast', 3);
13611 this.resolvedIds = resolvedIds || Object.create(null);
13612 // By default, `id` is the file name. Custom resolvers and loaders
13613 // can change that, but it makes sense to use it for the source file name
13614 const fileName = this.id;
13615 this.magicString = new MagicString(code, {
13616 filename: (this.excludeFromSourcemap ? null : fileName),
13617 indentExclusionRanges: []
13618 });
13619 this.removeExistingSourceMap();
13620 timeStart('analyse ast', 3);
13621 this.astContext = {
13622 addDynamicImport: this.addDynamicImport.bind(this),
13623 addExport: this.addExport.bind(this),
13624 addImport: this.addImport.bind(this),
13625 addImportMeta: this.addImportMeta.bind(this),
13626 annotations: (this.graph.treeshakingOptions &&
13627 this.graph.treeshakingOptions.annotations),
13628 code,
13629 deoptimizationTracker: this.graph.deoptimizationTracker,
13630 error: this.error.bind(this),
13631 fileName,
13632 getExports: this.getExports.bind(this),
13633 getFileName: this.graph.pluginDriver.getFileName,
13634 getModuleExecIndex: () => this.execIndex,
13635 getModuleName: this.basename.bind(this),
13636 getReexports: this.getReexports.bind(this),
13637 importDescriptions: this.importDescriptions,
13638 includeDynamicImport: this.includeDynamicImport.bind(this),
13639 includeVariable: this.includeVariable.bind(this),
13640 isCrossChunkImport: importDescription => importDescription.module.chunk !== this.chunk,
13641 magicString: this.magicString,
13642 module: this,
13643 moduleContext: this.context,
13644 nodeConstructors,
13645 preserveModules: this.graph.preserveModules,
13646 propertyReadSideEffects: (!this.graph.treeshakingOptions ||
13647 this.graph.treeshakingOptions.propertyReadSideEffects),
13648 traceExport: this.getVariableForExportName.bind(this),
13649 traceVariable: this.traceVariable.bind(this),
13650 treeshake: !!this.graph.treeshakingOptions,
13651 tryCatchDeoptimization: (!this.graph.treeshakingOptions ||
13652 this.graph.treeshakingOptions.tryCatchDeoptimization),
13653 usesTopLevelAwait: false,
13654 warn: this.warn.bind(this),
13655 warnDeprecation: this.graph.warnDeprecation.bind(this.graph)
13656 };
13657 this.scope = new ModuleScope(this.graph.scope, this.astContext);
13658 this.ast = new Program$1(this.esTreeAst, { type: 'Module', context: this.astContext }, this.scope);
13659 timeEnd('analyse ast', 3);
13660 }
13661 toJSON() {
13662 return {
13663 ast: this.esTreeAst,
13664 code: this.code,
13665 customTransformCache: this.customTransformCache,
13666 dependencies: this.dependencies.map(module => module.id),
13667 id: this.id,
13668 moduleSideEffects: this.moduleSideEffects,
13669 originalCode: this.originalCode,
13670 originalSourcemap: this.originalSourcemap,
13671 resolvedIds: this.resolvedIds,
13672 sourcemapChain: this.sourcemapChain,
13673 transformDependencies: this.transformDependencies,
13674 transformFiles: this.transformFiles
13675 };
13676 }
13677 traceVariable(name) {
13678 const localVariable = this.scope.variables.get(name);
13679 if (localVariable) {
13680 return localVariable;
13681 }
13682 if (name in this.importDescriptions) {
13683 const importDeclaration = this.importDescriptions[name];
13684 const otherModule = importDeclaration.module;
13685 if (otherModule instanceof Module && importDeclaration.name === '*') {
13686 return otherModule.getOrCreateNamespace();
13687 }
13688 const declaration = otherModule.getVariableForExportName(importDeclaration.name);
13689 if (!declaration) {
13690 handleMissingExport(importDeclaration.name, this, otherModule.id, importDeclaration.start);
13691 }
13692 return declaration;
13693 }
13694 return null;
13695 }
13696 warn(warning, pos) {
13697 if (pos !== undefined) {
13698 warning.pos = pos;
13699 const { line, column } = locate(this.code, pos, { offsetLine: 1 }); // TODO trace sourcemaps, cf. error()
13700 warning.loc = { file: this.id, line, column };
13701 warning.frame = getCodeFrame(this.code, line, column);
13702 }
13703 warning.id = this.id;
13704 this.graph.warn(warning);
13705 }
13706 addDynamicImport(node) {
13707 this.dynamicImports.push({ node, resolution: null });
13708 }
13709 addExport(node) {
13710 const source = node.source && node.source.value;
13711 // export { name } from './other'
13712 if (source) {
13713 if (this.sources.indexOf(source) === -1)
13714 this.sources.push(source);
13715 if (node.type === ExportAllDeclaration) {
13716 // Store `export * from '...'` statements in an array of delegates.
13717 // When an unknown import is encountered, we see if one of them can satisfy it.
13718 this.exportAllSources.push(source);
13719 }
13720 else {
13721 for (const specifier of node.specifiers) {
13722 const name = specifier.exported.name;
13723 if (this.exports[name] || this.reexports[name]) {
13724 this.error({
13725 code: 'DUPLICATE_EXPORT',
13726 message: `A module cannot have multiple exports with the same name ('${name}')`
13727 }, specifier.start);
13728 }
13729 this.reexports[name] = {
13730 localName: specifier.local.name,
13731 module: null,
13732 source,
13733 start: specifier.start
13734 };
13735 }
13736 }
13737 }
13738 else if (node instanceof ExportDefaultDeclaration) {
13739 // export default function foo () {}
13740 // export default foo;
13741 // export default 42;
13742 if (this.exports.default) {
13743 this.error({
13744 code: 'DUPLICATE_EXPORT',
13745 message: `A module can only have one default export`
13746 }, node.start);
13747 }
13748 this.exports.default = {
13749 identifier: node.variable.getAssignedVariableName(),
13750 localName: 'default'
13751 };
13752 }
13753 else if (node.declaration) {
13754 // export var { foo, bar } = ...
13755 // export var foo = 42;
13756 // export var a = 1, b = 2, c = 3;
13757 // export function foo () {}
13758 const declaration = node.declaration;
13759 if (declaration.type === VariableDeclaration) {
13760 for (const decl of declaration.declarations) {
13761 for (const localName of extractAssignedNames(decl.id)) {
13762 this.exports[localName] = { identifier: null, localName };
13763 }
13764 }
13765 }
13766 else {
13767 // export function foo () {}
13768 const localName = declaration.id.name;
13769 this.exports[localName] = { identifier: null, localName };
13770 }
13771 }
13772 else {
13773 // export { foo, bar, baz }
13774 for (const specifier of node.specifiers) {
13775 const localName = specifier.local.name;
13776 const exportedName = specifier.exported.name;
13777 if (this.exports[exportedName] || this.reexports[exportedName]) {
13778 this.error({
13779 code: 'DUPLICATE_EXPORT',
13780 message: `A module cannot have multiple exports with the same name ('${exportedName}')`
13781 }, specifier.start);
13782 }
13783 this.exports[exportedName] = { identifier: null, localName };
13784 }
13785 }
13786 }
13787 addImport(node) {
13788 const source = node.source.value;
13789 if (this.sources.indexOf(source) === -1)
13790 this.sources.push(source);
13791 for (const specifier of node.specifiers) {
13792 const localName = specifier.local.name;
13793 if (this.importDescriptions[localName]) {
13794 this.error({
13795 code: 'DUPLICATE_IMPORT',
13796 message: `Duplicated import '${localName}'`
13797 }, specifier.start);
13798 }
13799 const isDefault = specifier.type === ImportDefaultSpecifier;
13800 const isNamespace = specifier.type === ImportNamespaceSpecifier;
13801 const name = isDefault
13802 ? 'default'
13803 : isNamespace
13804 ? '*'
13805 : specifier.imported.name;
13806 this.importDescriptions[localName] = { source, start: specifier.start, name, module: null };
13807 }
13808 }
13809 addImportMeta(node) {
13810 this.importMetas.push(node);
13811 }
13812 addModulesToSpecifiers(specifiers) {
13813 for (const name of Object.keys(specifiers)) {
13814 const specifier = specifiers[name];
13815 const id = this.resolvedIds[specifier.source].id;
13816 specifier.module = this.graph.moduleById.get(id);
13817 }
13818 }
13819 includeDynamicImport(node) {
13820 const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
13821 if (resolution instanceof Module) {
13822 resolution.dynamicallyImportedBy.push(this);
13823 resolution.includeAllExports();
13824 }
13825 }
13826 includeVariable(variable) {
13827 const variableModule = variable.module;
13828 if (!variable.included) {
13829 variable.include();
13830 this.graph.needsTreeshakingPass = true;
13831 }
13832 if (variableModule && variableModule !== this) {
13833 this.imports.add(variable);
13834 }
13835 }
13836 removeExistingSourceMap() {
13837 for (const comment of this.comments) {
13838 if (!comment.block && SOURCEMAPPING_URL_RE.test(comment.text)) {
13839 this.magicString.remove(comment.start, comment.end);
13840 }
13841 }
13842 }
13843 shimMissingExport(name) {
13844 if (!this.exports[name]) {
13845 this.graph.warn({
13846 code: 'SHIMMED_EXPORT',
13847 exporter: index.relativeId(this.id),
13848 exportName: name,
13849 message: `Missing export "${name}" has been shimmed in module ${index.relativeId(this.id)}.`
13850 });
13851 this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
13852 }
13853 }
13854}
13855
13856class Source {
13857 constructor(filename, content) {
13858 this.isOriginal = true;
13859 this.filename = filename;
13860 this.content = content;
13861 }
13862 traceSegment(line, column, name) {
13863 return { line, column, name, source: this };
13864 }
13865}
13866class Link {
13867 constructor(map, sources) {
13868 this.sources = sources;
13869 this.names = map.names;
13870 this.mappings = map.mappings;
13871 }
13872 traceMappings() {
13873 const sources = [];
13874 const sourcesContent = [];
13875 const names = [];
13876 const mappings = [];
13877 for (const line of this.mappings) {
13878 const tracedLine = [];
13879 for (const segment of line) {
13880 if (segment.length == 1)
13881 continue;
13882 const source = this.sources[segment[1]];
13883 if (!source)
13884 continue;
13885 const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
13886 if (traced) {
13887 // newer sources are more likely to be used, so search backwards.
13888 let sourceIndex = sources.lastIndexOf(traced.source.filename);
13889 if (sourceIndex === -1) {
13890 sourceIndex = sources.length;
13891 sources.push(traced.source.filename);
13892 sourcesContent[sourceIndex] = traced.source.content;
13893 }
13894 else if (sourcesContent[sourceIndex] == null) {
13895 sourcesContent[sourceIndex] = traced.source.content;
13896 }
13897 else if (traced.source.content != null &&
13898 sourcesContent[sourceIndex] !== traced.source.content) {
13899 error({
13900 message: `Multiple conflicting contents for sourcemap source ${traced.source.filename}`
13901 });
13902 }
13903 const tracedSegment = [
13904 segment[0],
13905 sourceIndex,
13906 traced.line,
13907 traced.column
13908 ];
13909 if (traced.name) {
13910 let nameIndex = names.indexOf(traced.name);
13911 if (nameIndex === -1) {
13912 nameIndex = names.length;
13913 names.push(traced.name);
13914 }
13915 tracedSegment[4] = nameIndex;
13916 }
13917 tracedLine.push(tracedSegment);
13918 }
13919 }
13920 mappings.push(tracedLine);
13921 }
13922 return { sources, sourcesContent, names, mappings };
13923 }
13924 traceSegment(line, column, name) {
13925 const segments = this.mappings[line];
13926 if (!segments)
13927 return null;
13928 // binary search through segments for the given column
13929 let i = 0;
13930 let j = segments.length - 1;
13931 while (i <= j) {
13932 const m = (i + j) >> 1;
13933 const segment = segments[m];
13934 if (segment[0] === column) {
13935 if (segment.length == 1)
13936 return null;
13937 const source = this.sources[segment[1]];
13938 if (!source)
13939 return null;
13940 return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
13941 }
13942 if (segment[0] > column) {
13943 j = m - 1;
13944 }
13945 else {
13946 i = m + 1;
13947 }
13948 }
13949 return null;
13950 }
13951}
13952function getLinkMap(graph) {
13953 return function linkMap(source, map) {
13954 if (map.mappings) {
13955 return new Link(map, [source]);
13956 }
13957 graph.warn({
13958 code: 'SOURCEMAP_BROKEN',
13959 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`,
13960 plugin: map.plugin,
13961 url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
13962 });
13963 return new Link({
13964 mappings: [],
13965 names: []
13966 }, [source]);
13967 };
13968}
13969function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
13970 let source;
13971 if (!originalSourcemap) {
13972 source = new Source(id, originalCode);
13973 }
13974 else {
13975 const sources = originalSourcemap.sources;
13976 const sourcesContent = originalSourcemap.sourcesContent || [];
13977 // TODO indiscriminately treating IDs and sources as normal paths is probably bad.
13978 const directory = path.dirname(id) || '.';
13979 const sourceRoot = originalSourcemap.sourceRoot || '.';
13980 const baseSources = sources.map((source, i) => new Source(path.resolve(directory, sourceRoot, source), sourcesContent[i]));
13981 source = new Link(originalSourcemap, baseSources);
13982 }
13983 return sourcemapChain.reduce(linkMap, source);
13984}
13985function collapseSourcemaps(bundle, file, map, modules, bundleSourcemapChain, excludeContent) {
13986 const linkMap = getLinkMap(bundle.graph);
13987 const moduleSources = modules
13988 .filter(module => !module.excludeFromSourcemap)
13989 .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
13990 // DecodedSourceMap (from magic-string) uses a number[] instead of the more
13991 // correct SourceMapSegment tuples. Cast it here to gain type safety.
13992 let source = new Link(map, moduleSources);
13993 source = bundleSourcemapChain.reduce(linkMap, source);
13994 let { sources, sourcesContent, names, mappings } = source.traceMappings();
13995 if (file) {
13996 const directory = path.dirname(file);
13997 sources = sources.map((source) => path.relative(directory, source));
13998 file = path.basename(file);
13999 }
14000 sourcesContent = (excludeContent ? null : sourcesContent);
14001 return new SourceMap({ file, sources, sourcesContent, names, mappings });
14002}
14003function collapseSourcemap(graph, id, originalCode, originalSourcemap, sourcemapChain) {
14004 if (!sourcemapChain.length) {
14005 return originalSourcemap;
14006 }
14007 const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(graph));
14008 const map = source.traceMappings();
14009 return Object.assign({ version: 3 }, map);
14010}
14011
14012const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
14013 amd: deconflictImportsOther,
14014 cjs: deconflictImportsOther,
14015 es: deconflictImportsEsm,
14016 iife: deconflictImportsOther,
14017 system: deconflictImportsEsm,
14018 umd: deconflictImportsOther
14019};
14020function deconflictChunk(modules, dependencies, imports, usedNames, format, interop, preserveModules) {
14021 addUsedGlobalNames(usedNames, modules, format);
14022 deconflictTopLevelVariables(usedNames, modules);
14023 DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependencies, interop, preserveModules);
14024 for (const module of modules) {
14025 module.scope.deconflict(format);
14026 }
14027}
14028function addUsedGlobalNames(usedNames, modules, format) {
14029 for (const module of modules) {
14030 const moduleScope = module.scope;
14031 for (const [name, variable] of moduleScope.accessedOutsideVariables) {
14032 if (variable.included) {
14033 usedNames.add(name);
14034 }
14035 }
14036 const accessedGlobalVariables = moduleScope.accessedGlobalVariablesByFormat &&
14037 moduleScope.accessedGlobalVariablesByFormat.get(format);
14038 if (accessedGlobalVariables) {
14039 for (const name of accessedGlobalVariables) {
14040 usedNames.add(name);
14041 }
14042 }
14043 }
14044}
14045function deconflictImportsEsm(usedNames, imports, _dependencies, interop) {
14046 for (const variable of imports) {
14047 const module = variable.module;
14048 const name = variable.name;
14049 let proposedName;
14050 if (module instanceof ExternalModule && (name === '*' || name === 'default')) {
14051 if (name === 'default' && interop && module.exportsNamespace) {
14052 proposedName = module.variableName + '__default';
14053 }
14054 else {
14055 proposedName = module.variableName;
14056 }
14057 }
14058 else {
14059 proposedName = name;
14060 }
14061 variable.setRenderNames(null, getSafeName(proposedName, usedNames));
14062 }
14063}
14064function deconflictImportsOther(usedNames, imports, dependencies, interop, preserveModules) {
14065 for (const chunkOrExternalModule of dependencies) {
14066 chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.variableName, usedNames);
14067 }
14068 for (const variable of imports) {
14069 const module = variable.module;
14070 if (module instanceof ExternalModule) {
14071 const name = variable.name;
14072 if (name === 'default' && interop && (module.exportsNamespace || module.exportsNames)) {
14073 variable.setRenderNames(null, module.variableName + '__default');
14074 }
14075 else if (name === '*' || name === 'default') {
14076 variable.setRenderNames(null, module.variableName);
14077 }
14078 else {
14079 variable.setRenderNames(module.variableName, null);
14080 }
14081 }
14082 else {
14083 const chunk = module.chunk;
14084 if (chunk.exportMode === 'default' || (preserveModules && variable.isNamespace)) {
14085 variable.setRenderNames(null, chunk.variableName);
14086 }
14087 else {
14088 variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
14089 }
14090 }
14091 }
14092}
14093function deconflictTopLevelVariables(usedNames, modules) {
14094 for (const module of modules) {
14095 for (const variable of module.scope.variables.values()) {
14096 if (variable.included &&
14097 // this will only happen for exports in some formats
14098 !(variable.renderBaseName ||
14099 (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
14100 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
14101 }
14102 }
14103 const namespace = module.getOrCreateNamespace();
14104 if (namespace.included) {
14105 namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
14106 }
14107 }
14108}
14109
14110const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
14111function sortByExecutionOrder(units) {
14112 units.sort(compareExecIndex);
14113}
14114function analyseModuleExecution(entryModules) {
14115 let nextExecIndex = 0;
14116 const cyclePaths = [];
14117 const analysedModules = {};
14118 const orderedModules = [];
14119 const dynamicImports = [];
14120 const parents = {};
14121 const analyseModule = (module) => {
14122 if (analysedModules[module.id])
14123 return;
14124 if (module instanceof ExternalModule) {
14125 module.execIndex = nextExecIndex++;
14126 analysedModules[module.id] = true;
14127 return;
14128 }
14129 for (const dependency of module.dependencies) {
14130 if (dependency.id in parents) {
14131 if (!analysedModules[dependency.id]) {
14132 cyclePaths.push(getCyclePath(dependency.id, module.id, parents));
14133 }
14134 continue;
14135 }
14136 parents[dependency.id] = module.id;
14137 analyseModule(dependency);
14138 }
14139 for (const { resolution } of module.dynamicImports) {
14140 if (resolution instanceof Module && dynamicImports.indexOf(resolution) === -1) {
14141 dynamicImports.push(resolution);
14142 }
14143 }
14144 module.execIndex = nextExecIndex++;
14145 analysedModules[module.id] = true;
14146 orderedModules.push(module);
14147 };
14148 for (const curEntry of entryModules) {
14149 if (!parents[curEntry.id]) {
14150 parents[curEntry.id] = null;
14151 analyseModule(curEntry);
14152 }
14153 }
14154 for (const curEntry of dynamicImports) {
14155 if (!parents[curEntry.id]) {
14156 parents[curEntry.id] = null;
14157 analyseModule(curEntry);
14158 }
14159 }
14160 return { orderedModules, cyclePaths };
14161}
14162function getCyclePath(id, parentId, parents) {
14163 const path = [index.relativeId(id)];
14164 let curId = parentId;
14165 while (curId !== id) {
14166 path.push(index.relativeId(curId));
14167 curId = parents[curId];
14168 if (!curId)
14169 break;
14170 }
14171 path.push(path[0]);
14172 path.reverse();
14173 return path;
14174}
14175
14176function guessIndentString(code) {
14177 const lines = code.split('\n');
14178 const tabbed = lines.filter(line => /^\t+/.test(line));
14179 const spaced = lines.filter(line => /^ {2,}/.test(line));
14180 if (tabbed.length === 0 && spaced.length === 0) {
14181 return null;
14182 }
14183 // More lines tabbed than spaced? Assume tabs, and
14184 // default to tabs in the case of a tie (or nothing
14185 // to go on)
14186 if (tabbed.length >= spaced.length) {
14187 return '\t';
14188 }
14189 // Otherwise, we need to guess the multiple
14190 const min = spaced.reduce((previous, current) => {
14191 const numSpaces = /^ +/.exec(current)[0].length;
14192 return Math.min(numSpaces, previous);
14193 }, Infinity);
14194 return new Array(min + 1).join(' ');
14195}
14196function getIndentString(modules, options) {
14197 if (options.indent !== true)
14198 return options.indent || '';
14199 for (let i = 0; i < modules.length; i++) {
14200 const indent = guessIndentString(modules[i].originalCode);
14201 if (indent !== null)
14202 return indent;
14203 }
14204 return '\t';
14205}
14206
14207function decodedSourcemap(map) {
14208 if (!map)
14209 return null;
14210 if (typeof map === 'string') {
14211 map = JSON.parse(map);
14212 }
14213 if (map.mappings === '') {
14214 return {
14215 mappings: [],
14216 names: [],
14217 sources: [],
14218 version: 3
14219 };
14220 }
14221 let mappings;
14222 if (typeof map.mappings === 'string') {
14223 mappings = decode(map.mappings);
14224 }
14225 else {
14226 mappings = map.mappings;
14227 }
14228 return Object.assign({}, map, { mappings });
14229}
14230
14231function renderChunk({ graph, chunk, renderChunk, code, sourcemapChain, options }) {
14232 const renderChunkReducer = (code, result, plugin) => {
14233 if (result == null)
14234 return code;
14235 if (typeof result === 'string')
14236 result = {
14237 code: result,
14238 map: undefined
14239 };
14240 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
14241 if (result.map !== null) {
14242 const map = decodedSourcemap(result.map);
14243 sourcemapChain.push(map || { missing: true, plugin: plugin.name });
14244 }
14245 return result.code;
14246 };
14247 let inTransformBundle = false;
14248 let inRenderChunk = true;
14249 return graph.pluginDriver
14250 .hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer)
14251 .then(code => {
14252 inRenderChunk = false;
14253 return graph.pluginDriver.hookReduceArg0('transformChunk', [code, options, chunk], renderChunkReducer);
14254 })
14255 .then(code => {
14256 inTransformBundle = true;
14257 return graph.pluginDriver.hookReduceArg0('transformBundle', [code, options, chunk], renderChunkReducer);
14258 })
14259 .catch(err => {
14260 if (inRenderChunk)
14261 throw err;
14262 return error(err, {
14263 code: inTransformBundle ? 'BAD_BUNDLE_TRANSFORMER' : 'BAD_CHUNK_TRANSFORMER',
14264 message: `Error transforming ${(inTransformBundle ? 'bundle' : 'chunk') +
14265 (err.plugin ? ` with '${err.plugin}' plugin` : '')}: ${err.message}`,
14266 plugin: err.plugin
14267 });
14268 });
14269}
14270
14271function renderNamePattern(pattern, patternName, replacements) {
14272 if (!index.isPlainPathFragment(pattern))
14273 return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths and must not contain invalid characters.`));
14274 return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
14275 if (!replacements.hasOwnProperty(type)) {
14276 return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
14277 }
14278 const replacement = replacements[type]();
14279 if (!index.isPlainPathFragment(replacement))
14280 return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
14281 return replacement;
14282 });
14283}
14284function makeUnique(name, existingNames) {
14285 if (name in existingNames === false)
14286 return name;
14287 const ext = path.extname(name);
14288 name = name.substr(0, name.length - ext.length);
14289 let uniqueName, uniqueIndex = 1;
14290 while (existingNames[(uniqueName = name + ++uniqueIndex + ext)])
14291 ;
14292 return uniqueName;
14293}
14294
14295function getGlobalName(module, globals, graph, hasExports) {
14296 let globalName;
14297 if (typeof globals === 'function') {
14298 globalName = globals(module.id);
14299 }
14300 else if (globals) {
14301 globalName = globals[module.id];
14302 }
14303 if (globalName) {
14304 return globalName;
14305 }
14306 if (hasExports) {
14307 graph.warn({
14308 code: 'MISSING_GLOBAL_NAME',
14309 guess: module.variableName,
14310 message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
14311 source: module.id
14312 });
14313 return module.variableName;
14314 }
14315}
14316function isChunkRendered(chunk) {
14317 return !chunk.isEmpty || chunk.entryModules.length > 0 || chunk.manualChunkAlias !== null;
14318}
14319class Chunk$1 {
14320 constructor(graph, orderedModules) {
14321 this.entryModules = [];
14322 this.exportMode = 'named';
14323 this.facadeModule = null;
14324 this.id = null;
14325 this.indentString = undefined;
14326 this.manualChunkAlias = null;
14327 this.usedModules = undefined;
14328 this.variableName = 'chunk';
14329 this.dependencies = undefined;
14330 this.dynamicDependencies = undefined;
14331 this.exportNames = Object.create(null);
14332 this.exports = new Set();
14333 this.fileName = null;
14334 this.imports = new Set();
14335 this.name = null;
14336 this.needsExportsShim = false;
14337 this.renderedDeclarations = undefined;
14338 this.renderedHash = undefined;
14339 this.renderedModuleSources = new Map();
14340 this.renderedSource = null;
14341 this.renderedSourceLength = undefined;
14342 this.sortedExportNames = null;
14343 this.graph = graph;
14344 this.orderedModules = orderedModules;
14345 this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
14346 this.isEmpty = true;
14347 for (const module of orderedModules) {
14348 if (this.isEmpty && module.isIncluded()) {
14349 this.isEmpty = false;
14350 }
14351 if (module.manualChunkAlias) {
14352 this.manualChunkAlias = module.manualChunkAlias;
14353 }
14354 module.chunk = this;
14355 if (module.isEntryPoint ||
14356 module.dynamicallyImportedBy.some(module => orderedModules.indexOf(module) === -1)) {
14357 this.entryModules.push(module);
14358 }
14359 }
14360 const moduleForNaming = this.entryModules[0] || this.orderedModules[this.orderedModules.length - 1];
14361 if (moduleForNaming) {
14362 this.variableName = makeLegal(path.basename(moduleForNaming.chunkName ||
14363 moduleForNaming.manualChunkAlias ||
14364 index.getAliasName(moduleForNaming.id)));
14365 }
14366 }
14367 static generateFacade(graph, facadedModule, facadeName) {
14368 const chunk = new Chunk$1(graph, []);
14369 chunk.assignFacadeName(facadeName, facadedModule);
14370 if (!facadedModule.facadeChunk) {
14371 facadedModule.facadeChunk = chunk;
14372 }
14373 chunk.dependencies = [facadedModule.chunk];
14374 chunk.dynamicDependencies = [];
14375 chunk.facadeModule = facadedModule;
14376 for (const exportName of facadedModule.getAllExportNames()) {
14377 const tracedVariable = facadedModule.getVariableForExportName(exportName);
14378 chunk.exports.add(tracedVariable);
14379 chunk.exportNames[exportName] = tracedVariable;
14380 }
14381 return chunk;
14382 }
14383 canModuleBeFacade(moduleExportNamesByVariable) {
14384 for (const exposedVariable of this.exports) {
14385 if (!moduleExportNamesByVariable.has(exposedVariable)) {
14386 return false;
14387 }
14388 }
14389 return true;
14390 }
14391 generateFacades() {
14392 const facades = [];
14393 for (const module of this.entryModules) {
14394 const requiredFacades = Array.from(module.userChunkNames).map(name => ({
14395 name
14396 }));
14397 if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
14398 requiredFacades.push({});
14399 }
14400 requiredFacades.push(...Array.from(module.chunkFileNames).map(fileName => ({ fileName })));
14401 if (requiredFacades.length === 0) {
14402 requiredFacades.push({});
14403 }
14404 if (!this.facadeModule) {
14405 const exportNamesByVariable = module.getExportNamesByVariable();
14406 if (this.graph.preserveModules || this.canModuleBeFacade(exportNamesByVariable)) {
14407 this.facadeModule = module;
14408 module.facadeChunk = this;
14409 for (const [variable, exportNames] of exportNamesByVariable) {
14410 for (const exportName of exportNames) {
14411 this.exportNames[exportName] = variable;
14412 }
14413 }
14414 this.assignFacadeName(requiredFacades.shift(), module);
14415 }
14416 }
14417 for (const facadeName of requiredFacades) {
14418 facades.push(Chunk$1.generateFacade(this.graph, module, facadeName));
14419 }
14420 }
14421 return facades;
14422 }
14423 generateId(pattern, patternName, addons, options, existingNames) {
14424 if (this.fileName !== null) {
14425 return this.fileName;
14426 }
14427 return makeUnique(renderNamePattern(pattern, patternName, {
14428 format: () => (options.format === 'es' ? 'esm' : options.format),
14429 hash: () => this.computeContentHashWithDependencies(addons, options),
14430 name: () => this.getChunkName()
14431 }), existingNames);
14432 }
14433 generateIdPreserveModules(preserveModulesRelativeDir, existingNames) {
14434 const sanitizedId = index.sanitizeFileName(this.orderedModules[0].id);
14435 return makeUnique(index.normalize(index.isAbsolute(this.orderedModules[0].id)
14436 ? relative(preserveModulesRelativeDir, sanitizedId)
14437 : '_virtual/' + path.basename(sanitizedId)), existingNames);
14438 }
14439 generateInternalExports(options) {
14440 if (this.facadeModule !== null)
14441 return;
14442 const mangle = options.format === 'system' || options.format === 'es' || options.compact;
14443 let i = 0, safeExportName;
14444 this.exportNames = Object.create(null);
14445 this.sortedExportNames = null;
14446 if (mangle) {
14447 for (const variable of this.exports) {
14448 const suggestedName = variable.name[0];
14449 if (!this.exportNames[suggestedName]) {
14450 this.exportNames[suggestedName] = variable;
14451 }
14452 else {
14453 do {
14454 safeExportName = toBase64(++i);
14455 // skip past leading number identifiers
14456 if (safeExportName.charCodeAt(0) === 49 /* '1' */) {
14457 i += 9 * Math.pow(64, (safeExportName.length - 1));
14458 safeExportName = toBase64(i);
14459 }
14460 } while (RESERVED_NAMES[safeExportName] || this.exportNames[safeExportName]);
14461 this.exportNames[safeExportName] = variable;
14462 }
14463 }
14464 }
14465 else {
14466 for (const variable of this.exports) {
14467 i = 0;
14468 safeExportName = variable.name;
14469 while (this.exportNames[safeExportName]) {
14470 safeExportName = variable.name + '$' + ++i;
14471 }
14472 this.exportNames[safeExportName] = variable;
14473 }
14474 }
14475 }
14476 getChunkName() {
14477 return this.name || (this.name = index.sanitizeFileName(this.getFallbackChunkName()));
14478 }
14479 getDynamicImportIds() {
14480 return this.dynamicDependencies.map(chunk => chunk.id).filter(Boolean);
14481 }
14482 getExportNames() {
14483 return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportNames).sort()));
14484 }
14485 getImportIds() {
14486 return this.dependencies.map(chunk => chunk.id).filter(Boolean);
14487 }
14488 getRenderedHash() {
14489 if (this.renderedHash)
14490 return this.renderedHash;
14491 if (!this.renderedSource)
14492 return '';
14493 const hash = _256();
14494 hash.update(this.renderedSource.toString());
14495 hash.update(this.getExportNames()
14496 .map(exportName => {
14497 const variable = this.exportNames[exportName];
14498 return `${index.relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
14499 })
14500 .join(','));
14501 return (this.renderedHash = hash.digest('hex'));
14502 }
14503 getRenderedSourceLength() {
14504 if (this.renderedSourceLength !== undefined)
14505 return this.renderedSourceLength;
14506 return (this.renderedSourceLength = this.renderedSource.length());
14507 }
14508 getVariableExportName(variable) {
14509 if (this.graph.preserveModules && variable instanceof NamespaceVariable) {
14510 return '*';
14511 }
14512 for (const exportName of Object.keys(this.exportNames)) {
14513 if (this.exportNames[exportName] === variable)
14514 return exportName;
14515 }
14516 throw new Error(`Internal Error: Could not find export name for variable ${variable.name}.`);
14517 }
14518 link() {
14519 const dependencies = new Set();
14520 const dynamicDependencies = new Set();
14521 for (const module of this.orderedModules) {
14522 this.addDependenciesToChunk(module.getTransitiveDependencies(), dependencies);
14523 this.addDependenciesToChunk(module.dynamicDependencies, dynamicDependencies);
14524 this.setUpChunkImportsAndExportsForModule(module);
14525 }
14526 this.dependencies = Array.from(dependencies);
14527 this.dynamicDependencies = Array.from(dynamicDependencies);
14528 }
14529 /*
14530 * Performs a full merge of another chunk into this chunk
14531 * chunkList allows updating references in other chunks for the merged chunk to this chunk
14532 * A new facade will be added to chunkList if tainting exports of either as an entry point
14533 */
14534 merge(chunk, chunkList, options, inputBase) {
14535 if (this.facadeModule !== null || chunk.facadeModule !== null)
14536 throw new Error('Internal error: Code splitting chunk merges not supported for facades');
14537 for (const module of chunk.orderedModules) {
14538 module.chunk = this;
14539 this.orderedModules.push(module);
14540 }
14541 for (const variable of chunk.imports) {
14542 if (!this.imports.has(variable) && variable.module.chunk !== this) {
14543 this.imports.add(variable);
14544 }
14545 }
14546 // NB detect when exported variables are orphaned by the merge itself
14547 // (involves reverse tracing dependents)
14548 for (const variable of chunk.exports) {
14549 if (!this.exports.has(variable)) {
14550 this.exports.add(variable);
14551 }
14552 }
14553 const thisOldExportNames = this.exportNames;
14554 // regenerate internal names
14555 this.generateInternalExports(options);
14556 const updateRenderedDeclaration = (dep, oldExportNames) => {
14557 if (dep.imports) {
14558 for (const impt of dep.imports) {
14559 impt.imported = this.getVariableExportName(oldExportNames[impt.imported]);
14560 }
14561 }
14562 if (dep.reexports) {
14563 for (const reexport of dep.reexports) {
14564 reexport.imported = this.getVariableExportName(oldExportNames[reexport.imported]);
14565 }
14566 }
14567 };
14568 const mergeRenderedDeclaration = (into, from) => {
14569 if (from.imports) {
14570 if (!into.imports) {
14571 into.imports = from.imports;
14572 }
14573 else {
14574 into.imports = into.imports.concat(from.imports);
14575 }
14576 }
14577 if (from.reexports) {
14578 if (!into.reexports) {
14579 into.reexports = from.reexports;
14580 }
14581 else {
14582 into.reexports = into.reexports.concat(from.reexports);
14583 }
14584 }
14585 if (!into.exportsNames && from.exportsNames) {
14586 into.exportsNames = true;
14587 }
14588 if (!into.exportsDefault && from.exportsDefault) {
14589 into.exportsDefault = true;
14590 }
14591 into.name = this.variableName;
14592 };
14593 // go through the other chunks and update their dependencies
14594 // also update their import and reexport names in the process
14595 for (const c of chunkList) {
14596 let includedDeclaration = undefined;
14597 for (let i = 0; i < c.dependencies.length; i++) {
14598 const dep = c.dependencies[i];
14599 if ((dep === chunk || dep === this) && includedDeclaration) {
14600 const duplicateDeclaration = c.renderedDeclarations.dependencies[i];
14601 updateRenderedDeclaration(duplicateDeclaration, dep === chunk ? chunk.exportNames : thisOldExportNames);
14602 mergeRenderedDeclaration(includedDeclaration, duplicateDeclaration);
14603 c.renderedDeclarations.dependencies.splice(i, 1);
14604 c.dependencies.splice(i--, 1);
14605 }
14606 else if (dep === chunk) {
14607 c.dependencies[i] = this;
14608 includedDeclaration = c.renderedDeclarations.dependencies[i];
14609 updateRenderedDeclaration(includedDeclaration, chunk.exportNames);
14610 }
14611 else if (dep === this) {
14612 includedDeclaration = c.renderedDeclarations.dependencies[i];
14613 updateRenderedDeclaration(includedDeclaration, thisOldExportNames);
14614 }
14615 }
14616 }
14617 // re-render the merged chunk
14618 this.preRender(options, inputBase);
14619 }
14620 // prerender allows chunk hashes and names to be generated before finalizing
14621 preRender(options, inputBase) {
14622 timeStart('render modules', 3);
14623 const magicString = new Bundle({ separator: options.compact ? '' : '\n\n' });
14624 this.usedModules = [];
14625 this.indentString = options.compact ? '' : getIndentString(this.orderedModules, options);
14626 const n = options.compact ? '' : '\n';
14627 const _ = options.compact ? '' : ' ';
14628 const renderOptions = {
14629 compact: options.compact,
14630 dynamicImportFunction: options.dynamicImportFunction,
14631 format: options.format,
14632 freeze: options.freeze !== false,
14633 indent: this.indentString,
14634 namespaceToStringTag: options.namespaceToStringTag === true,
14635 varOrConst: options.preferConst ? 'const' : 'var'
14636 };
14637 // Make sure the direct dependencies of a chunk are present to maintain execution order
14638 for (const { module } of this.imports) {
14639 const chunkOrExternal = (module instanceof Module ? module.chunk : module);
14640 if (this.dependencies.indexOf(chunkOrExternal) === -1) {
14641 this.dependencies.push(chunkOrExternal);
14642 }
14643 }
14644 // for static and dynamic entry points, inline the execution list to avoid loading latency
14645 if (!this.graph.preserveModules && this.facadeModule !== null) {
14646 for (const dep of this.dependencies) {
14647 if (dep instanceof Chunk$1)
14648 this.inlineChunkDependencies(dep, true);
14649 }
14650 }
14651 // prune empty dependency chunks, inlining their side-effect dependencies
14652 for (let i = 0; i < this.dependencies.length; i++) {
14653 const dep = this.dependencies[i];
14654 if (dep instanceof Chunk$1 && dep.isEmpty) {
14655 this.dependencies.splice(i--, 1);
14656 this.inlineChunkDependencies(dep, false);
14657 }
14658 }
14659 sortByExecutionOrder(this.dependencies);
14660 this.prepareDynamicImports();
14661 this.setIdentifierRenderResolutions(options);
14662 let hoistedSource = '';
14663 const renderedModules = (this.renderedModules = Object.create(null));
14664 for (const module of this.orderedModules) {
14665 let renderedLength = 0;
14666 if (module.isIncluded()) {
14667 const source = module.render(renderOptions).trim();
14668 if (options.compact && source.lastLine().indexOf('//') !== -1)
14669 source.append('\n');
14670 const namespace = module.getOrCreateNamespace();
14671 if (namespace.included || source.length() > 0) {
14672 renderedLength = source.length();
14673 this.renderedModuleSources.set(module, source);
14674 magicString.addSource(source);
14675 this.usedModules.push(module);
14676 if (namespace.included && !this.graph.preserveModules) {
14677 const rendered = namespace.renderBlock(renderOptions);
14678 if (namespace.renderFirst())
14679 hoistedSource += n + rendered;
14680 else
14681 magicString.addSource(new MagicString(rendered));
14682 }
14683 }
14684 }
14685 const { renderedExports, removedExports } = module.getRenderedExports();
14686 renderedModules[module.id] = {
14687 originalLength: module.originalCode.length,
14688 removedExports,
14689 renderedExports,
14690 renderedLength
14691 };
14692 }
14693 if (hoistedSource)
14694 magicString.prepend(hoistedSource + n + n);
14695 if (this.needsExportsShim) {
14696 magicString.prepend(`${n}${renderOptions.varOrConst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
14697 }
14698 if (options.compact) {
14699 this.renderedSource = magicString;
14700 }
14701 else {
14702 this.renderedSource = magicString.trim();
14703 }
14704 this.renderedSourceLength = undefined;
14705 this.renderedHash = undefined;
14706 if (this.getExportNames().length === 0 && this.getImportIds().length === 0 && this.isEmpty) {
14707 this.graph.warn({
14708 code: 'EMPTY_BUNDLE',
14709 message: 'Generated an empty bundle'
14710 });
14711 }
14712 this.setExternalRenderPaths(options, inputBase);
14713 this.renderedDeclarations = {
14714 dependencies: this.getChunkDependencyDeclarations(options),
14715 exports: this.exportMode === 'none' ? [] : this.getChunkExportDeclarations()
14716 };
14717 timeEnd('render modules', 3);
14718 }
14719 render(options, addons, outputChunk) {
14720 timeStart('render format', 3);
14721 if (!this.renderedSource)
14722 throw new Error('Internal error: Chunk render called before preRender');
14723 const format = options.format;
14724 const finalise = finalisers[format];
14725 if (!finalise) {
14726 error({
14727 code: 'INVALID_OPTION',
14728 message: `Invalid format: ${format} - valid options are ${Object.keys(finalisers).join(', ')}.`
14729 });
14730 }
14731 if (options.dynamicImportFunction && format !== 'es') {
14732 this.graph.warn({
14733 code: 'INVALID_OPTION',
14734 message: '"output.dynamicImportFunction" is ignored for formats other than "esm".'
14735 });
14736 }
14737 // populate ids in the rendered declarations only here
14738 // as chunk ids known only after prerender
14739 for (let i = 0; i < this.dependencies.length; i++) {
14740 const dep = this.dependencies[i];
14741 if (dep instanceof ExternalModule && !dep.renormalizeRenderPath)
14742 continue;
14743 const renderedDependency = this.renderedDeclarations.dependencies[i];
14744 const depId = dep instanceof ExternalModule ? renderedDependency.id : dep.id;
14745 if (dep instanceof Chunk$1)
14746 renderedDependency.namedExportsMode = dep.exportMode !== 'default';
14747 renderedDependency.id = this.getRelativePath(depId);
14748 }
14749 this.finaliseDynamicImports(format);
14750 this.finaliseImportMetas(format);
14751 const hasExports = this.renderedDeclarations.exports.length !== 0 ||
14752 this.renderedDeclarations.dependencies.some(dep => (dep.reexports && dep.reexports.length !== 0));
14753 let usesTopLevelAwait = false;
14754 const accessedGlobals = new Set();
14755 for (const module of this.orderedModules) {
14756 if (module.usesTopLevelAwait) {
14757 usesTopLevelAwait = true;
14758 }
14759 const accessedGlobalVariablesByFormat = module.scope.accessedGlobalVariablesByFormat;
14760 const accessedGlobalVariables = accessedGlobalVariablesByFormat && accessedGlobalVariablesByFormat.get(format);
14761 if (accessedGlobalVariables) {
14762 for (const name of accessedGlobalVariables) {
14763 accessedGlobals.add(name);
14764 }
14765 }
14766 }
14767 if (usesTopLevelAwait && format !== 'es' && format !== 'system') {
14768 error({
14769 code: 'INVALID_TLA_FORMAT',
14770 message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
14771 });
14772 }
14773 const magicString = finalise(this.renderedSource, {
14774 accessedGlobals,
14775 dependencies: this.renderedDeclarations.dependencies,
14776 exports: this.renderedDeclarations.exports,
14777 hasExports,
14778 indentString: this.indentString,
14779 intro: addons.intro,
14780 isEntryModuleFacade: this.facadeModule !== null && this.facadeModule.isEntryPoint,
14781 namedExportsMode: this.exportMode !== 'default',
14782 outro: addons.outro,
14783 usesTopLevelAwait,
14784 varOrConst: options.preferConst ? 'const' : 'var',
14785 warn: this.graph.warn.bind(this.graph)
14786 }, options);
14787 if (addons.banner)
14788 magicString.prepend(addons.banner);
14789 if (addons.footer)
14790 magicString.append(addons.footer);
14791 const prevCode = magicString.toString();
14792 timeEnd('render format', 3);
14793 let map = null;
14794 const chunkSourcemapChain = [];
14795 return renderChunk({
14796 chunk: this,
14797 code: prevCode,
14798 graph: this.graph,
14799 options,
14800 renderChunk: outputChunk,
14801 sourcemapChain: chunkSourcemapChain
14802 }).then((code) => {
14803 if (options.sourcemap) {
14804 timeStart('sourcemap', 3);
14805 let file;
14806 if (options.file)
14807 file = path.resolve(options.sourcemapFile || options.file);
14808 else if (options.dir)
14809 file = path.resolve(options.dir, this.id);
14810 else
14811 file = path.resolve(this.id);
14812 const decodedMap = magicString.generateDecodedMap({});
14813 map = collapseSourcemaps(this, file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources);
14814 map.sources = map.sources.map(sourcePath => index.normalize(options.sourcemapPathTransform ? options.sourcemapPathTransform(sourcePath) : sourcePath));
14815 timeEnd('sourcemap', 3);
14816 }
14817 if (options.compact !== true && code[code.length - 1] !== '\n')
14818 code += '\n';
14819 return { code, map };
14820 });
14821 }
14822 visitDependencies(handleDependency) {
14823 const toBeVisited = [this];
14824 const visited = new Set();
14825 for (const current of toBeVisited) {
14826 handleDependency(current);
14827 if (current instanceof ExternalModule)
14828 continue;
14829 for (const dependency of current.dependencies.concat(current.dynamicDependencies)) {
14830 if (!visited.has(dependency)) {
14831 visited.add(dependency);
14832 toBeVisited.push(dependency);
14833 }
14834 }
14835 }
14836 }
14837 visitStaticDependenciesUntilCondition(isConditionSatisfied) {
14838 const seen = new Set();
14839 function visitDep(dep) {
14840 if (seen.has(dep))
14841 return undefined;
14842 seen.add(dep);
14843 if (dep instanceof Chunk$1) {
14844 for (const subDep of dep.dependencies) {
14845 if (visitDep(subDep))
14846 return true;
14847 }
14848 }
14849 return isConditionSatisfied(dep) === true;
14850 }
14851 return visitDep(this);
14852 }
14853 addDependenciesToChunk(moduleDependencies, chunkDependencies) {
14854 for (const depModule of moduleDependencies) {
14855 if (depModule.chunk === this) {
14856 continue;
14857 }
14858 let dependency;
14859 if (depModule instanceof Module) {
14860 dependency = depModule.chunk;
14861 }
14862 else {
14863 if (!(depModule.used || depModule.moduleSideEffects)) {
14864 continue;
14865 }
14866 dependency = depModule;
14867 }
14868 chunkDependencies.add(dependency);
14869 }
14870 }
14871 assignFacadeName({ fileName, name }, facadedModule) {
14872 if (fileName) {
14873 this.fileName = fileName;
14874 }
14875 else {
14876 this.name = index.sanitizeFileName(name || facadedModule.chunkName || index.getAliasName(facadedModule.id));
14877 }
14878 }
14879 computeContentHashWithDependencies(addons, options) {
14880 const hash = _256();
14881 hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':'));
14882 hash.update(options.format);
14883 this.visitDependencies(dep => {
14884 if (dep instanceof ExternalModule)
14885 hash.update(':' + dep.renderPath);
14886 else
14887 hash.update(dep.getRenderedHash());
14888 });
14889 return hash.digest('hex').substr(0, 8);
14890 }
14891 finaliseDynamicImports(format) {
14892 for (const [module, code] of this.renderedModuleSources) {
14893 for (const { node, resolution } of module.dynamicImports) {
14894 if (!resolution)
14895 continue;
14896 if (resolution instanceof Module) {
14897 if (resolution.chunk !== this && isChunkRendered(resolution.chunk)) {
14898 const resolutionChunk = resolution.facadeChunk || resolution.chunk;
14899 node.renderFinalResolution(code, `'${this.getRelativePath(resolutionChunk.id)}'`, format);
14900 }
14901 }
14902 else {
14903 node.renderFinalResolution(code, resolution instanceof ExternalModule
14904 ? `'${resolution.renormalizeRenderPath
14905 ? this.getRelativePath(resolution.renderPath)
14906 : resolution.id}'`
14907 : resolution, format);
14908 }
14909 }
14910 }
14911 }
14912 finaliseImportMetas(format) {
14913 for (const [module, code] of this.renderedModuleSources) {
14914 for (const importMeta of module.importMetas) {
14915 importMeta.renderFinalMechanism(code, this.id, format, this.graph.pluginDriver);
14916 }
14917 }
14918 }
14919 getChunkDependencyDeclarations(options) {
14920 const reexportDeclarations = new Map();
14921 for (let exportName of this.getExportNames()) {
14922 let exportChunk;
14923 let importName;
14924 let needsLiveBinding = false;
14925 if (exportName[0] === '*') {
14926 needsLiveBinding = options.externalLiveBindings !== false;
14927 exportChunk = this.graph.moduleById.get(exportName.substr(1));
14928 importName = exportName = '*';
14929 }
14930 else {
14931 const variable = this.exportNames[exportName];
14932 const module = variable.module;
14933 // skip local exports
14934 if (!module || module.chunk === this)
14935 continue;
14936 if (module instanceof Module) {
14937 exportChunk = module.chunk;
14938 importName = exportChunk.getVariableExportName(variable);
14939 needsLiveBinding = variable.isReassigned;
14940 }
14941 else {
14942 exportChunk = module;
14943 importName = variable.name;
14944 needsLiveBinding = options.externalLiveBindings !== false;
14945 }
14946 }
14947 let reexportDeclaration = reexportDeclarations.get(exportChunk);
14948 if (!reexportDeclaration)
14949 reexportDeclarations.set(exportChunk, (reexportDeclaration = []));
14950 reexportDeclaration.push({ imported: importName, reexported: exportName, needsLiveBinding });
14951 }
14952 const renderedImports = new Set();
14953 const dependencies = [];
14954 for (const dep of this.dependencies) {
14955 const imports = [];
14956 for (const variable of this.imports) {
14957 const renderedVariable = variable instanceof ExportDefaultVariable ? variable.getOriginalVariable() : variable;
14958 if ((variable.module instanceof Module
14959 ? variable.module.chunk === dep
14960 : variable.module === dep) &&
14961 !renderedImports.has(renderedVariable)) {
14962 renderedImports.add(renderedVariable);
14963 imports.push({
14964 imported: variable.module instanceof ExternalModule
14965 ? variable.name
14966 : variable.module.chunk.getVariableExportName(variable),
14967 local: variable.getName()
14968 });
14969 }
14970 }
14971 const reexports = reexportDeclarations.get(dep);
14972 let exportsNames, exportsDefault;
14973 let namedExportsMode = true;
14974 if (dep instanceof ExternalModule) {
14975 exportsNames = dep.exportsNames || dep.exportsNamespace;
14976 exportsDefault = 'default' in dep.declarations;
14977 }
14978 else {
14979 exportsNames = true;
14980 // we don't want any interop patterns to trigger
14981 exportsDefault = false;
14982 namedExportsMode = dep.exportMode !== 'default';
14983 }
14984 let id = undefined;
14985 let globalName = undefined;
14986 if (dep instanceof ExternalModule) {
14987 id = dep.renderPath;
14988 if (options.format === 'umd' || options.format === 'iife') {
14989 globalName = getGlobalName(dep, options.globals, this.graph, exportsNames || exportsDefault);
14990 }
14991 }
14992 dependencies.push({
14993 exportsDefault,
14994 exportsNames,
14995 globalName,
14996 id,
14997 imports: imports.length > 0 ? imports : null,
14998 isChunk: dep instanceof Chunk$1,
14999 name: dep.variableName,
15000 namedExportsMode,
15001 reexports
15002 });
15003 }
15004 return dependencies;
15005 }
15006 getChunkExportDeclarations() {
15007 const exports = [];
15008 for (const exportName of this.getExportNames()) {
15009 if (exportName[0] === '*')
15010 continue;
15011 const variable = this.exportNames[exportName];
15012 const module = variable.module;
15013 if (module && module.chunk !== this)
15014 continue;
15015 let hoisted = false;
15016 let uninitialized = false;
15017 if (variable instanceof LocalVariable) {
15018 if (variable.init === UNDEFINED_EXPRESSION) {
15019 uninitialized = true;
15020 }
15021 for (const declaration of variable.declarations) {
15022 if (declaration.parent instanceof FunctionDeclaration ||
15023 (declaration instanceof ExportDefaultDeclaration &&
15024 declaration.declaration instanceof FunctionDeclaration)) {
15025 hoisted = true;
15026 break;
15027 }
15028 }
15029 }
15030 else if (variable instanceof GlobalVariable) {
15031 hoisted = true;
15032 }
15033 const localName = variable.getName();
15034 exports.push({
15035 exported: exportName === '*' ? localName : exportName,
15036 hoisted,
15037 local: localName,
15038 uninitialized
15039 });
15040 }
15041 return exports;
15042 }
15043 getFallbackChunkName() {
15044 if (this.manualChunkAlias) {
15045 return this.manualChunkAlias;
15046 }
15047 if (this.fileName) {
15048 return index.getAliasName(this.fileName);
15049 }
15050 return index.getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
15051 }
15052 getRelativePath(targetPath) {
15053 const relativePath = index.normalize(relative(path.dirname(this.id), targetPath));
15054 return relativePath.startsWith('../') ? relativePath : './' + relativePath;
15055 }
15056 inlineChunkDependencies(chunk, deep) {
15057 for (const dep of chunk.dependencies) {
15058 if (dep instanceof ExternalModule) {
15059 if (this.dependencies.indexOf(dep) === -1)
15060 this.dependencies.push(dep);
15061 }
15062 else {
15063 if (dep === this || this.dependencies.indexOf(dep) !== -1)
15064 continue;
15065 if (!dep.isEmpty)
15066 this.dependencies.push(dep);
15067 if (deep)
15068 this.inlineChunkDependencies(dep, true);
15069 }
15070 }
15071 }
15072 prepareDynamicImports() {
15073 for (const module of this.orderedModules) {
15074 for (const { node, resolution } of module.dynamicImports) {
15075 if (!node.included)
15076 continue;
15077 if (resolution instanceof Module) {
15078 if (resolution.chunk === this) {
15079 const namespace = resolution.getOrCreateNamespace();
15080 node.setResolution('named', namespace);
15081 }
15082 else {
15083 node.setResolution(resolution.chunk.exportMode);
15084 }
15085 }
15086 else {
15087 node.setResolution('auto');
15088 }
15089 }
15090 }
15091 }
15092 setExternalRenderPaths(options, inputBase) {
15093 for (const dependency of this.dependencies.concat(this.dynamicDependencies)) {
15094 if (dependency instanceof ExternalModule) {
15095 dependency.setRenderPath(options, inputBase);
15096 }
15097 }
15098 }
15099 setIdentifierRenderResolutions(options) {
15100 for (const exportName of this.getExportNames()) {
15101 const exportVariable = this.exportNames[exportName];
15102 if (exportVariable) {
15103 if (exportVariable instanceof ExportShimVariable) {
15104 this.needsExportsShim = true;
15105 }
15106 exportVariable.exportName = exportName;
15107 if (options.format !== 'es' &&
15108 options.format !== 'system' &&
15109 exportVariable.isReassigned &&
15110 !exportVariable.isId &&
15111 !(exportVariable instanceof ExportDefaultVariable && exportVariable.hasId)) {
15112 exportVariable.setRenderNames('exports', exportName);
15113 }
15114 else {
15115 exportVariable.setRenderNames(null, null);
15116 }
15117 }
15118 }
15119 const usedNames = new Set();
15120 if (this.needsExportsShim) {
15121 usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
15122 }
15123 if (options.format !== 'es') {
15124 usedNames.add('exports');
15125 if (options.format === 'cjs') {
15126 usedNames
15127 .add(INTEROP_DEFAULT_VARIABLE)
15128 .add('require')
15129 .add('module')
15130 .add('__filename')
15131 .add('__dirname');
15132 }
15133 }
15134 deconflictChunk(this.orderedModules, this.dependencies, this.imports, usedNames, options.format, options.interop !== false, this.graph.preserveModules);
15135 }
15136 setUpChunkImportsAndExportsForModule(module) {
15137 for (const variable of module.imports) {
15138 if (variable.module.chunk !== this) {
15139 this.imports.add(variable);
15140 if (variable.module instanceof Module) {
15141 variable.module.chunk.exports.add(variable);
15142 }
15143 }
15144 }
15145 if (module.isEntryPoint ||
15146 module.dynamicallyImportedBy.some(importer => importer.chunk !== this)) {
15147 const map = module.getExportNamesByVariable();
15148 for (const exportedVariable of map.keys()) {
15149 this.exports.add(exportedVariable);
15150 const exportingModule = exportedVariable.module;
15151 if (exportingModule && exportingModule.chunk && exportingModule.chunk !== this) {
15152 exportingModule.chunk.exports.add(exportedVariable);
15153 }
15154 }
15155 }
15156 if (module.getOrCreateNamespace().included) {
15157 for (const reexportName of Object.keys(module.reexports)) {
15158 const reexport = module.reexports[reexportName];
15159 const variable = reexport.module.getVariableForExportName(reexport.localName);
15160 if (variable.module.chunk !== this) {
15161 this.imports.add(variable);
15162 if (variable.module instanceof Module) {
15163 variable.module.chunk.exports.add(variable);
15164 }
15165 }
15166 }
15167 }
15168 for (const { node, resolution } of module.dynamicImports) {
15169 if (node.included && resolution instanceof Module && resolution.chunk === this)
15170 resolution.getOrCreateNamespace().include();
15171 }
15172 }
15173}
15174
15175/*
15176 * Given a chunk list, perform optimizations on that chunk list
15177 * to reduce the mumber of chunks. Mutates the chunks array.
15178 *
15179 * Manual chunks (with chunk.chunkAlias already set) are preserved
15180 * Entry points are carefully preserved as well
15181 *
15182 */
15183function optimizeChunks(chunks, options, CHUNK_GROUPING_SIZE, inputBase) {
15184 for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
15185 const mainChunk = chunks[chunkIndex];
15186 const execGroup = [];
15187 mainChunk.visitStaticDependenciesUntilCondition(dep => {
15188 if (dep instanceof Chunk$1) {
15189 execGroup.push(dep);
15190 }
15191 });
15192 if (execGroup.length < 2) {
15193 continue;
15194 }
15195 let execGroupIndex = 1;
15196 let seekingFirstMergeCandidate = true;
15197 let lastChunk = undefined, chunk = execGroup[0], nextChunk = execGroup[1];
15198 const isMergeCandidate = (chunk) => {
15199 if (chunk.facadeModule !== null || chunk.manualChunkAlias !== null) {
15200 return false;
15201 }
15202 if (!nextChunk || nextChunk.facadeModule !== null) {
15203 return false;
15204 }
15205 if (chunk.getRenderedSourceLength() > CHUNK_GROUPING_SIZE) {
15206 return false;
15207 }
15208 // if (!chunk.isPure()) continue;
15209 return true;
15210 };
15211 do {
15212 if (seekingFirstMergeCandidate) {
15213 if (isMergeCandidate(chunk)) {
15214 seekingFirstMergeCandidate = false;
15215 }
15216 continue;
15217 }
15218 let remainingSize = CHUNK_GROUPING_SIZE - lastChunk.getRenderedSourceLength() - chunk.getRenderedSourceLength();
15219 if (remainingSize <= 0) {
15220 if (!isMergeCandidate(chunk)) {
15221 seekingFirstMergeCandidate = true;
15222 }
15223 continue;
15224 }
15225 // if (!chunk.isPure()) continue;
15226 const chunkDependencies = new Set();
15227 chunk.visitStaticDependenciesUntilCondition(dep => chunkDependencies.add(dep));
15228 const ignoreSizeChunks = new Set([chunk, lastChunk]);
15229 if (lastChunk.visitStaticDependenciesUntilCondition(dep => {
15230 if (dep === chunk || dep === lastChunk) {
15231 return false;
15232 }
15233 if (chunkDependencies.has(dep)) {
15234 return false;
15235 }
15236 if (dep instanceof ExternalModule) {
15237 return true;
15238 }
15239 remainingSize -= dep.getRenderedSourceLength();
15240 if (remainingSize <= 0) {
15241 return true;
15242 }
15243 ignoreSizeChunks.add(dep);
15244 })) {
15245 if (!isMergeCandidate(chunk)) {
15246 seekingFirstMergeCandidate = true;
15247 }
15248 continue;
15249 }
15250 if (chunk.visitStaticDependenciesUntilCondition(dep => {
15251 if (ignoreSizeChunks.has(dep)) {
15252 return false;
15253 }
15254 if (dep instanceof ExternalModule) {
15255 return true;
15256 }
15257 remainingSize -= dep.getRenderedSourceLength();
15258 if (remainingSize <= 0) {
15259 return true;
15260 }
15261 })) {
15262 if (!isMergeCandidate(chunk)) {
15263 seekingFirstMergeCandidate = true;
15264 }
15265 continue;
15266 }
15267 // within the size limit -> merge!
15268 const optimizedChunkIndex = chunks.indexOf(chunk);
15269 if (optimizedChunkIndex <= chunkIndex)
15270 chunkIndex--;
15271 chunks.splice(optimizedChunkIndex, 1);
15272 lastChunk.merge(chunk, chunks, options, inputBase);
15273 execGroup.splice(--execGroupIndex, 1);
15274 chunk = lastChunk;
15275 // keep going to see if we can merge this with the next again
15276 if (nextChunk && !isMergeCandidate(nextChunk)) {
15277 seekingFirstMergeCandidate = true;
15278 }
15279 } while (((lastChunk = chunk), (chunk = nextChunk), (nextChunk = execGroup[++execGroupIndex]), chunk));
15280 }
15281 return chunks;
15282}
15283
15284const tt = acorn.tokTypes;
15285const isIdentifierStart = acorn.isIdentifierStart;
15286var acornBigint = function (Parser) {
15287 return class extends Parser {
15288 parseLiteral(value) {
15289 const node = super.parseLiteral(value);
15290 if (node.raw.charCodeAt(node.raw.length - 1) == 110)
15291 node.bigint = this.getNumberInput(node.start, node.end);
15292 return node;
15293 }
15294 readRadixNumber(radix) {
15295 let start = this.pos;
15296 this.pos += 2; // 0x
15297 let val = this.readInt(radix);
15298 if (val === null)
15299 this.raise(this.start + 2, `Expected number in radix ${radix}`);
15300 if (this.input.charCodeAt(this.pos) == 110) {
15301 let str = this.getNumberInput(start, this.pos);
15302 val = typeof BigInt !== "undefined" ? BigInt(str) : null;
15303 ++this.pos;
15304 }
15305 else if (isIdentifierStart(this.fullCharCodeAtPos()))
15306 this.raise(this.pos, "Identifier directly after number");
15307 return this.finishToken(tt.num, val);
15308 }
15309 readNumber(startsWithDot) {
15310 let start = this.pos;
15311 // Not an int
15312 if (startsWithDot)
15313 return super.readNumber(startsWithDot);
15314 // Legacy octal
15315 if (this.input.charCodeAt(start) === 48 && this.input.charCodeAt(start + 1) !== 110) {
15316 return super.readNumber(startsWithDot);
15317 }
15318 if (this.readInt(10) === null)
15319 this.raise(start, "Invalid number");
15320 // Not a BigInt, reset and parse again
15321 if (this.input.charCodeAt(this.pos) != 110) {
15322 this.pos = start;
15323 return super.readNumber(startsWithDot);
15324 }
15325 let str = this.getNumberInput(start, this.pos);
15326 let val = typeof BigInt !== "undefined" ? BigInt(str) : null;
15327 ++this.pos;
15328 return this.finishToken(tt.num, val);
15329 }
15330 // This is basically a hook for acorn-numeric-separator
15331 getNumberInput(start, end) {
15332 if (super.getNumberInput)
15333 return super.getNumberInput(start, end);
15334 return this.input.slice(start, end);
15335 }
15336 };
15337};
15338
15339/* eslint-disable no-underscore-dangle */
15340const DynamicImportKey = 'Import';
15341// NOTE: This allows `yield import()` to parse correctly.
15342acorn.tokTypes._import.startsExpr = true;
15343function parseDynamicImport() {
15344 const node = this.startNode();
15345 this.next();
15346 if (this.type !== acorn.tokTypes.parenL) {
15347 this.unexpected();
15348 }
15349 return this.finishNode(node, DynamicImportKey);
15350}
15351function parenAfter() {
15352 return /^(\s|\/\/.*|\/\*[^]*?\*\/)*\(/.test(this.input.slice(this.pos));
15353}
15354function dynamicImport(Parser) {
15355 return class extends Parser {
15356 parseStatement(context, topLevel, exports) {
15357 if (this.type === acorn.tokTypes._import && parenAfter.call(this)) {
15358 return this.parseExpressionStatement(this.startNode(), this.parseExpression());
15359 }
15360 return super.parseStatement(context, topLevel, exports);
15361 }
15362 parseExprAtom(refDestructuringErrors) {
15363 if (this.type === acorn.tokTypes._import) {
15364 return parseDynamicImport.call(this);
15365 }
15366 return super.parseExprAtom(refDestructuringErrors);
15367 }
15368 };
15369}
15370
15371const tt$1 = acorn.tokTypes;
15372const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
15373const nextTokenIsDot = parser => {
15374 skipWhiteSpace.lastIndex = parser.pos;
15375 let skip = skipWhiteSpace.exec(parser.input);
15376 let next = parser.pos + skip[0].length;
15377 return parser.input.slice(next, next + 1) === ".";
15378};
15379var acornImportMeta = function (Parser) {
15380 return class extends Parser {
15381 parseExprAtom(refDestructuringErrors) {
15382 if (this.type !== tt$1._import || !nextTokenIsDot(this))
15383 return super.parseExprAtom(refDestructuringErrors);
15384 if (!this.options.allowImportExportEverywhere && !this.inModule) {
15385 this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
15386 }
15387 let node = this.startNode();
15388 node.meta = this.parseIdent(true);
15389 this.expect(tt$1.dot);
15390 node.property = this.parseIdent(true);
15391 if (node.property.name !== "meta") {
15392 this.raiseRecoverable(node.property.start, "The only valid meta property for import is import.meta");
15393 }
15394 if (this.containsEsc) {
15395 this.raiseRecoverable(node.property.start, "\"meta\" in import.meta must not contain escape sequences");
15396 }
15397 return this.finishNode(node, "MetaProperty");
15398 }
15399 parseStatement(context, topLevel, exports) {
15400 if (this.type !== tt$1._import || !nextTokenIsDot(this)) {
15401 return super.parseStatement(context, topLevel, exports);
15402 }
15403 let node = this.startNode();
15404 let expr = this.parseExpression();
15405 return this.parseExpressionStatement(node, expr);
15406 }
15407 };
15408};
15409
15410class UndefinedVariable extends Variable {
15411 constructor() {
15412 super('undefined');
15413 }
15414 getLiteralValueAtPath() {
15415 return undefined;
15416 }
15417}
15418
15419class GlobalScope extends Scope {
15420 constructor() {
15421 super();
15422 this.variables.set('undefined', new UndefinedVariable());
15423 }
15424 findVariable(name) {
15425 let variable = this.variables.get(name);
15426 if (!variable) {
15427 variable = new GlobalVariable(name);
15428 this.variables.set(name, variable);
15429 }
15430 return variable;
15431 }
15432}
15433
15434const getNewTrackedPaths = () => ({
15435 paths: Object.create(null),
15436 tracked: false,
15437 unknownPath: null
15438});
15439class EntityPathTracker {
15440 constructor() {
15441 this.entityPaths = new Map();
15442 }
15443 track(entity, path) {
15444 let trackedPaths = this.entityPaths.get(entity);
15445 if (!trackedPaths) {
15446 trackedPaths = getNewTrackedPaths();
15447 this.entityPaths.set(entity, trackedPaths);
15448 }
15449 let pathIndex = 0, trackedSubPaths;
15450 while (pathIndex < path.length) {
15451 const key = path[pathIndex];
15452 if (typeof key === 'string') {
15453 trackedSubPaths = trackedPaths.paths[key];
15454 if (!trackedSubPaths) {
15455 trackedSubPaths = getNewTrackedPaths();
15456 trackedPaths.paths[key] = trackedSubPaths;
15457 }
15458 }
15459 else {
15460 trackedSubPaths = trackedPaths.unknownPath;
15461 if (!trackedSubPaths) {
15462 trackedSubPaths = getNewTrackedPaths();
15463 trackedPaths.unknownPath = trackedSubPaths;
15464 }
15465 }
15466 trackedPaths = trackedSubPaths;
15467 pathIndex++;
15468 }
15469 const found = trackedPaths.tracked;
15470 trackedPaths.tracked = true;
15471 return found;
15472 }
15473}
15474
15475var BuildPhase;
15476(function (BuildPhase) {
15477 BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
15478 BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
15479 BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
15480})(BuildPhase || (BuildPhase = {}));
15481
15482function generateAssetFileName(name, source, output) {
15483 const emittedName = name || 'asset';
15484 return makeUnique(renderNamePattern(output.assetFileNames, 'output.assetFileNames', {
15485 hash() {
15486 const hash = _256();
15487 hash.update(emittedName);
15488 hash.update(':');
15489 hash.update(source);
15490 return hash.digest('hex').substr(0, 8);
15491 },
15492 ext: () => path.extname(emittedName).substr(1),
15493 extname: () => path.extname(emittedName),
15494 name: () => emittedName.substr(0, emittedName.length - path.extname(emittedName).length)
15495 }), output.bundle);
15496}
15497function reserveFileNameInBundle(fileName, bundle) {
15498 if (fileName in bundle) {
15499 return error(errFileNameConflict(fileName));
15500 }
15501 bundle[fileName] = FILE_PLACEHOLDER;
15502}
15503const FILE_PLACEHOLDER = {
15504 isPlaceholder: true
15505};
15506function hasValidType(emittedFile) {
15507 return (emittedFile &&
15508 (emittedFile.type === 'asset' ||
15509 emittedFile.type === 'chunk'));
15510}
15511function hasValidName(emittedFile) {
15512 const validatedName = emittedFile.fileName || emittedFile.name;
15513 return (!validatedName || (typeof validatedName === 'string' && index.isPlainPathFragment(validatedName)));
15514}
15515function getValidSource(source, emittedFile, fileReferenceId) {
15516 if (typeof source !== 'string' && !Buffer.isBuffer(source)) {
15517 const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
15518 return error(errFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string of Buffer.`));
15519 }
15520 return source;
15521}
15522function getAssetFileName(file, referenceId) {
15523 if (typeof file.fileName !== 'string') {
15524 return error(errAssetNotFinalisedForFileName(file.name || referenceId));
15525 }
15526 return file.fileName;
15527}
15528function getChunkFileName(file) {
15529 const fileName = file.fileName || (file.module && file.module.facadeChunk.id);
15530 if (!fileName)
15531 return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
15532 return fileName;
15533}
15534class FileEmitter {
15535 constructor(graph) {
15536 this.filesByReferenceId = new Map();
15537 // tslint:disable member-ordering
15538 this.buildFilesByReferenceId = this.filesByReferenceId;
15539 this.output = null;
15540 this.emitFile = (emittedFile) => {
15541 if (!hasValidType(emittedFile)) {
15542 return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile &&
15543 emittedFile.type}".`));
15544 }
15545 if (!hasValidName(emittedFile)) {
15546 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 ||
15547 emittedFile.name}".`));
15548 }
15549 if (emittedFile.type === 'chunk') {
15550 return this.emitChunk(emittedFile);
15551 }
15552 else {
15553 return this.emitAsset(emittedFile);
15554 }
15555 };
15556 this.getFileName = (fileReferenceId) => {
15557 const emittedFile = this.filesByReferenceId.get(fileReferenceId);
15558 if (!emittedFile)
15559 return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
15560 if (emittedFile.type === 'chunk') {
15561 return getChunkFileName(emittedFile);
15562 }
15563 else {
15564 return getAssetFileName(emittedFile, fileReferenceId);
15565 }
15566 };
15567 this.setAssetSource = (referenceId, requestedSource) => {
15568 const consumedFile = this.filesByReferenceId.get(referenceId);
15569 if (!consumedFile)
15570 return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
15571 if (consumedFile.type !== 'asset') {
15572 return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
15573 }
15574 if (consumedFile.source !== undefined) {
15575 return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
15576 }
15577 const source = getValidSource(requestedSource, consumedFile, referenceId);
15578 if (this.output) {
15579 this.finalizeAsset(consumedFile, source, referenceId, this.output);
15580 }
15581 else {
15582 consumedFile.source = source;
15583 }
15584 };
15585 this.graph = graph;
15586 }
15587 startOutput(outputBundle, assetFileNames) {
15588 this.filesByReferenceId = new Map(this.buildFilesByReferenceId);
15589 this.output = {
15590 assetFileNames,
15591 bundle: outputBundle
15592 };
15593 for (const emittedFile of this.filesByReferenceId.values()) {
15594 if (emittedFile.fileName) {
15595 reserveFileNameInBundle(emittedFile.fileName, this.output.bundle);
15596 }
15597 }
15598 for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) {
15599 if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
15600 this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.output);
15601 }
15602 }
15603 }
15604 assertAssetsFinalized() {
15605 for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) {
15606 if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
15607 error(errNoAssetSourceSet(emittedFile.name || referenceId));
15608 }
15609 }
15610 emitAsset(emittedAsset) {
15611 const source = typeof emittedAsset.source !== 'undefined'
15612 ? getValidSource(emittedAsset.source, emittedAsset, null)
15613 : undefined;
15614 const consumedAsset = {
15615 fileName: emittedAsset.fileName,
15616 name: emittedAsset.name,
15617 source,
15618 type: 'asset'
15619 };
15620 const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
15621 if (this.output) {
15622 if (emittedAsset.fileName) {
15623 reserveFileNameInBundle(emittedAsset.fileName, this.output.bundle);
15624 }
15625 if (source !== undefined) {
15626 this.finalizeAsset(consumedAsset, source, referenceId, this.output);
15627 }
15628 }
15629 return referenceId;
15630 }
15631 emitChunk(emittedChunk) {
15632 if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
15633 error(errInvalidRollupPhaseForChunkEmission());
15634 }
15635 if (typeof emittedChunk.id !== 'string') {
15636 return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
15637 }
15638 const consumedChunk = {
15639 fileName: emittedChunk.fileName,
15640 module: null,
15641 name: emittedChunk.name || emittedChunk.id,
15642 type: 'chunk'
15643 };
15644 this.graph.moduleLoader
15645 .addEntryModules([
15646 {
15647 fileName: emittedChunk.fileName || null,
15648 id: emittedChunk.id,
15649 name: emittedChunk.name || null
15650 }
15651 ], false)
15652 .then(({ newEntryModules: [module] }) => {
15653 consumedChunk.module = module;
15654 })
15655 .catch(() => {
15656 // Avoid unhandled Promise rejection as the error will be thrown later
15657 // once module loading has finished
15658 });
15659 return this.assignReferenceId(consumedChunk, emittedChunk.id);
15660 }
15661 assignReferenceId(file, idBase) {
15662 let referenceId;
15663 do {
15664 const hash = _256();
15665 if (referenceId) {
15666 hash.update(referenceId);
15667 }
15668 else {
15669 hash.update(idBase);
15670 }
15671 referenceId = hash.digest('hex').substr(0, 8);
15672 } while (this.filesByReferenceId.has(referenceId));
15673 this.filesByReferenceId.set(referenceId, file);
15674 return referenceId;
15675 }
15676 finalizeAsset(consumedFile, source, referenceId, output) {
15677 const fileName = consumedFile.fileName ||
15678 this.findExistingAssetFileNameWithSource(output.bundle, source) ||
15679 generateAssetFileName(consumedFile.name, source, output);
15680 // We must not modify the original assets to avoid interaction between outputs
15681 const assetWithFileName = Object.assign({}, consumedFile, { source, fileName });
15682 this.filesByReferenceId.set(referenceId, assetWithFileName);
15683 output.bundle[fileName] = { fileName, isAsset: true, source };
15684 }
15685 findExistingAssetFileNameWithSource(bundle, source) {
15686 for (const fileName of Object.keys(bundle)) {
15687 const outputFile = bundle[fileName];
15688 if (outputFile.isAsset &&
15689 (Buffer.isBuffer(source) && Buffer.isBuffer(outputFile.source)
15690 ? source.equals(outputFile.source)
15691 : source === outputFile.source))
15692 return fileName;
15693 }
15694 return null;
15695 }
15696}
15697
15698const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
15699const deprecatedHooks = [
15700 { active: true, deprecated: 'ongenerate', replacement: 'generateBundle' },
15701 { active: true, deprecated: 'onwrite', replacement: 'generateBundle/writeBundle' },
15702 { active: true, deprecated: 'transformBundle', replacement: 'renderChunk' },
15703 { active: true, deprecated: 'transformChunk', replacement: 'renderChunk' },
15704 { active: false, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
15705];
15706function warnDeprecatedHooks(plugins, graph) {
15707 for (const { active, deprecated, replacement } of deprecatedHooks) {
15708 for (const plugin of plugins) {
15709 if (deprecated in plugin) {
15710 graph.warnDeprecation({
15711 message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
15712 plugin: plugin.name
15713 }, active);
15714 }
15715 }
15716 }
15717}
15718function throwPluginError(err, plugin, { hook, id } = {}) {
15719 if (typeof err === 'string')
15720 err = { message: err };
15721 if (err.code && err.code !== Errors.PLUGIN_ERROR) {
15722 err.pluginCode = err.code;
15723 }
15724 err.code = Errors.PLUGIN_ERROR;
15725 err.plugin = plugin;
15726 if (hook) {
15727 err.hook = hook;
15728 }
15729 if (id) {
15730 err.id = id;
15731 }
15732 return error(err);
15733}
15734function createPluginDriver(graph, options, pluginCache, watcher) {
15735 warnDeprecatedHooks(options.plugins, graph);
15736 function getDeprecatedHookHandler(handler, handlerName, newHandlerName, pluginName, acitveDeprecation) {
15737 let deprecationWarningShown = false;
15738 return ((...args) => {
15739 if (!deprecationWarningShown) {
15740 deprecationWarningShown = true;
15741 graph.warnDeprecation({
15742 message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
15743 plugin: pluginName
15744 }, acitveDeprecation);
15745 }
15746 return handler(...args);
15747 });
15748 }
15749 const plugins = [
15750 ...options.plugins,
15751 getRollupDefaultPlugin(options.preserveSymlinks)
15752 ];
15753 const fileEmitter = new FileEmitter(graph);
15754 const existingPluginKeys = new Set();
15755 const pluginContexts = plugins.map((plugin, pidx) => {
15756 let cacheable = true;
15757 if (typeof plugin.cacheKey !== 'string') {
15758 if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) || existingPluginKeys.has(plugin.name)) {
15759 cacheable = false;
15760 }
15761 else {
15762 existingPluginKeys.add(plugin.name);
15763 }
15764 }
15765 let cacheInstance;
15766 if (!pluginCache) {
15767 cacheInstance = noCache;
15768 }
15769 else if (cacheable) {
15770 const cacheKey = plugin.cacheKey || plugin.name;
15771 cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
15772 }
15773 else {
15774 cacheInstance = uncacheablePlugin(plugin.name);
15775 }
15776 const context = {
15777 addWatchFile(id) {
15778 if (graph.phase >= BuildPhase.GENERATE)
15779 this.error(errInvalidRollupPhaseForAddWatchFile());
15780 graph.watchFiles[id] = true;
15781 },
15782 cache: cacheInstance,
15783 emitAsset: getDeprecatedHookHandler((name, source) => fileEmitter.emitFile({ type: 'asset', name, source }), 'emitAsset', 'emitFile', plugin.name, false),
15784 emitChunk: getDeprecatedHookHandler((id, options) => fileEmitter.emitFile({ type: 'chunk', id, name: options && options.name }), 'emitChunk', 'emitFile', plugin.name, false),
15785 emitFile: fileEmitter.emitFile,
15786 error(err) {
15787 return throwPluginError(err, plugin.name);
15788 },
15789 getAssetFileName: getDeprecatedHookHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, false),
15790 getChunkFileName: getDeprecatedHookHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, false),
15791 getFileName: fileEmitter.getFileName,
15792 getModuleInfo(moduleId) {
15793 const foundModule = graph.moduleById.get(moduleId);
15794 if (foundModule == null) {
15795 throw new Error(`Unable to find module ${moduleId}`);
15796 }
15797 return {
15798 hasModuleSideEffects: foundModule.moduleSideEffects,
15799 id: foundModule.id,
15800 importedIds: foundModule instanceof ExternalModule
15801 ? []
15802 : foundModule.sources.map(id => foundModule.resolvedIds[id].id),
15803 isEntry: foundModule instanceof Module && foundModule.isEntryPoint,
15804 isExternal: foundModule instanceof ExternalModule
15805 };
15806 },
15807 isExternal: getDeprecatedHookHandler((id, parentId, isResolved = false) => graph.moduleLoader.isExternal(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, false),
15808 meta: {
15809 rollupVersion: index.version
15810 },
15811 get moduleIds() {
15812 return graph.moduleById.keys();
15813 },
15814 parse: graph.contextParse,
15815 resolve(source, importer, options) {
15816 return graph.moduleLoader.resolveId(source, importer, options && options.skipSelf ? pidx : null);
15817 },
15818 resolveId: getDeprecatedHookHandler((source, importer) => graph.moduleLoader
15819 .resolveId(source, importer)
15820 .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, false),
15821 setAssetSource: fileEmitter.setAssetSource,
15822 warn(warning) {
15823 if (typeof warning === 'string')
15824 warning = { message: warning };
15825 if (warning.code)
15826 warning.pluginCode = warning.code;
15827 warning.code = 'PLUGIN_WARNING';
15828 warning.plugin = plugin.name;
15829 graph.warn(warning);
15830 },
15831 watcher: watcher
15832 ? (() => {
15833 let deprecationWarningShown = false;
15834 function deprecatedWatchListener(event, handler) {
15835 if (!deprecationWarningShown) {
15836 context.warn({
15837 code: 'PLUGIN_WATCHER_DEPRECATED',
15838 message: `this.watcher usage is deprecated in plugins. Use the watchChange plugin hook and this.addWatchFile() instead.`
15839 });
15840 deprecationWarningShown = true;
15841 }
15842 return watcher.on(event, handler);
15843 }
15844 return Object.assign({}, watcher, { addListener: deprecatedWatchListener, on: deprecatedWatchListener });
15845 })()
15846 : undefined
15847 };
15848 return context;
15849 });
15850 function runHookSync(hookName, args, pluginIndex, permitValues = false, hookContext) {
15851 const plugin = plugins[pluginIndex];
15852 let context = pluginContexts[pluginIndex];
15853 const hook = plugin[hookName];
15854 if (!hook)
15855 return undefined;
15856 if (hookContext) {
15857 context = hookContext(context, plugin);
15858 if (!context || context === pluginContexts[pluginIndex])
15859 throw new Error('Internal Rollup error: hookContext must return a new context object.');
15860 }
15861 try {
15862 // permit values allows values to be returned instead of a functional hook
15863 if (typeof hook !== 'function') {
15864 if (permitValues)
15865 return hook;
15866 error({
15867 code: 'INVALID_PLUGIN_HOOK',
15868 message: `Error running plugin hook ${hookName} for ${plugin.name}, expected a function hook.`
15869 });
15870 }
15871 return hook.apply(context, args);
15872 }
15873 catch (err) {
15874 return throwPluginError(err, plugin.name, { hook: hookName });
15875 }
15876 }
15877 function runHook(hookName, args, pluginIndex, permitValues = false, hookContext) {
15878 const plugin = plugins[pluginIndex];
15879 let context = pluginContexts[pluginIndex];
15880 const hook = plugin[hookName];
15881 if (!hook)
15882 return undefined;
15883 if (hookContext) {
15884 context = hookContext(context, plugin);
15885 if (!context || context === pluginContexts[pluginIndex])
15886 throw new Error('Internal Rollup error: hookContext must return a new context object.');
15887 }
15888 return Promise.resolve()
15889 .then(() => {
15890 // permit values allows values to be returned instead of a functional hook
15891 if (typeof hook !== 'function') {
15892 if (permitValues)
15893 return hook;
15894 error({
15895 code: 'INVALID_PLUGIN_HOOK',
15896 message: `Error running plugin hook ${hookName} for ${plugin.name}, expected a function hook.`
15897 });
15898 }
15899 return hook.apply(context, args);
15900 })
15901 .catch(err => throwPluginError(err, plugin.name, { hook: hookName }));
15902 }
15903 const pluginDriver = {
15904 emitFile: fileEmitter.emitFile,
15905 finaliseAssets() {
15906 fileEmitter.assertAssetsFinalized();
15907 },
15908 getFileName: fileEmitter.getFileName,
15909 // chains, ignores returns
15910 hookSeq(name, args, hookContext) {
15911 let promise = Promise.resolve();
15912 for (let i = 0; i < plugins.length; i++)
15913 promise = promise.then(() => runHook(name, args, i, false, hookContext));
15914 return promise;
15915 },
15916 // chains, ignores returns
15917 hookSeqSync(name, args, hookContext) {
15918 for (let i = 0; i < plugins.length; i++)
15919 runHookSync(name, args, i, false, hookContext);
15920 },
15921 // chains, first non-null result stops and returns
15922 hookFirst(name, args, hookContext, skip) {
15923 let promise = Promise.resolve();
15924 for (let i = 0; i < plugins.length; i++) {
15925 if (skip === i)
15926 continue;
15927 promise = promise.then((result) => {
15928 if (result != null)
15929 return result;
15930 return runHook(name, args, i, false, hookContext);
15931 });
15932 }
15933 return promise;
15934 },
15935 // chains synchronously, first non-null result stops and returns
15936 hookFirstSync(name, args, hookContext) {
15937 for (let i = 0; i < plugins.length; i++) {
15938 const result = runHookSync(name, args, i, false, hookContext);
15939 if (result != null)
15940 return result;
15941 }
15942 return null;
15943 },
15944 // parallel, ignores returns
15945 hookParallel(name, args, hookContext) {
15946 const promises = [];
15947 for (let i = 0; i < plugins.length; i++) {
15948 const hookPromise = runHook(name, args, i, false, hookContext);
15949 if (!hookPromise)
15950 continue;
15951 promises.push(hookPromise);
15952 }
15953 return Promise.all(promises).then(() => { });
15954 },
15955 // chains, reduces returns of type R, to type T, handling the reduced value as the first hook argument
15956 hookReduceArg0(name, [arg0, ...args], reduce, hookContext) {
15957 let promise = Promise.resolve(arg0);
15958 for (let i = 0; i < plugins.length; i++) {
15959 promise = promise.then(arg0 => {
15960 const hookPromise = runHook(name, [arg0, ...args], i, false, hookContext);
15961 if (!hookPromise)
15962 return arg0;
15963 return hookPromise.then((result) => reduce.call(pluginContexts[i], arg0, result, plugins[i]));
15964 });
15965 }
15966 return promise;
15967 },
15968 // chains synchronously, reduces returns of type R, to type T, handling the reduced value as the first hook argument
15969 hookReduceArg0Sync(name, [arg0, ...args], reduce, hookContext) {
15970 for (let i = 0; i < plugins.length; i++) {
15971 const result = runHookSync(name, [arg0, ...args], i, false, hookContext);
15972 arg0 = reduce.call(pluginContexts[i], arg0, result, plugins[i]);
15973 }
15974 return arg0;
15975 },
15976 // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values.
15977 hookReduceValue(name, initial, args, reduce, hookContext) {
15978 let promise = Promise.resolve(initial);
15979 for (let i = 0; i < plugins.length; i++) {
15980 promise = promise.then(value => {
15981 const hookPromise = runHook(name, args, i, true, hookContext);
15982 if (!hookPromise)
15983 return value;
15984 return hookPromise.then((result) => reduce.call(pluginContexts[i], value, result, plugins[i]));
15985 });
15986 }
15987 return promise;
15988 },
15989 startOutput(outputBundle, assetFileNames) {
15990 fileEmitter.startOutput(outputBundle, assetFileNames);
15991 }
15992 };
15993 return pluginDriver;
15994}
15995function createPluginCache(cache) {
15996 return {
15997 has(id) {
15998 const item = cache[id];
15999 if (!item)
16000 return false;
16001 item[0] = 0;
16002 return true;
16003 },
16004 get(id) {
16005 const item = cache[id];
16006 if (!item)
16007 return undefined;
16008 item[0] = 0;
16009 return item[1];
16010 },
16011 set(id, value) {
16012 cache[id] = [0, value];
16013 },
16014 delete(id) {
16015 return delete cache[id];
16016 }
16017 };
16018}
16019function trackPluginCache(pluginCache) {
16020 const result = { used: false, cache: undefined };
16021 result.cache = {
16022 has(id) {
16023 result.used = true;
16024 return pluginCache.has(id);
16025 },
16026 get(id) {
16027 result.used = true;
16028 return pluginCache.get(id);
16029 },
16030 set(id, value) {
16031 result.used = true;
16032 return pluginCache.set(id, value);
16033 },
16034 delete(id) {
16035 result.used = true;
16036 return pluginCache.delete(id);
16037 }
16038 };
16039 return result;
16040}
16041const noCache = {
16042 has() {
16043 return false;
16044 },
16045 get() {
16046 return undefined;
16047 },
16048 set() { },
16049 delete() {
16050 return false;
16051 }
16052};
16053function uncacheablePluginError(pluginName) {
16054 if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX))
16055 error({
16056 code: 'ANONYMOUS_PLUGIN_CACHE',
16057 message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
16058 });
16059 else
16060 error({
16061 code: 'DUPLICATE_PLUGIN_NAME',
16062 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).`
16063 });
16064}
16065const uncacheablePlugin = pluginName => ({
16066 has() {
16067 uncacheablePluginError(pluginName);
16068 return false;
16069 },
16070 get() {
16071 uncacheablePluginError(pluginName);
16072 return undefined;
16073 },
16074 set() {
16075 uncacheablePluginError(pluginName);
16076 },
16077 delete() {
16078 uncacheablePluginError(pluginName);
16079 return false;
16080 }
16081});
16082
16083function transform(graph, source, module) {
16084 const id = module.id;
16085 const sourcemapChain = [];
16086 let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
16087 const originalCode = source.code;
16088 let ast = source.ast;
16089 const transformDependencies = [];
16090 const emittedFiles = [];
16091 let customTransformCache = false;
16092 let moduleSideEffects = null;
16093 let trackedPluginCache;
16094 let curPlugin;
16095 const curSource = source.code;
16096 function transformReducer(code, result, plugin) {
16097 // track which plugins use the custom this.cache to opt-out of transform caching
16098 if (!customTransformCache && trackedPluginCache.used)
16099 customTransformCache = true;
16100 if (customTransformCache) {
16101 if (result && typeof result === 'object' && Array.isArray(result.dependencies)) {
16102 for (const dep of result.dependencies) {
16103 graph.watchFiles[path.resolve(path.dirname(id), dep)] = true;
16104 }
16105 }
16106 }
16107 else {
16108 // files emitted by a transform hook need to be emitted again if the hook is skipped
16109 if (emittedFiles.length)
16110 module.transformFiles = emittedFiles;
16111 if (result && typeof result === 'object' && Array.isArray(result.dependencies)) {
16112 // not great, but a useful way to track this without assuming WeakMap
16113 if (!curPlugin.warnedTransformDependencies)
16114 graph.warnDeprecation(`Returning "dependencies" from the "transform" hook as done by plugin ${plugin.name} is deprecated. The "this.addWatchFile" plugin context function should be used instead.`, true);
16115 curPlugin.warnedTransformDependencies = true;
16116 for (const dep of result.dependencies)
16117 transformDependencies.push(path.resolve(path.dirname(id), dep));
16118 }
16119 }
16120 if (typeof result === 'string') {
16121 result = {
16122 ast: undefined,
16123 code: result,
16124 map: undefined
16125 };
16126 }
16127 else if (result && typeof result === 'object') {
16128 if (typeof result.map === 'string') {
16129 result.map = JSON.parse(result.map);
16130 }
16131 if (typeof result.moduleSideEffects === 'boolean') {
16132 moduleSideEffects = result.moduleSideEffects;
16133 }
16134 }
16135 else {
16136 return code;
16137 }
16138 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
16139 if (result.map !== null) {
16140 const map = decodedSourcemap(result.map);
16141 sourcemapChain.push(map || { missing: true, plugin: plugin.name });
16142 }
16143 ast = result.ast;
16144 return result.code;
16145 }
16146 let setAssetSourceErr;
16147 return graph.pluginDriver
16148 .hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
16149 curPlugin = plugin;
16150 if (curPlugin.cacheKey)
16151 customTransformCache = true;
16152 else
16153 trackedPluginCache = trackPluginCache(pluginContext.cache);
16154 return Object.assign({}, pluginContext, { cache: trackedPluginCache ? trackedPluginCache.cache : pluginContext.cache, warn(warning, pos) {
16155 if (typeof warning === 'string')
16156 warning = { message: warning };
16157 if (pos)
16158 augmentCodeLocation(warning, pos, curSource, id);
16159 warning.id = id;
16160 warning.hook = 'transform';
16161 pluginContext.warn(warning);
16162 },
16163 error(err, pos) {
16164 if (typeof err === 'string')
16165 err = { message: err };
16166 if (pos)
16167 augmentCodeLocation(err, pos, curSource, id);
16168 err.id = id;
16169 err.hook = 'transform';
16170 return pluginContext.error(err);
16171 },
16172 emitAsset(name, source) {
16173 const emittedFile = { type: 'asset', name, source };
16174 emittedFiles.push(Object.assign({}, emittedFile));
16175 return graph.pluginDriver.emitFile(emittedFile);
16176 },
16177 emitChunk(id, options) {
16178 const emittedFile = { type: 'chunk', id, name: options && options.name };
16179 emittedFiles.push(Object.assign({}, emittedFile));
16180 return graph.pluginDriver.emitFile(emittedFile);
16181 },
16182 emitFile(emittedFile) {
16183 emittedFiles.push(emittedFile);
16184 return graph.pluginDriver.emitFile(emittedFile);
16185 },
16186 addWatchFile(id) {
16187 transformDependencies.push(id);
16188 pluginContext.addWatchFile(id);
16189 },
16190 setAssetSource(assetReferenceId, source) {
16191 pluginContext.setAssetSource(assetReferenceId, source);
16192 if (!customTransformCache && !setAssetSourceErr) {
16193 try {
16194 this.error({
16195 code: 'INVALID_SETASSETSOURCE',
16196 message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
16197 });
16198 }
16199 catch (err) {
16200 setAssetSourceErr = err;
16201 }
16202 }
16203 },
16204 getCombinedSourcemap() {
16205 const combinedMap = collapseSourcemap(graph, id, originalCode, originalSourcemap, sourcemapChain);
16206 if (!combinedMap) {
16207 const magicString = new MagicString(originalCode);
16208 return magicString.generateMap({ includeContent: true, hires: true, source: id });
16209 }
16210 if (originalSourcemap !== combinedMap) {
16211 originalSourcemap = combinedMap;
16212 sourcemapChain.length = 0;
16213 }
16214 return new SourceMap(Object.assign({}, combinedMap, { file: null, sourcesContent: combinedMap.sourcesContent }));
16215 } });
16216 })
16217 .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id }))
16218 .then(code => {
16219 if (!customTransformCache && setAssetSourceErr)
16220 throw setAssetSourceErr;
16221 return {
16222 ast: ast,
16223 code,
16224 customTransformCache,
16225 moduleSideEffects,
16226 originalCode,
16227 originalSourcemap,
16228 sourcemapChain,
16229 transformDependencies
16230 };
16231 });
16232}
16233
16234function normalizeRelativeExternalId(importer, source) {
16235 return index.isRelative(source) ? path.resolve(importer, '..', source) : source;
16236}
16237function getIdMatcher(option) {
16238 if (option === true) {
16239 return () => true;
16240 }
16241 if (typeof option === 'function') {
16242 return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
16243 }
16244 if (option) {
16245 const ids = new Set(Array.isArray(option) ? option : option ? [option] : []);
16246 return (id => ids.has(id));
16247 }
16248 return () => false;
16249}
16250function getHasModuleSideEffects(moduleSideEffectsOption, pureExternalModules, graph) {
16251 if (typeof moduleSideEffectsOption === 'boolean') {
16252 return () => moduleSideEffectsOption;
16253 }
16254 if (moduleSideEffectsOption === 'no-external') {
16255 return (_id, external) => !external;
16256 }
16257 if (typeof moduleSideEffectsOption === 'function') {
16258 return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
16259 }
16260 if (Array.isArray(moduleSideEffectsOption)) {
16261 const ids = new Set(moduleSideEffectsOption);
16262 return id => ids.has(id);
16263 }
16264 if (moduleSideEffectsOption) {
16265 graph.warn(errInvalidOption('treeshake.moduleSideEffects', 'please use one of false, "no-external", a function or an array'));
16266 }
16267 const isPureExternalModule = getIdMatcher(pureExternalModules);
16268 return (id, external) => !(external && isPureExternalModule(id));
16269}
16270class ModuleLoader {
16271 constructor(graph, modulesById, pluginDriver, external, getManualChunk, moduleSideEffects, pureExternalModules) {
16272 this.entryModules = [];
16273 this.latestLoadModulesPromise = Promise.resolve();
16274 this.manualChunkModules = {};
16275 this.loadEntryModule = (unresolvedId, isEntry) => this.pluginDriver.hookFirst('resolveId', [unresolvedId, undefined]).then(resolveIdResult => {
16276 if (resolveIdResult === false ||
16277 (resolveIdResult && typeof resolveIdResult === 'object' && resolveIdResult.external)) {
16278 return error(errEntryCannotBeExternal(unresolvedId));
16279 }
16280 const id = resolveIdResult && typeof resolveIdResult === 'object'
16281 ? resolveIdResult.id
16282 : resolveIdResult;
16283 if (typeof id === 'string') {
16284 return this.fetchModule(id, undefined, true, isEntry);
16285 }
16286 return error(errUnresolvedEntry(unresolvedId));
16287 });
16288 this.graph = graph;
16289 this.modulesById = modulesById;
16290 this.pluginDriver = pluginDriver;
16291 this.isExternal = getIdMatcher(external);
16292 this.hasModuleSideEffects = getHasModuleSideEffects(moduleSideEffects, pureExternalModules, graph);
16293 this.getManualChunk = typeof getManualChunk === 'function' ? getManualChunk : () => null;
16294 }
16295 addEntryModules(unresolvedEntryModules, isUserDefined) {
16296 const loadNewEntryModulesPromise = Promise.all(unresolvedEntryModules.map(({ fileName, id, name }) => this.loadEntryModule(id, true).then(module => {
16297 if (fileName !== null) {
16298 module.chunkFileNames.add(fileName);
16299 }
16300 else if (name !== null) {
16301 if (module.chunkName === null) {
16302 module.chunkName = name;
16303 }
16304 if (isUserDefined) {
16305 module.userChunkNames.add(name);
16306 }
16307 }
16308 return module;
16309 }))).then(entryModules => {
16310 for (const entryModule of entryModules) {
16311 entryModule.isUserDefinedEntryPoint = entryModule.isUserDefinedEntryPoint || isUserDefined;
16312 const existingEntryModule = this.entryModules.find(module => module.id === entryModule.id);
16313 if (!existingEntryModule) {
16314 this.entryModules.push(entryModule);
16315 }
16316 }
16317 return entryModules;
16318 });
16319 return this.awaitLoadModulesPromise(loadNewEntryModulesPromise).then(newEntryModules => ({
16320 entryModules: this.entryModules,
16321 manualChunkModulesByAlias: this.manualChunkModules,
16322 newEntryModules
16323 }));
16324 }
16325 addManualChunks(manualChunks) {
16326 const unresolvedManualChunks = [];
16327 for (const alias of Object.keys(manualChunks)) {
16328 const manualChunkIds = manualChunks[alias];
16329 for (const id of manualChunkIds) {
16330 unresolvedManualChunks.push({ id, alias });
16331 }
16332 }
16333 const loadNewManualChunkModulesPromise = Promise.all(unresolvedManualChunks.map(({ id }) => this.loadEntryModule(id, false))).then(manualChunkModules => {
16334 for (let index = 0; index < manualChunkModules.length; index++) {
16335 this.addModuleToManualChunk(unresolvedManualChunks[index].alias, manualChunkModules[index]);
16336 }
16337 });
16338 return this.awaitLoadModulesPromise(loadNewManualChunkModulesPromise);
16339 }
16340 resolveId(source, importer, skip) {
16341 return __awaiter(this, void 0, void 0, function* () {
16342 return this.normalizeResolveIdResult(this.isExternal(source, importer, false)
16343 ? false
16344 : yield this.pluginDriver.hookFirst('resolveId', [source, importer], null, skip), importer, source);
16345 });
16346 }
16347 addModuleToManualChunk(alias, module) {
16348 if (module.manualChunkAlias !== null && module.manualChunkAlias !== alias) {
16349 error(errCannotAssignModuleToChunk(module.id, alias, module.manualChunkAlias));
16350 }
16351 module.manualChunkAlias = alias;
16352 if (!this.manualChunkModules[alias]) {
16353 this.manualChunkModules[alias] = [];
16354 }
16355 this.manualChunkModules[alias].push(module);
16356 }
16357 awaitLoadModulesPromise(loadNewModulesPromise) {
16358 this.latestLoadModulesPromise = Promise.all([
16359 loadNewModulesPromise,
16360 this.latestLoadModulesPromise
16361 ]);
16362 const getCombinedPromise = () => {
16363 const startingPromise = this.latestLoadModulesPromise;
16364 return startingPromise.then(() => {
16365 if (this.latestLoadModulesPromise !== startingPromise) {
16366 return getCombinedPromise();
16367 }
16368 });
16369 };
16370 return getCombinedPromise().then(() => loadNewModulesPromise);
16371 }
16372 fetchAllDependencies(module) {
16373 const fetchDynamicImportsPromise = Promise.all(module.getDynamicImportExpressions().map((specifier, index$1) => this.resolveDynamicImport(module, specifier, module.id).then(resolvedId => {
16374 if (resolvedId === null)
16375 return;
16376 const dynamicImport = module.dynamicImports[index$1];
16377 if (typeof resolvedId === 'string') {
16378 dynamicImport.resolution = resolvedId;
16379 return;
16380 }
16381 return this.fetchResolvedDependency(index.relativeId(resolvedId.id), module.id, resolvedId).then(module => {
16382 dynamicImport.resolution = module;
16383 });
16384 })));
16385 fetchDynamicImportsPromise.catch(() => { });
16386 return Promise.all(module.sources.map(source => this.resolveAndFetchDependency(module, source))).then(() => fetchDynamicImportsPromise);
16387 }
16388 fetchModule(id, importer, moduleSideEffects, isEntry) {
16389 const existingModule = this.modulesById.get(id);
16390 if (existingModule) {
16391 if (existingModule instanceof ExternalModule)
16392 throw new Error(`Cannot fetch external module ${id}`);
16393 existingModule.isEntryPoint = existingModule.isEntryPoint || isEntry;
16394 return Promise.resolve(existingModule);
16395 }
16396 const module = new Module(this.graph, id, moduleSideEffects, isEntry);
16397 this.modulesById.set(id, module);
16398 const manualChunkAlias = this.getManualChunk(id);
16399 if (typeof manualChunkAlias === 'string') {
16400 this.addModuleToManualChunk(manualChunkAlias, module);
16401 }
16402 timeStart('load modules', 3);
16403 return Promise.resolve(this.pluginDriver.hookFirst('load', [id]))
16404 .catch((err) => {
16405 timeEnd('load modules', 3);
16406 let msg = `Could not load ${id}`;
16407 if (importer)
16408 msg += ` (imported by ${importer})`;
16409 msg += `: ${err.message}`;
16410 err.message = msg;
16411 throw err;
16412 })
16413 .then(source => {
16414 timeEnd('load modules', 3);
16415 if (typeof source === 'string')
16416 return { code: source };
16417 if (source && typeof source === 'object' && typeof source.code === 'string')
16418 return source;
16419 return error(errBadLoader(id));
16420 })
16421 .then(sourceDescription => {
16422 const cachedModule = this.graph.cachedModules.get(id);
16423 if (cachedModule &&
16424 !cachedModule.customTransformCache &&
16425 cachedModule.originalCode === sourceDescription.code) {
16426 if (cachedModule.transformFiles) {
16427 for (const emittedFile of cachedModule.transformFiles)
16428 this.pluginDriver.emitFile(emittedFile);
16429 }
16430 return cachedModule;
16431 }
16432 if (typeof sourceDescription.moduleSideEffects === 'boolean') {
16433 module.moduleSideEffects = sourceDescription.moduleSideEffects;
16434 }
16435 return transform(this.graph, sourceDescription, module);
16436 })
16437 .then((source) => {
16438 module.setSource(source);
16439 this.modulesById.set(id, module);
16440 return this.fetchAllDependencies(module).then(() => {
16441 for (const name in module.exports) {
16442 if (name !== 'default') {
16443 module.exportsAll[name] = module.id;
16444 }
16445 }
16446 module.exportAllSources.forEach(source => {
16447 const id = module.resolvedIds[source].id;
16448 const exportAllModule = this.modulesById.get(id);
16449 if (exportAllModule instanceof ExternalModule)
16450 return;
16451 for (const name in exportAllModule.exportsAll) {
16452 if (name in module.exportsAll) {
16453 this.graph.warn(errNamespaceConflict(name, module, exportAllModule));
16454 }
16455 else {
16456 module.exportsAll[name] = exportAllModule.exportsAll[name];
16457 }
16458 }
16459 });
16460 return module;
16461 });
16462 });
16463 }
16464 fetchResolvedDependency(source, importer, resolvedId) {
16465 if (resolvedId.external) {
16466 if (!this.modulesById.has(resolvedId.id)) {
16467 this.modulesById.set(resolvedId.id, new ExternalModule(this.graph, resolvedId.id, resolvedId.moduleSideEffects));
16468 }
16469 const externalModule = this.modulesById.get(resolvedId.id);
16470 if (!(externalModule instanceof ExternalModule)) {
16471 return error(errInternalIdCannotBeExternal(source, importer));
16472 }
16473 return Promise.resolve(externalModule);
16474 }
16475 else {
16476 return this.fetchModule(resolvedId.id, importer, resolvedId.moduleSideEffects, false);
16477 }
16478 }
16479 handleMissingImports(resolvedId, source, importer) {
16480 if (resolvedId === null) {
16481 if (index.isRelative(source)) {
16482 error(errUnresolvedImport(source, importer));
16483 }
16484 this.graph.warn(errUnresolvedImportTreatedAsExternal(source, importer));
16485 return {
16486 external: true,
16487 id: source,
16488 moduleSideEffects: this.hasModuleSideEffects(source, true)
16489 };
16490 }
16491 return resolvedId;
16492 }
16493 normalizeResolveIdResult(resolveIdResult, importer, source) {
16494 let id = '';
16495 let external = false;
16496 let moduleSideEffects = null;
16497 if (resolveIdResult) {
16498 if (typeof resolveIdResult === 'object') {
16499 id = resolveIdResult.id;
16500 if (resolveIdResult.external) {
16501 external = true;
16502 }
16503 if (typeof resolveIdResult.moduleSideEffects === 'boolean') {
16504 moduleSideEffects = resolveIdResult.moduleSideEffects;
16505 }
16506 }
16507 else {
16508 if (this.isExternal(resolveIdResult, importer, true)) {
16509 external = true;
16510 }
16511 id = external ? normalizeRelativeExternalId(importer, resolveIdResult) : resolveIdResult;
16512 }
16513 }
16514 else {
16515 id = normalizeRelativeExternalId(importer, source);
16516 if (resolveIdResult !== false && !this.isExternal(id, importer, true)) {
16517 return null;
16518 }
16519 external = true;
16520 }
16521 return {
16522 external,
16523 id,
16524 moduleSideEffects: typeof moduleSideEffects === 'boolean'
16525 ? moduleSideEffects
16526 : this.hasModuleSideEffects(id, external)
16527 };
16528 }
16529 resolveAndFetchDependency(module, source) {
16530 return __awaiter(this, void 0, void 0, function* () {
16531 return this.fetchResolvedDependency(source, module.id, (module.resolvedIds[source] =
16532 module.resolvedIds[source] ||
16533 this.handleMissingImports(yield this.resolveId(source, module.id), source, module.id)));
16534 });
16535 }
16536 resolveDynamicImport(module, specifier, importer) {
16537 return __awaiter(this, void 0, void 0, function* () {
16538 // TODO we only should expose the acorn AST here
16539 const resolution = yield this.pluginDriver.hookFirst('resolveDynamicImport', [
16540 specifier,
16541 importer
16542 ]);
16543 if (typeof specifier !== 'string') {
16544 if (typeof resolution === 'string') {
16545 return resolution;
16546 }
16547 if (!resolution) {
16548 return null;
16549 }
16550 return Object.assign({ external: false, moduleSideEffects: true }, resolution);
16551 }
16552 if (resolution == null) {
16553 return (module.resolvedIds[specifier] =
16554 module.resolvedIds[specifier] ||
16555 this.handleMissingImports(yield this.resolveId(specifier, module.id), specifier, module.id));
16556 }
16557 return this.handleMissingImports(this.normalizeResolveIdResult(resolution, importer, specifier), specifier, importer);
16558 });
16559 }
16560}
16561
16562const CHAR_CODE_A = 97;
16563const CHAR_CODE_0 = 48;
16564function intToHex(num) {
16565 if (num < 10)
16566 return String.fromCharCode(CHAR_CODE_0 + num);
16567 else
16568 return String.fromCharCode(CHAR_CODE_A + (num - 10));
16569}
16570function Uint8ArrayToHexString(buffer) {
16571 let str = '';
16572 // hex conversion - 2 chars per 8 bit component
16573 for (let i = 0; i < buffer.length; i++) {
16574 const num = buffer[i];
16575 // big endian conversion, but whatever
16576 str += intToHex(num >> 4);
16577 str += intToHex(num & 0xf);
16578 }
16579 return str;
16580}
16581function Uint8ArrayXor(to, from) {
16582 for (let i = 0; i < to.length; i++)
16583 to[i] = to[i] ^ from[i];
16584 return to;
16585}
16586function randomUint8Array(len) {
16587 const buffer = new Uint8Array(len);
16588 for (let i = 0; i < buffer.length; i++)
16589 buffer[i] = Math.random() * (2 << 8);
16590 return buffer;
16591}
16592
16593function assignChunkColouringHashes(entryModules, manualChunkModules) {
16594 let currentEntry, currentEntryHash;
16595 let modulesVisitedForCurrentEntry;
16596 const handledEntryPoints = new Set();
16597 const dynamicImports = [];
16598 const addCurrentEntryColourToModule = (module) => {
16599 if (currentEntry.manualChunkAlias) {
16600 module.manualChunkAlias = currentEntry.manualChunkAlias;
16601 module.entryPointsHash = currentEntryHash;
16602 }
16603 else {
16604 Uint8ArrayXor(module.entryPointsHash, currentEntryHash);
16605 }
16606 for (const dependency of module.dependencies) {
16607 if (dependency instanceof ExternalModule ||
16608 modulesVisitedForCurrentEntry.has(dependency.id)) {
16609 continue;
16610 }
16611 modulesVisitedForCurrentEntry.add(dependency.id);
16612 if (!handledEntryPoints.has(dependency.id) && !dependency.manualChunkAlias) {
16613 addCurrentEntryColourToModule(dependency);
16614 }
16615 }
16616 for (const { resolution } of module.dynamicImports) {
16617 if (resolution instanceof Module &&
16618 resolution.dynamicallyImportedBy.length > 0 &&
16619 !resolution.manualChunkAlias) {
16620 dynamicImports.push(resolution);
16621 }
16622 }
16623 };
16624 if (manualChunkModules) {
16625 for (const chunkName of Object.keys(manualChunkModules)) {
16626 currentEntryHash = randomUint8Array(10);
16627 for (currentEntry of manualChunkModules[chunkName]) {
16628 modulesVisitedForCurrentEntry = new Set(currentEntry.id);
16629 addCurrentEntryColourToModule(currentEntry);
16630 }
16631 }
16632 }
16633 for (currentEntry of entryModules) {
16634 handledEntryPoints.add(currentEntry.id);
16635 currentEntryHash = randomUint8Array(10);
16636 modulesVisitedForCurrentEntry = new Set(currentEntry.id);
16637 if (!currentEntry.manualChunkAlias) {
16638 addCurrentEntryColourToModule(currentEntry);
16639 }
16640 }
16641 for (currentEntry of dynamicImports) {
16642 if (handledEntryPoints.has(currentEntry.id)) {
16643 continue;
16644 }
16645 handledEntryPoints.add(currentEntry.id);
16646 currentEntryHash = randomUint8Array(10);
16647 modulesVisitedForCurrentEntry = new Set(currentEntry.id);
16648 addCurrentEntryColourToModule(currentEntry);
16649 }
16650}
16651
16652function makeOnwarn() {
16653 const warned = Object.create(null);
16654 return (warning) => {
16655 const str = warning.toString();
16656 if (str in warned)
16657 return;
16658 console.error(str);
16659 warned[str] = true;
16660 };
16661}
16662function normalizeEntryModules(entryModules) {
16663 if (typeof entryModules === 'string') {
16664 return [{ fileName: null, name: null, id: entryModules }];
16665 }
16666 if (Array.isArray(entryModules)) {
16667 return entryModules.map(id => ({ fileName: null, name: null, id }));
16668 }
16669 return Object.keys(entryModules).map(name => ({
16670 fileName: null,
16671 id: entryModules[name],
16672 name
16673 }));
16674}
16675class Graph {
16676 constructor(options, watcher) {
16677 this.moduleById = new Map();
16678 this.needsTreeshakingPass = false;
16679 this.phase = BuildPhase.LOAD_AND_PARSE;
16680 this.watchFiles = Object.create(null);
16681 this.externalModules = [];
16682 this.modules = [];
16683 this.onwarn = options.onwarn || makeOnwarn();
16684 this.deoptimizationTracker = new EntityPathTracker();
16685 this.cachedModules = new Map();
16686 if (options.cache) {
16687 if (options.cache.modules)
16688 for (const module of options.cache.modules)
16689 this.cachedModules.set(module.id, module);
16690 }
16691 if (options.cache !== false) {
16692 this.pluginCache = (options.cache && options.cache.plugins) || Object.create(null);
16693 // increment access counter
16694 for (const name in this.pluginCache) {
16695 const cache = this.pluginCache[name];
16696 for (const key of Object.keys(cache))
16697 cache[key][0]++;
16698 }
16699 }
16700 this.preserveModules = options.preserveModules;
16701 this.strictDeprecations = options.strictDeprecations;
16702 this.cacheExpiry = options.experimentalCacheExpiry;
16703 if (options.treeshake !== false) {
16704 this.treeshakingOptions = options.treeshake
16705 ? {
16706 annotations: options.treeshake.annotations !== false,
16707 moduleSideEffects: options.treeshake.moduleSideEffects,
16708 propertyReadSideEffects: options.treeshake.propertyReadSideEffects !== false,
16709 pureExternalModules: options.treeshake.pureExternalModules,
16710 tryCatchDeoptimization: options.treeshake.tryCatchDeoptimization !== false
16711 }
16712 : {
16713 annotations: true,
16714 moduleSideEffects: true,
16715 propertyReadSideEffects: true,
16716 tryCatchDeoptimization: true
16717 };
16718 if (typeof this.treeshakingOptions.pureExternalModules !== 'undefined') {
16719 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);
16720 }
16721 }
16722 this.contextParse = (code, options = {}) => this.acornParser.parse(code, Object.assign({}, defaultAcornOptions, options, this.acornOptions));
16723 this.pluginDriver = createPluginDriver(this, options, this.pluginCache, watcher);
16724 if (watcher) {
16725 const handleChange = (id) => this.pluginDriver.hookSeqSync('watchChange', [id]);
16726 watcher.on('change', handleChange);
16727 watcher.once('restart', () => {
16728 watcher.removeListener('change', handleChange);
16729 });
16730 }
16731 this.shimMissingExports = options.shimMissingExports;
16732 this.scope = new GlobalScope();
16733 this.context = String(options.context);
16734 const optionsModuleContext = options.moduleContext;
16735 if (typeof optionsModuleContext === 'function') {
16736 this.getModuleContext = id => optionsModuleContext(id) || this.context;
16737 }
16738 else if (typeof optionsModuleContext === 'object') {
16739 const moduleContext = new Map();
16740 for (const key in optionsModuleContext) {
16741 moduleContext.set(path.resolve(key), optionsModuleContext[key]);
16742 }
16743 this.getModuleContext = id => moduleContext.get(id) || this.context;
16744 }
16745 else {
16746 this.getModuleContext = () => this.context;
16747 }
16748 this.acornOptions = options.acorn || {};
16749 const acornPluginsToInject = [];
16750 acornPluginsToInject.push(dynamicImport);
16751 acornPluginsToInject.push(acornImportMeta);
16752 acornPluginsToInject.push(acornBigint);
16753 if (options.experimentalTopLevelAwait) {
16754 this.acornOptions.allowAwaitOutsideFunction = true;
16755 }
16756 const acornInjectPlugins = options.acornInjectPlugins;
16757 acornPluginsToInject.push(...(Array.isArray(acornInjectPlugins)
16758 ? acornInjectPlugins
16759 : acornInjectPlugins
16760 ? [acornInjectPlugins]
16761 : []));
16762 this.acornParser = acorn.Parser.extend(...acornPluginsToInject);
16763 this.moduleLoader = new ModuleLoader(this, this.moduleById, this.pluginDriver, options.external, (typeof options.manualChunks === 'function' && options.manualChunks), (this.treeshakingOptions
16764 ? this.treeshakingOptions.moduleSideEffects
16765 : null), (this.treeshakingOptions
16766 ? this.treeshakingOptions.pureExternalModules
16767 : false));
16768 }
16769 build(entryModules, manualChunks, inlineDynamicImports) {
16770 // Phase 1 – discovery. We load the entry module and find which
16771 // modules it imports, and import those, until we have all
16772 // of the entry module's dependencies
16773 timeStart('parse modules', 2);
16774 return Promise.all([
16775 this.moduleLoader.addEntryModules(normalizeEntryModules(entryModules), true),
16776 (manualChunks &&
16777 typeof manualChunks === 'object' &&
16778 this.moduleLoader.addManualChunks(manualChunks))
16779 ]).then(([{ entryModules, manualChunkModulesByAlias }]) => {
16780 if (entryModules.length === 0) {
16781 throw new Error('You must supply options.input to rollup');
16782 }
16783 for (const module of this.moduleById.values()) {
16784 if (module instanceof Module) {
16785 this.modules.push(module);
16786 this.watchFiles[module.id] = true;
16787 }
16788 else {
16789 this.externalModules.push(module);
16790 }
16791 }
16792 timeEnd('parse modules', 2);
16793 this.phase = BuildPhase.ANALYSE;
16794 // Phase 2 - linking. We populate the module dependency links and
16795 // determine the topological execution order for the bundle
16796 timeStart('analyse dependency graph', 2);
16797 this.link(entryModules);
16798 timeEnd('analyse dependency graph', 2);
16799 // Phase 3 – marking. We include all statements that should be included
16800 timeStart('mark included statements', 2);
16801 if (inlineDynamicImports) {
16802 if (entryModules.length > 1) {
16803 throw new Error('Internal Error: can only inline dynamic imports for single-file builds.');
16804 }
16805 }
16806 for (const module of entryModules) {
16807 module.includeAllExports();
16808 }
16809 this.includeMarked(this.modules);
16810 // check for unused external imports
16811 for (const externalModule of this.externalModules)
16812 externalModule.warnUnusedImports();
16813 timeEnd('mark included statements', 2);
16814 // Phase 4 – we construct the chunks, working out the optimal chunking using
16815 // entry point graph colouring, before generating the import and export facades
16816 timeStart('generate chunks', 2);
16817 if (!this.preserveModules && !inlineDynamicImports) {
16818 assignChunkColouringHashes(entryModules, manualChunkModulesByAlias);
16819 }
16820 // TODO: there is one special edge case unhandled here and that is that any module
16821 // exposed as an unresolvable export * (to a graph external export *,
16822 // either as a namespace import reexported or top-level export *)
16823 // should be made to be its own entry point module before chunking
16824 let chunks = [];
16825 if (this.preserveModules) {
16826 for (const module of this.modules) {
16827 const chunk = new Chunk$1(this, [module]);
16828 if (module.isEntryPoint || !chunk.isEmpty) {
16829 chunk.entryModules = [module];
16830 }
16831 chunks.push(chunk);
16832 }
16833 }
16834 else {
16835 const chunkModules = {};
16836 for (const module of this.modules) {
16837 const entryPointsHashStr = Uint8ArrayToHexString(module.entryPointsHash);
16838 const curChunk = chunkModules[entryPointsHashStr];
16839 if (curChunk) {
16840 curChunk.push(module);
16841 }
16842 else {
16843 chunkModules[entryPointsHashStr] = [module];
16844 }
16845 }
16846 for (const entryHashSum in chunkModules) {
16847 const chunkModulesOrdered = chunkModules[entryHashSum];
16848 sortByExecutionOrder(chunkModulesOrdered);
16849 const chunk = new Chunk$1(this, chunkModulesOrdered);
16850 chunks.push(chunk);
16851 }
16852 }
16853 for (const chunk of chunks) {
16854 chunk.link();
16855 }
16856 chunks = chunks.filter(isChunkRendered);
16857 const facades = [];
16858 for (const chunk of chunks) {
16859 facades.push(...chunk.generateFacades());
16860 }
16861 timeEnd('generate chunks', 2);
16862 this.phase = BuildPhase.GENERATE;
16863 return chunks.concat(facades);
16864 });
16865 }
16866 getCache() {
16867 // handle plugin cache eviction
16868 for (const name in this.pluginCache) {
16869 const cache = this.pluginCache[name];
16870 let allDeleted = true;
16871 for (const key of Object.keys(cache)) {
16872 if (cache[key][0] >= this.cacheExpiry)
16873 delete cache[key];
16874 else
16875 allDeleted = false;
16876 }
16877 if (allDeleted)
16878 delete this.pluginCache[name];
16879 }
16880 return {
16881 modules: this.modules.map(module => module.toJSON()),
16882 plugins: this.pluginCache
16883 };
16884 }
16885 includeMarked(modules) {
16886 if (this.treeshakingOptions) {
16887 let treeshakingPass = 1;
16888 do {
16889 timeStart(`treeshaking pass ${treeshakingPass}`, 3);
16890 this.needsTreeshakingPass = false;
16891 for (const module of modules) {
16892 if (module.isExecuted)
16893 module.include();
16894 }
16895 timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
16896 } while (this.needsTreeshakingPass);
16897 }
16898 else {
16899 // Necessary to properly replace namespace imports
16900 for (const module of modules)
16901 module.includeAllInBundle();
16902 }
16903 }
16904 warn(warning) {
16905 warning.toString = () => {
16906 let str = '';
16907 if (warning.plugin)
16908 str += `(${warning.plugin} plugin) `;
16909 if (warning.loc)
16910 str += `${index.relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
16911 str += warning.message;
16912 return str;
16913 };
16914 this.onwarn(warning);
16915 }
16916 warnDeprecation(deprecation, activeDeprecation) {
16917 if (activeDeprecation || this.strictDeprecations) {
16918 const warning = errDeprecation(deprecation);
16919 if (this.strictDeprecations) {
16920 return error(warning);
16921 }
16922 this.warn(warning);
16923 }
16924 }
16925 link(entryModules) {
16926 for (const module of this.modules) {
16927 module.linkDependencies();
16928 }
16929 const { orderedModules, cyclePaths } = analyseModuleExecution(entryModules);
16930 for (const cyclePath of cyclePaths) {
16931 this.warn({
16932 code: 'CIRCULAR_DEPENDENCY',
16933 importer: cyclePath[0],
16934 message: `Circular dependency: ${cyclePath.join(' -> ')}`
16935 });
16936 }
16937 this.modules = orderedModules;
16938 for (const module of this.modules) {
16939 module.bindReferences();
16940 }
16941 this.warnForMissingExports();
16942 }
16943 warnForMissingExports() {
16944 for (const module of this.modules) {
16945 for (const importName of Object.keys(module.importDescriptions)) {
16946 const importDescription = module.importDescriptions[importName];
16947 if (importDescription.name !== '*' &&
16948 !importDescription.module.getVariableForExportName(importDescription.name)) {
16949 module.warn({
16950 code: 'NON_EXISTENT_EXPORT',
16951 message: `Non-existent export '${importDescription.name}' is imported from ${index.relativeId(importDescription.module.id)}`,
16952 name: importDescription.name,
16953 source: importDescription.module.id
16954 }, importDescription.start);
16955 }
16956 }
16957 }
16958 }
16959}
16960
16961function evalIfFn(strOrFn) {
16962 switch (typeof strOrFn) {
16963 case 'function':
16964 return strOrFn();
16965 case 'string':
16966 return strOrFn;
16967 default:
16968 return '';
16969 }
16970}
16971const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
16972const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
16973function createAddons(graph, options) {
16974 const pluginDriver = graph.pluginDriver;
16975 return Promise.all([
16976 pluginDriver.hookReduceValue('banner', evalIfFn(options.banner), [], concatSep),
16977 pluginDriver.hookReduceValue('footer', evalIfFn(options.footer), [], concatSep),
16978 pluginDriver.hookReduceValue('intro', evalIfFn(options.intro), [], concatDblSep),
16979 pluginDriver.hookReduceValue('outro', evalIfFn(options.outro), [], concatDblSep)
16980 ])
16981 .then(([banner, footer, intro, outro]) => {
16982 if (intro)
16983 intro += '\n\n';
16984 if (outro)
16985 outro = `\n\n${outro}`;
16986 if (banner.length)
16987 banner += '\n';
16988 if (footer.length)
16989 footer = '\n' + footer;
16990 return { intro, outro, banner, footer };
16991 })
16992 .catch((err) => {
16993 error({
16994 code: 'ADDON_ERROR',
16995 message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
16996\tError Message: ${err.message}`
16997 });
16998 });
16999}
17000
17001function assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, bundle) {
17002 const entryChunks = [];
17003 const otherChunks = [];
17004 for (const chunk of chunks) {
17005 (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
17006 ? entryChunks
17007 : otherChunks).push(chunk);
17008 }
17009 // make sure entry chunk names take precedence with regard to deconflicting
17010 const chunksForNaming = entryChunks.concat(otherChunks);
17011 for (const chunk of chunksForNaming) {
17012 const facadeModule = chunk.facadeModule;
17013 if (outputOptions.file) {
17014 chunk.id = path.basename(outputOptions.file);
17015 }
17016 else if (inputOptions.preserveModules) {
17017 chunk.id = chunk.generateIdPreserveModules(inputBase, bundle);
17018 }
17019 else {
17020 let pattern, patternName;
17021 if (facadeModule && facadeModule.isUserDefinedEntryPoint) {
17022 pattern = outputOptions.entryFileNames || '[name].js';
17023 patternName = 'output.entryFileNames';
17024 }
17025 else {
17026 pattern = outputOptions.chunkFileNames || '[name]-[hash].js';
17027 patternName = 'output.chunkFileNames';
17028 }
17029 chunk.id = chunk.generateId(pattern, patternName, addons, outputOptions, bundle);
17030 }
17031 bundle[chunk.id] = FILE_PLACEHOLDER;
17032 }
17033}
17034
17035// ported from https://github.com/substack/node-commondir
17036function commondir(files) {
17037 if (files.length === 0)
17038 return '/';
17039 if (files.length === 1)
17040 return path.dirname(files[0]);
17041 const commonSegments = files.slice(1).reduce((commonSegments, file) => {
17042 const pathSegements = file.split(/\/+|\\+/);
17043 let i;
17044 for (i = 0; commonSegments[i] === pathSegements[i] &&
17045 i < Math.min(commonSegments.length, pathSegements.length); i++)
17046 ;
17047 return commonSegments.slice(0, i);
17048 }, files[0].split(/\/+|\\+/));
17049 // Windows correctly handles paths with forward-slashes
17050 return commonSegments.length > 1 ? commonSegments.join('/') : '/';
17051}
17052
17053function badExports(option, keys) {
17054 error({
17055 code: 'INVALID_EXPORT_OPTION',
17056 message: `'${option}' was specified for output.exports, but entry module has following exports: ${keys.join(', ')}`
17057 });
17058}
17059function getExportMode(chunk, { exports: exportMode, name, format }) {
17060 const exportKeys = chunk.getExportNames();
17061 if (exportMode === 'default') {
17062 if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
17063 badExports('default', exportKeys);
17064 }
17065 }
17066 else if (exportMode === 'none' && exportKeys.length) {
17067 badExports('none', exportKeys);
17068 }
17069 if (!exportMode || exportMode === 'auto') {
17070 if (exportKeys.length === 0) {
17071 exportMode = 'none';
17072 }
17073 else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
17074 exportMode = 'default';
17075 }
17076 else {
17077 if (chunk.facadeModule !== null &&
17078 chunk.facadeModule.isEntryPoint &&
17079 format !== 'es' &&
17080 exportKeys.indexOf('default') !== -1) {
17081 chunk.graph.warn({
17082 code: 'MIXED_EXPORTS',
17083 message: `Using named and default exports together. Consumers of your bundle will have to use ${name ||
17084 'bundle'}['default'] to access the default export, which may not be what you want. Use \`output.exports: 'named'\` to disable this warning`,
17085 url: `https://rollupjs.org/guide/en/#output-exports`
17086 });
17087 }
17088 exportMode = 'named';
17089 }
17090 }
17091 if (!/(?:default|named|none)/.test(exportMode)) {
17092 error({
17093 code: 'INVALID_EXPORT_OPTION',
17094 message: `output.exports must be 'default', 'named', 'none', 'auto', or left unspecified (defaults to 'auto')`,
17095 url: `https://rollupjs.org/guide/en/#output-exports`
17096 });
17097 }
17098 return exportMode;
17099}
17100
17101function checkOutputOptions(options) {
17102 if (options.format === 'es6') {
17103 error(errDeprecation({
17104 message: 'The "es6" output format is deprecated – use "esm" instead',
17105 url: `https://rollupjs.org/guide/en/#output-format`
17106 }));
17107 }
17108 if (['amd', 'cjs', 'system', 'es', 'iife', 'umd'].indexOf(options.format) < 0) {
17109 error({
17110 message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "esm", "iife" or "umd".`,
17111 url: `https://rollupjs.org/guide/en/#output-format`
17112 });
17113 }
17114}
17115function getAbsoluteEntryModulePaths(chunks) {
17116 const absoluteEntryModulePaths = [];
17117 for (const chunk of chunks) {
17118 for (const entryModule of chunk.entryModules) {
17119 if (index.isAbsolute(entryModule.id)) {
17120 absoluteEntryModulePaths.push(entryModule.id);
17121 }
17122 }
17123 }
17124 return absoluteEntryModulePaths;
17125}
17126const throwAsyncGenerateError = {
17127 get() {
17128 throw new Error(`bundle.generate(...) now returns a Promise instead of a { code, map } object`);
17129 }
17130};
17131function applyOptionHook(inputOptions, plugin) {
17132 if (plugin.options)
17133 return plugin.options.call({ meta: { rollupVersion: index.version } }, inputOptions) || inputOptions;
17134 return inputOptions;
17135}
17136function ensureArray(items) {
17137 if (Array.isArray(items)) {
17138 return items.filter(Boolean);
17139 }
17140 if (items) {
17141 return [items];
17142 }
17143 return [];
17144}
17145function getInputOptions(rawInputOptions) {
17146 if (!rawInputOptions) {
17147 throw new Error('You must supply an options object to rollup');
17148 }
17149 let { inputOptions, optionError } = index.mergeOptions({
17150 config: rawInputOptions
17151 });
17152 if (optionError)
17153 inputOptions.onwarn({ message: optionError, code: 'UNKNOWN_OPTION' });
17154 inputOptions = ensureArray(inputOptions.plugins).reduce(applyOptionHook, inputOptions);
17155 inputOptions.plugins = ensureArray(inputOptions.plugins);
17156 for (let pluginIndex = 0; pluginIndex < inputOptions.plugins.length; pluginIndex++) {
17157 const plugin = inputOptions.plugins[pluginIndex];
17158 if (!plugin.name) {
17159 plugin.name = `${ANONYMOUS_PLUGIN_PREFIX}${pluginIndex + 1}`;
17160 }
17161 }
17162 if (inputOptions.inlineDynamicImports) {
17163 if (inputOptions.preserveModules)
17164 error({
17165 code: 'INVALID_OPTION',
17166 message: `"preserveModules" does not support the "inlineDynamicImports" option.`
17167 });
17168 if (inputOptions.manualChunks)
17169 error({
17170 code: 'INVALID_OPTION',
17171 message: '"manualChunks" option is not supported for "inlineDynamicImports".'
17172 });
17173 if (inputOptions.experimentalOptimizeChunks)
17174 error({
17175 code: 'INVALID_OPTION',
17176 message: '"experimentalOptimizeChunks" option is not supported for "inlineDynamicImports".'
17177 });
17178 if ((inputOptions.input instanceof Array && inputOptions.input.length > 1) ||
17179 (typeof inputOptions.input === 'object' && Object.keys(inputOptions.input).length > 1))
17180 error({
17181 code: 'INVALID_OPTION',
17182 message: 'Multiple inputs are not supported for "inlineDynamicImports".'
17183 });
17184 }
17185 else if (inputOptions.preserveModules) {
17186 if (inputOptions.manualChunks)
17187 error({
17188 code: 'INVALID_OPTION',
17189 message: '"preserveModules" does not support the "manualChunks" option.'
17190 });
17191 if (inputOptions.experimentalOptimizeChunks)
17192 error({
17193 code: 'INVALID_OPTION',
17194 message: '"preserveModules" does not support the "experimentalOptimizeChunks" option.'
17195 });
17196 }
17197 return inputOptions;
17198}
17199let curWatcher;
17200function setWatcher(watcher) {
17201 curWatcher = watcher;
17202}
17203function assignChunksToBundle(chunks, outputBundle) {
17204 for (let i = 0; i < chunks.length; i++) {
17205 const chunk = chunks[i];
17206 const facadeModule = chunk.facadeModule;
17207 outputBundle[chunk.id] = {
17208 code: undefined,
17209 dynamicImports: chunk.getDynamicImportIds(),
17210 exports: chunk.getExportNames(),
17211 facadeModuleId: facadeModule && facadeModule.id,
17212 fileName: chunk.id,
17213 imports: chunk.getImportIds(),
17214 isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0,
17215 isEntry: facadeModule !== null && facadeModule.isEntryPoint,
17216 map: undefined,
17217 modules: chunk.renderedModules,
17218 get name() {
17219 return chunk.getChunkName();
17220 }
17221 };
17222 }
17223 return outputBundle;
17224}
17225function rollup(rawInputOptions) {
17226 try {
17227 const inputOptions = getInputOptions(rawInputOptions);
17228 initialiseTimers(inputOptions);
17229 const graph = new Graph(inputOptions, curWatcher);
17230 curWatcher = undefined;
17231 // remove the cache option from the memory after graph creation (cache is not used anymore)
17232 const useCache = rawInputOptions.cache !== false;
17233 delete inputOptions.cache;
17234 delete rawInputOptions.cache;
17235 timeStart('BUILD', 1);
17236 return graph.pluginDriver
17237 .hookParallel('buildStart', [inputOptions])
17238 .then(() => graph.build(inputOptions.input, inputOptions.manualChunks, inputOptions.inlineDynamicImports))
17239 .then(chunks => graph.pluginDriver.hookParallel('buildEnd', []).then(() => chunks), err => graph.pluginDriver.hookParallel('buildEnd', [err]).then(() => {
17240 throw err;
17241 }))
17242 .then(chunks => {
17243 timeEnd('BUILD', 1);
17244 // ensure we only do one optimization pass per build
17245 let optimized = false;
17246 function getOutputOptions(rawOutputOptions) {
17247 return normalizeOutputOptions(inputOptions, rawOutputOptions, chunks.length > 1, graph.pluginDriver);
17248 }
17249 function generate(outputOptions, isWrite) {
17250 return __awaiter(this, void 0, void 0, function* () {
17251 timeStart('GENERATE', 1);
17252 const assetFileNames = outputOptions.assetFileNames || 'assets/[name]-[hash][extname]';
17253 const outputBundleWithPlaceholders = Object.create(null);
17254 let outputBundle;
17255 const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
17256 graph.pluginDriver.startOutput(outputBundleWithPlaceholders, assetFileNames);
17257 try {
17258 yield graph.pluginDriver.hookParallel('renderStart', []);
17259 const addons = yield createAddons(graph, outputOptions);
17260 for (const chunk of chunks) {
17261 if (!inputOptions.preserveModules)
17262 chunk.generateInternalExports(outputOptions);
17263 if (chunk.facadeModule && chunk.facadeModule.isEntryPoint)
17264 chunk.exportMode = getExportMode(chunk, outputOptions);
17265 }
17266 for (const chunk of chunks) {
17267 chunk.preRender(outputOptions, inputBase);
17268 }
17269 if (!optimized && inputOptions.experimentalOptimizeChunks) {
17270 optimizeChunks(chunks, outputOptions, inputOptions.chunkGroupingSize, inputBase);
17271 optimized = true;
17272 }
17273 assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, outputBundleWithPlaceholders);
17274 outputBundle = assignChunksToBundle(chunks, outputBundleWithPlaceholders);
17275 yield Promise.all(chunks.map(chunk => {
17276 const outputChunk = outputBundleWithPlaceholders[chunk.id];
17277 return chunk.render(outputOptions, addons, outputChunk).then(rendered => {
17278 outputChunk.code = rendered.code;
17279 outputChunk.map = rendered.map;
17280 return graph.pluginDriver.hookParallel('ongenerate', [
17281 Object.assign({ bundle: outputChunk }, outputOptions),
17282 outputChunk
17283 ]);
17284 });
17285 }));
17286 }
17287 catch (error) {
17288 yield graph.pluginDriver.hookParallel('renderError', [error]);
17289 throw error;
17290 }
17291 yield graph.pluginDriver.hookSeq('generateBundle', [
17292 outputOptions,
17293 outputBundle,
17294 isWrite
17295 ]);
17296 graph.pluginDriver.finaliseAssets();
17297 timeEnd('GENERATE', 1);
17298 return outputBundle;
17299 });
17300 }
17301 const cache = useCache ? graph.getCache() : undefined;
17302 const result = {
17303 cache: cache,
17304 generate: ((rawOutputOptions) => {
17305 const promise = generate(getOutputOptions(rawOutputOptions), false).then(result => createOutput(result));
17306 Object.defineProperty(promise, 'code', throwAsyncGenerateError);
17307 Object.defineProperty(promise, 'map', throwAsyncGenerateError);
17308 return promise;
17309 }),
17310 watchFiles: Object.keys(graph.watchFiles),
17311 write: ((rawOutputOptions) => {
17312 const outputOptions = getOutputOptions(rawOutputOptions);
17313 if (!outputOptions.dir && !outputOptions.file) {
17314 error({
17315 code: 'MISSING_OPTION',
17316 message: 'You must specify "output.file" or "output.dir" for the build.'
17317 });
17318 }
17319 return generate(outputOptions, true).then(bundle => {
17320 let chunkCnt = 0;
17321 for (const fileName of Object.keys(bundle)) {
17322 const file = bundle[fileName];
17323 if (file.isAsset)
17324 continue;
17325 chunkCnt++;
17326 if (chunkCnt > 1)
17327 break;
17328 }
17329 if (chunkCnt > 1) {
17330 if (outputOptions.sourcemapFile)
17331 error({
17332 code: 'INVALID_OPTION',
17333 message: '"output.sourcemapFile" is only supported for single-file builds.'
17334 });
17335 if (typeof outputOptions.file === 'string')
17336 error({
17337 code: 'INVALID_OPTION',
17338 message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file".' +
17339 (typeof inputOptions.input !== 'string' ||
17340 inputOptions.inlineDynamicImports === true
17341 ? ''
17342 : ' To inline dynamic imports, set the "inlineDynamicImports" option.')
17343 });
17344 }
17345 return Promise.all(Object.keys(bundle).map(chunkId => writeOutputFile(graph, result, bundle[chunkId], outputOptions)))
17346 .then(() => graph.pluginDriver.hookParallel('writeBundle', [bundle]))
17347 .then(() => createOutput(bundle));
17348 });
17349 })
17350 };
17351 if (inputOptions.perf === true)
17352 result.getTimings = getTimings;
17353 return result;
17354 });
17355 }
17356 catch (err) {
17357 return Promise.reject(err);
17358 }
17359}
17360var SortingFileType;
17361(function (SortingFileType) {
17362 SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
17363 SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
17364 SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
17365})(SortingFileType || (SortingFileType = {}));
17366function getSortingFileType(file) {
17367 if (file.isAsset) {
17368 return SortingFileType.ASSET;
17369 }
17370 if (file.isEntry) {
17371 return SortingFileType.ENTRY_CHUNK;
17372 }
17373 return SortingFileType.SECONDARY_CHUNK;
17374}
17375function createOutput(outputBundle) {
17376 return {
17377 output: Object.keys(outputBundle)
17378 .map(fileName => outputBundle[fileName])
17379 .filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
17380 const fileTypeA = getSortingFileType(outputFileA);
17381 const fileTypeB = getSortingFileType(outputFileB);
17382 if (fileTypeA === fileTypeB)
17383 return 0;
17384 return fileTypeA < fileTypeB ? -1 : 1;
17385 })
17386 };
17387}
17388function isOutputAsset(file) {
17389 return file.isAsset === true;
17390}
17391function writeOutputFile(graph, build, outputFile, outputOptions) {
17392 const fileName = path.resolve(outputOptions.dir || path.dirname(outputOptions.file), outputFile.fileName);
17393 let writeSourceMapPromise;
17394 let source;
17395 if (isOutputAsset(outputFile)) {
17396 source = outputFile.source;
17397 }
17398 else {
17399 source = outputFile.code;
17400 if (outputOptions.sourcemap && outputFile.map) {
17401 let url;
17402 if (outputOptions.sourcemap === 'inline') {
17403 url = outputFile.map.toUrl();
17404 }
17405 else {
17406 url = `${path.basename(outputFile.fileName)}.map`;
17407 writeSourceMapPromise = writeFile(`${fileName}.map`, outputFile.map.toString());
17408 }
17409 source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
17410 }
17411 }
17412 return writeFile(fileName, source)
17413 .then(() => writeSourceMapPromise)
17414 .then(() => !isOutputAsset(outputFile) &&
17415 graph.pluginDriver.hookSeq('onwrite', [
17416 Object.assign({ bundle: build }, outputOptions),
17417 outputFile
17418 ]))
17419 .then(() => { });
17420}
17421function normalizeOutputOptions(inputOptions, rawOutputOptions, hasMultipleChunks, pluginDriver) {
17422 if (!rawOutputOptions) {
17423 throw new Error('You must supply an options object');
17424 }
17425 const mergedOptions = index.mergeOptions({
17426 config: {
17427 output: Object.assign({}, rawOutputOptions, rawOutputOptions.output, inputOptions.output)
17428 }
17429 });
17430 if (mergedOptions.optionError)
17431 throw new Error(mergedOptions.optionError);
17432 // now outputOptions is an array, but rollup.rollup API doesn't support arrays
17433 const mergedOutputOptions = mergedOptions.outputOptions[0];
17434 const outputOptionsReducer = (outputOptions, result) => result || outputOptions;
17435 const outputOptions = pluginDriver.hookReduceArg0Sync('outputOptions', [mergedOutputOptions], outputOptionsReducer, pluginContext => {
17436 const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
17437 return Object.assign({}, pluginContext, { emitFile: emitError, setAssetSource: emitError });
17438 });
17439 checkOutputOptions(outputOptions);
17440 if (typeof outputOptions.file === 'string') {
17441 if (typeof outputOptions.dir === 'string')
17442 error({
17443 code: 'INVALID_OPTION',
17444 message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
17445 });
17446 if (inputOptions.preserveModules) {
17447 error({
17448 code: 'INVALID_OPTION',
17449 message: 'You must set "output.dir" instead of "output.file" when using the "preserveModules" option.'
17450 });
17451 }
17452 if (typeof inputOptions.input === 'object' && !Array.isArray(inputOptions.input))
17453 error({
17454 code: 'INVALID_OPTION',
17455 message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
17456 });
17457 }
17458 if (hasMultipleChunks) {
17459 if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
17460 error({
17461 code: 'INVALID_OPTION',
17462 message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
17463 });
17464 if (typeof outputOptions.file === 'string')
17465 error({
17466 code: 'INVALID_OPTION',
17467 message: 'You must set "output.dir" instead of "output.file" when generating multiple chunks.'
17468 });
17469 }
17470 return outputOptions;
17471}
17472
17473var utils$1 = index.createCommonjsModule(function (module, exports) {
17474 exports.isInteger = num => {
17475 if (typeof num === 'number') {
17476 return Number.isInteger(num);
17477 }
17478 if (typeof num === 'string' && num.trim() !== '') {
17479 return Number.isInteger(Number(num));
17480 }
17481 return false;
17482 };
17483 /**
17484 * Find a node of the given type
17485 */
17486 exports.find = (node, type) => node.nodes.find(node => node.type === type);
17487 /**
17488 * Find a node of the given type
17489 */
17490 exports.exceedsLimit = (min, max, step = 1, limit) => {
17491 if (limit === false)
17492 return false;
17493 if (!exports.isInteger(min) || !exports.isInteger(max))
17494 return false;
17495 return ((Number(max) - Number(min)) / Number(step)) >= limit;
17496 };
17497 /**
17498 * Escape the given node with '\\' before node.value
17499 */
17500 exports.escapeNode = (block, n = 0, type) => {
17501 let node = block.nodes[n];
17502 if (!node)
17503 return;
17504 if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
17505 if (node.escaped !== true) {
17506 node.value = '\\' + node.value;
17507 node.escaped = true;
17508 }
17509 }
17510 };
17511 /**
17512 * Returns true if the given brace node should be enclosed in literal braces
17513 */
17514 exports.encloseBrace = node => {
17515 if (node.type !== 'brace')
17516 return false;
17517 if ((node.commas >> 0 + node.ranges >> 0) === 0) {
17518 node.invalid = true;
17519 return true;
17520 }
17521 return false;
17522 };
17523 /**
17524 * Returns true if a brace node is invalid.
17525 */
17526 exports.isInvalidBrace = block => {
17527 if (block.type !== 'brace')
17528 return false;
17529 if (block.invalid === true || block.dollar)
17530 return true;
17531 if ((block.commas >> 0 + block.ranges >> 0) === 0) {
17532 block.invalid = true;
17533 return true;
17534 }
17535 if (block.open !== true || block.close !== true) {
17536 block.invalid = true;
17537 return true;
17538 }
17539 return false;
17540 };
17541 /**
17542 * Returns true if a node is an open or close node
17543 */
17544 exports.isOpenOrClose = node => {
17545 if (node.type === 'open' || node.type === 'close') {
17546 return true;
17547 }
17548 return node.open === true || node.close === true;
17549 };
17550 /**
17551 * Reduce an array of text nodes.
17552 */
17553 exports.reduce = nodes => nodes.reduce((acc, node) => {
17554 if (node.type === 'text')
17555 acc.push(node.value);
17556 if (node.type === 'range')
17557 node.type = 'text';
17558 return acc;
17559 }, []);
17560 /**
17561 * Flatten an array
17562 */
17563 exports.flatten = (...args) => {
17564 const result = [];
17565 const flat = arr => {
17566 for (let i = 0; i < arr.length; i++) {
17567 let ele = arr[i];
17568 Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
17569 }
17570 return result;
17571 };
17572 flat(args);
17573 return result;
17574 };
17575});
17576
17577var stringify = (ast, options = {}) => {
17578 let stringify = (node, parent = {}) => {
17579 let invalidBlock = options.escapeInvalid && utils$1.isInvalidBrace(parent);
17580 let invalidNode = node.invalid === true && options.escapeInvalid === true;
17581 let output = '';
17582 if (node.value) {
17583 if ((invalidBlock || invalidNode) && utils$1.isOpenOrClose(node)) {
17584 return '\\' + node.value;
17585 }
17586 return node.value;
17587 }
17588 if (node.value) {
17589 return node.value;
17590 }
17591 if (node.nodes) {
17592 for (let child of node.nodes) {
17593 output += stringify(child);
17594 }
17595 }
17596 return output;
17597 };
17598 return stringify(ast);
17599};
17600
17601/*!
17602 * is-number <https://github.com/jonschlinkert/is-number>
17603 *
17604 * Copyright (c) 2014-present, Jon Schlinkert.
17605 * Released under the MIT License.
17606 */
17607var isNumber = function (num) {
17608 if (typeof num === 'number') {
17609 return num - num === 0;
17610 }
17611 if (typeof num === 'string' && num.trim() !== '') {
17612 return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
17613 }
17614 return false;
17615};
17616
17617const toRegexRange = (min, max, options) => {
17618 if (isNumber(min) === false) {
17619 throw new TypeError('toRegexRange: expected the first argument to be a number');
17620 }
17621 if (max === void 0 || min === max) {
17622 return String(min);
17623 }
17624 if (isNumber(max) === false) {
17625 throw new TypeError('toRegexRange: expected the second argument to be a number.');
17626 }
17627 let opts = Object.assign({ relaxZeros: true }, options);
17628 if (typeof opts.strictZeros === 'boolean') {
17629 opts.relaxZeros = opts.strictZeros === false;
17630 }
17631 let relax = String(opts.relaxZeros);
17632 let shorthand = String(opts.shorthand);
17633 let capture = String(opts.capture);
17634 let wrap = String(opts.wrap);
17635 let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
17636 if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
17637 return toRegexRange.cache[cacheKey].result;
17638 }
17639 let a = Math.min(min, max);
17640 let b = Math.max(min, max);
17641 if (Math.abs(a - b) === 1) {
17642 let result = min + '|' + max;
17643 if (opts.capture) {
17644 return `(${result})`;
17645 }
17646 if (opts.wrap === false) {
17647 return result;
17648 }
17649 return `(?:${result})`;
17650 }
17651 let isPadded = hasPadding(min) || hasPadding(max);
17652 let state = { min, max, a, b };
17653 let positives = [];
17654 let negatives = [];
17655 if (isPadded) {
17656 state.isPadded = isPadded;
17657 state.maxLen = String(state.max).length;
17658 }
17659 if (a < 0) {
17660 let newMin = b < 0 ? Math.abs(b) : 1;
17661 negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
17662 a = state.a = 0;
17663 }
17664 if (b >= 0) {
17665 positives = splitToPatterns(a, b, state, opts);
17666 }
17667 state.negatives = negatives;
17668 state.positives = positives;
17669 state.result = collatePatterns(negatives, positives);
17670 if (opts.capture === true) {
17671 state.result = `(${state.result})`;
17672 }
17673 else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
17674 state.result = `(?:${state.result})`;
17675 }
17676 toRegexRange.cache[cacheKey] = state;
17677 return state.result;
17678};
17679function collatePatterns(neg, pos, options) {
17680 let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
17681 let onlyPositive = filterPatterns(pos, neg, '', false) || [];
17682 let intersected = filterPatterns(neg, pos, '-?', true) || [];
17683 let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
17684 return subpatterns.join('|');
17685}
17686function splitToRanges(min, max) {
17687 let nines = 1;
17688 let zeros = 1;
17689 let stop = countNines(min, nines);
17690 let stops = new Set([max]);
17691 while (min <= stop && stop <= max) {
17692 stops.add(stop);
17693 nines += 1;
17694 stop = countNines(min, nines);
17695 }
17696 stop = countZeros(max + 1, zeros) - 1;
17697 while (min < stop && stop <= max) {
17698 stops.add(stop);
17699 zeros += 1;
17700 stop = countZeros(max + 1, zeros) - 1;
17701 }
17702 stops = [...stops];
17703 stops.sort(compare);
17704 return stops;
17705}
17706/**
17707 * Convert a range to a regex pattern
17708 * @param {Number} `start`
17709 * @param {Number} `stop`
17710 * @return {String}
17711 */
17712function rangeToPattern(start, stop, options) {
17713 if (start === stop) {
17714 return { pattern: start, count: [], digits: 0 };
17715 }
17716 let zipped = zip(start, stop);
17717 let digits = zipped.length;
17718 let pattern = '';
17719 let count = 0;
17720 for (let i = 0; i < digits; i++) {
17721 let [startDigit, stopDigit] = zipped[i];
17722 if (startDigit === stopDigit) {
17723 pattern += startDigit;
17724 }
17725 else if (startDigit !== '0' || stopDigit !== '9') {
17726 pattern += toCharacterClass(startDigit, stopDigit);
17727 }
17728 else {
17729 count++;
17730 }
17731 }
17732 if (count) {
17733 pattern += options.shorthand === true ? '\\d' : '[0-9]';
17734 }
17735 return { pattern, count: [count], digits };
17736}
17737function splitToPatterns(min, max, tok, options) {
17738 let ranges = splitToRanges(min, max);
17739 let tokens = [];
17740 let start = min;
17741 let prev;
17742 for (let i = 0; i < ranges.length; i++) {
17743 let max = ranges[i];
17744 let obj = rangeToPattern(String(start), String(max), options);
17745 let zeros = '';
17746 if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
17747 if (prev.count.length > 1) {
17748 prev.count.pop();
17749 }
17750 prev.count.push(obj.count[0]);
17751 prev.string = prev.pattern + toQuantifier(prev.count);
17752 start = max + 1;
17753 continue;
17754 }
17755 if (tok.isPadded) {
17756 zeros = padZeros(max, tok, options);
17757 }
17758 obj.string = zeros + obj.pattern + toQuantifier(obj.count);
17759 tokens.push(obj);
17760 start = max + 1;
17761 prev = obj;
17762 }
17763 return tokens;
17764}
17765function filterPatterns(arr, comparison, prefix, intersection, options) {
17766 let result = [];
17767 for (let ele of arr) {
17768 let { string } = ele;
17769 // only push if _both_ are negative...
17770 if (!intersection && !contains(comparison, 'string', string)) {
17771 result.push(prefix + string);
17772 }
17773 // or _both_ are positive
17774 if (intersection && contains(comparison, 'string', string)) {
17775 result.push(prefix + string);
17776 }
17777 }
17778 return result;
17779}
17780/**
17781 * Zip strings
17782 */
17783function zip(a, b) {
17784 let arr = [];
17785 for (let i = 0; i < a.length; i++)
17786 arr.push([a[i], b[i]]);
17787 return arr;
17788}
17789function compare(a, b) {
17790 return a > b ? 1 : b > a ? -1 : 0;
17791}
17792function contains(arr, key, val) {
17793 return arr.some(ele => ele[key] === val);
17794}
17795function countNines(min, len) {
17796 return Number(String(min).slice(0, -len) + '9'.repeat(len));
17797}
17798function countZeros(integer, zeros) {
17799 return integer - (integer % Math.pow(10, zeros));
17800}
17801function toQuantifier(digits) {
17802 let [start = 0, stop = ''] = digits;
17803 if (stop || start > 1) {
17804 return `{${start + (stop ? ',' + stop : '')}}`;
17805 }
17806 return '';
17807}
17808function toCharacterClass(a, b, options) {
17809 return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
17810}
17811function hasPadding(str) {
17812 return /^-?(0+)\d/.test(str);
17813}
17814function padZeros(value, tok, options) {
17815 if (!tok.isPadded) {
17816 return value;
17817 }
17818 let diff = Math.abs(tok.maxLen - String(value).length);
17819 let relax = options.relaxZeros !== false;
17820 switch (diff) {
17821 case 0:
17822 return '';
17823 case 1:
17824 return relax ? '0?' : '0';
17825 case 2:
17826 return relax ? '0{0,2}' : '00';
17827 default: {
17828 return relax ? `0{0,${diff}}` : `0{${diff}}`;
17829 }
17830 }
17831}
17832/**
17833 * Cache
17834 */
17835toRegexRange.cache = {};
17836toRegexRange.clearCache = () => (toRegexRange.cache = {});
17837/**
17838 * Expose `toRegexRange`
17839 */
17840var toRegexRange_1 = toRegexRange;
17841
17842const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
17843const transform$1 = toNumber => {
17844 return value => toNumber === true ? Number(value) : String(value);
17845};
17846const isValidValue = value => {
17847 return typeof value === 'number' || (typeof value === 'string' && value !== '');
17848};
17849const isNumber$1 = num => Number.isInteger(+num);
17850const zeros = input => {
17851 let value = `${input}`;
17852 let index = -1;
17853 if (value[0] === '-')
17854 value = value.slice(1);
17855 if (value === '0')
17856 return false;
17857 while (value[++index] === '0')
17858 ;
17859 return index > 0;
17860};
17861const stringify$1 = (start, end, options) => {
17862 if (typeof start === 'string' || typeof end === 'string') {
17863 return true;
17864 }
17865 return options.stringify === true;
17866};
17867const pad = (input, maxLength, toNumber) => {
17868 if (maxLength > 0) {
17869 let dash = input[0] === '-' ? '-' : '';
17870 if (dash)
17871 input = input.slice(1);
17872 input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
17873 }
17874 if (toNumber === false) {
17875 return String(input);
17876 }
17877 return input;
17878};
17879const toMaxLen = (input, maxLength) => {
17880 let negative = input[0] === '-' ? '-' : '';
17881 if (negative) {
17882 input = input.slice(1);
17883 maxLength--;
17884 }
17885 while (input.length < maxLength)
17886 input = '0' + input;
17887 return negative ? ('-' + input) : input;
17888};
17889const toSequence = (parts, options) => {
17890 parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
17891 parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
17892 let prefix = options.capture ? '' : '?:';
17893 let positives = '';
17894 let negatives = '';
17895 let result;
17896 if (parts.positives.length) {
17897 positives = parts.positives.join('|');
17898 }
17899 if (parts.negatives.length) {
17900 negatives = `-(${prefix}${parts.negatives.join('|')})`;
17901 }
17902 if (positives && negatives) {
17903 result = `${positives}|${negatives}`;
17904 }
17905 else {
17906 result = positives || negatives;
17907 }
17908 if (options.wrap) {
17909 return `(${prefix}${result})`;
17910 }
17911 return result;
17912};
17913const toRange = (a, b, isNumbers, options) => {
17914 if (isNumbers) {
17915 return toRegexRange_1(a, b, Object.assign({ wrap: false }, options));
17916 }
17917 let start = String.fromCharCode(a);
17918 if (a === b)
17919 return start;
17920 let stop = String.fromCharCode(b);
17921 return `[${start}-${stop}]`;
17922};
17923const toRegex = (start, end, options) => {
17924 if (Array.isArray(start)) {
17925 let wrap = options.wrap === true;
17926 let prefix = options.capture ? '' : '?:';
17927 return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
17928 }
17929 return toRegexRange_1(start, end, options);
17930};
17931const rangeError = (...args) => {
17932 return new RangeError('Invalid range arguments: ' + util.inspect(...args));
17933};
17934const invalidRange = (start, end, options) => {
17935 if (options.strictRanges === true)
17936 throw rangeError([start, end]);
17937 return [];
17938};
17939const invalidStep = (step, options) => {
17940 if (options.strictRanges === true) {
17941 throw new TypeError(`Expected step "${step}" to be a number`);
17942 }
17943 return [];
17944};
17945const fillNumbers = (start, end, step = 1, options = {}) => {
17946 let a = Number(start);
17947 let b = Number(end);
17948 if (!Number.isInteger(a) || !Number.isInteger(b)) {
17949 if (options.strictRanges === true)
17950 throw rangeError([start, end]);
17951 return [];
17952 }
17953 // fix negative zero
17954 if (a === 0)
17955 a = 0;
17956 if (b === 0)
17957 b = 0;
17958 let descending = a > b;
17959 let startString = String(start);
17960 let endString = String(end);
17961 let stepString = String(step);
17962 step = Math.max(Math.abs(step), 1);
17963 let padded = zeros(startString) || zeros(endString) || zeros(stepString);
17964 let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
17965 let toNumber = padded === false && stringify$1(start, end, options) === false;
17966 let format = options.transform || transform$1(toNumber);
17967 if (options.toRegex && step === 1) {
17968 return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
17969 }
17970 let parts = { negatives: [], positives: [] };
17971 let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
17972 let range = [];
17973 let index = 0;
17974 while (descending ? a >= b : a <= b) {
17975 if (options.toRegex === true && step > 1) {
17976 push(a);
17977 }
17978 else {
17979 range.push(pad(format(a, index), maxLen, toNumber));
17980 }
17981 a = descending ? a - step : a + step;
17982 index++;
17983 }
17984 if (options.toRegex === true) {
17985 return step > 1
17986 ? toSequence(parts, options)
17987 : toRegex(range, null, Object.assign({ wrap: false }, options));
17988 }
17989 return range;
17990};
17991const fillLetters = (start, end, step = 1, options = {}) => {
17992 if ((!isNumber$1(start) && start.length > 1) || (!isNumber$1(end) && end.length > 1)) {
17993 return invalidRange(start, end, options);
17994 }
17995 let format = options.transform || (val => String.fromCharCode(val));
17996 let a = `${start}`.charCodeAt(0);
17997 let b = `${end}`.charCodeAt(0);
17998 let descending = a > b;
17999 let min = Math.min(a, b);
18000 let max = Math.max(a, b);
18001 if (options.toRegex && step === 1) {
18002 return toRange(min, max, false, options);
18003 }
18004 let range = [];
18005 let index = 0;
18006 while (descending ? a >= b : a <= b) {
18007 range.push(format(a, index));
18008 a = descending ? a - step : a + step;
18009 index++;
18010 }
18011 if (options.toRegex === true) {
18012 return toRegex(range, null, { wrap: false, options });
18013 }
18014 return range;
18015};
18016const fill = (start, end, step, options = {}) => {
18017 if (end == null && isValidValue(start)) {
18018 return [start];
18019 }
18020 if (!isValidValue(start) || !isValidValue(end)) {
18021 return invalidRange(start, end, options);
18022 }
18023 if (typeof step === 'function') {
18024 return fill(start, end, 1, { transform: step });
18025 }
18026 if (isObject$1(step)) {
18027 return fill(start, end, 0, step);
18028 }
18029 let opts = Object.assign({}, options);
18030 if (opts.capture === true)
18031 opts.wrap = true;
18032 step = step || opts.step || 1;
18033 if (!isNumber$1(step)) {
18034 if (step != null && !isObject$1(step))
18035 return invalidStep(step, opts);
18036 return fill(start, end, 1, step);
18037 }
18038 if (isNumber$1(start) && isNumber$1(end)) {
18039 return fillNumbers(start, end, step, opts);
18040 }
18041 return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
18042};
18043var fillRange = fill;
18044
18045const compile = (ast, options = {}) => {
18046 let walk = (node, parent = {}) => {
18047 let invalidBlock = utils$1.isInvalidBrace(parent);
18048 let invalidNode = node.invalid === true && options.escapeInvalid === true;
18049 let invalid = invalidBlock === true || invalidNode === true;
18050 let prefix = options.escapeInvalid === true ? '\\' : '';
18051 let output = '';
18052 if (node.isOpen === true) {
18053 return prefix + node.value;
18054 }
18055 if (node.isClose === true) {
18056 return prefix + node.value;
18057 }
18058 if (node.type === 'open') {
18059 return invalid ? (prefix + node.value) : '(';
18060 }
18061 if (node.type === 'close') {
18062 return invalid ? (prefix + node.value) : ')';
18063 }
18064 if (node.type === 'comma') {
18065 return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
18066 }
18067 if (node.value) {
18068 return node.value;
18069 }
18070 if (node.nodes && node.ranges > 0) {
18071 let args = utils$1.reduce(node.nodes);
18072 let range = fillRange(...args, Object.assign({}, options, { wrap: false, toRegex: true }));
18073 if (range.length !== 0) {
18074 return args.length > 1 && range.length > 1 ? `(${range})` : range;
18075 }
18076 }
18077 if (node.nodes) {
18078 for (let child of node.nodes) {
18079 output += walk(child, node);
18080 }
18081 }
18082 return output;
18083 };
18084 return walk(ast);
18085};
18086var compile_1 = compile;
18087
18088const append = (queue = '', stash = '', enclose = false) => {
18089 let result = [];
18090 queue = [].concat(queue);
18091 stash = [].concat(stash);
18092 if (!stash.length)
18093 return queue;
18094 if (!queue.length) {
18095 return enclose ? utils$1.flatten(stash).map(ele => `{${ele}}`) : stash;
18096 }
18097 for (let item of queue) {
18098 if (Array.isArray(item)) {
18099 for (let value of item) {
18100 result.push(append(value, stash, enclose));
18101 }
18102 }
18103 else {
18104 for (let ele of stash) {
18105 if (enclose === true && typeof ele === 'string')
18106 ele = `{${ele}}`;
18107 result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
18108 }
18109 }
18110 }
18111 return utils$1.flatten(result);
18112};
18113const expand = (ast, options = {}) => {
18114 let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
18115 let walk = (node, parent = {}) => {
18116 node.queue = [];
18117 let p = parent;
18118 let q = parent.queue;
18119 while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
18120 p = p.parent;
18121 q = p.queue;
18122 }
18123 if (node.invalid || node.dollar) {
18124 q.push(append(q.pop(), stringify(node, options)));
18125 return;
18126 }
18127 if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
18128 q.push(append(q.pop(), ['{}']));
18129 return;
18130 }
18131 if (node.nodes && node.ranges > 0) {
18132 let args = utils$1.reduce(node.nodes);
18133 if (utils$1.exceedsLimit(...args, options.step, rangeLimit)) {
18134 throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
18135 }
18136 let range = fillRange(...args, options);
18137 if (range.length === 0) {
18138 range = stringify(node, options);
18139 }
18140 q.push(append(q.pop(), range));
18141 node.nodes = [];
18142 return;
18143 }
18144 let enclose = utils$1.encloseBrace(node);
18145 let queue = node.queue;
18146 let block = node;
18147 while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
18148 block = block.parent;
18149 queue = block.queue;
18150 }
18151 for (let i = 0; i < node.nodes.length; i++) {
18152 let child = node.nodes[i];
18153 if (child.type === 'comma' && node.type === 'brace') {
18154 if (i === 1)
18155 queue.push('');
18156 queue.push('');
18157 continue;
18158 }
18159 if (child.type === 'close') {
18160 q.push(append(q.pop(), queue, enclose));
18161 continue;
18162 }
18163 if (child.value && child.type !== 'open') {
18164 queue.push(append(queue.pop(), child.value));
18165 continue;
18166 }
18167 if (child.nodes) {
18168 walk(child, node);
18169 }
18170 }
18171 return queue;
18172 };
18173 return utils$1.flatten(walk(ast));
18174};
18175var expand_1 = expand;
18176
18177var constants = {
18178 MAX_LENGTH: 1024 * 64,
18179 // Digits
18180 CHAR_0: '0',
18181 CHAR_9: '9',
18182 // Alphabet chars.
18183 CHAR_UPPERCASE_A: 'A',
18184 CHAR_LOWERCASE_A: 'a',
18185 CHAR_UPPERCASE_Z: 'Z',
18186 CHAR_LOWERCASE_Z: 'z',
18187 CHAR_LEFT_PARENTHESES: '(',
18188 CHAR_RIGHT_PARENTHESES: ')',
18189 CHAR_ASTERISK: '*',
18190 // Non-alphabetic chars.
18191 CHAR_AMPERSAND: '&',
18192 CHAR_AT: '@',
18193 CHAR_BACKSLASH: '\\',
18194 CHAR_BACKTICK: '`',
18195 CHAR_CARRIAGE_RETURN: '\r',
18196 CHAR_CIRCUMFLEX_ACCENT: '^',
18197 CHAR_COLON: ':',
18198 CHAR_COMMA: ',',
18199 CHAR_DOLLAR: '$',
18200 CHAR_DOT: '.',
18201 CHAR_DOUBLE_QUOTE: '"',
18202 CHAR_EQUAL: '=',
18203 CHAR_EXCLAMATION_MARK: '!',
18204 CHAR_FORM_FEED: '\f',
18205 CHAR_FORWARD_SLASH: '/',
18206 CHAR_HASH: '#',
18207 CHAR_HYPHEN_MINUS: '-',
18208 CHAR_LEFT_ANGLE_BRACKET: '<',
18209 CHAR_LEFT_CURLY_BRACE: '{',
18210 CHAR_LEFT_SQUARE_BRACKET: '[',
18211 CHAR_LINE_FEED: '\n',
18212 CHAR_NO_BREAK_SPACE: '\u00A0',
18213 CHAR_PERCENT: '%',
18214 CHAR_PLUS: '+',
18215 CHAR_QUESTION_MARK: '?',
18216 CHAR_RIGHT_ANGLE_BRACKET: '>',
18217 CHAR_RIGHT_CURLY_BRACE: '}',
18218 CHAR_RIGHT_SQUARE_BRACKET: ']',
18219 CHAR_SEMICOLON: ';',
18220 CHAR_SINGLE_QUOTE: '\'',
18221 CHAR_SPACE: ' ',
18222 CHAR_TAB: '\t',
18223 CHAR_UNDERSCORE: '_',
18224 CHAR_VERTICAL_LINE: '|',
18225 CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
18226};
18227
18228/**
18229 * Constants
18230 */
18231const { MAX_LENGTH, CHAR_BACKSLASH, /* \ */ CHAR_BACKTICK, /* ` */ CHAR_COMMA, /* , */ CHAR_DOT, /* . */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_LEFT_SQUARE_BRACKET, /* [ */ CHAR_RIGHT_SQUARE_BRACKET, /* ] */ CHAR_DOUBLE_QUOTE, /* " */ CHAR_SINGLE_QUOTE, /* ' */ CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = constants;
18232/**
18233 * parse
18234 */
18235const parse = (input, options = {}) => {
18236 if (typeof input !== 'string') {
18237 throw new TypeError('Expected a string');
18238 }
18239 let opts = options || {};
18240 let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
18241 if (input.length > max) {
18242 throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
18243 }
18244 let ast = { type: 'root', input, nodes: [] };
18245 let stack = [ast];
18246 let block = ast;
18247 let prev = ast;
18248 let brackets = 0;
18249 let length = input.length;
18250 let index = 0;
18251 let depth = 0;
18252 let value;
18253 /**
18254 * Helpers
18255 */
18256 const advance = () => input[index++];
18257 const push = node => {
18258 if (node.type === 'text' && prev.type === 'dot') {
18259 prev.type = 'text';
18260 }
18261 if (prev && prev.type === 'text' && node.type === 'text') {
18262 prev.value += node.value;
18263 return;
18264 }
18265 block.nodes.push(node);
18266 node.parent = block;
18267 node.prev = prev;
18268 prev = node;
18269 return node;
18270 };
18271 push({ type: 'bos' });
18272 while (index < length) {
18273 block = stack[stack.length - 1];
18274 value = advance();
18275 /**
18276 * Invalid chars
18277 */
18278 if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
18279 continue;
18280 }
18281 /**
18282 * Escaped chars
18283 */
18284 if (value === CHAR_BACKSLASH) {
18285 push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
18286 continue;
18287 }
18288 /**
18289 * Right square bracket (literal): ']'
18290 */
18291 if (value === CHAR_RIGHT_SQUARE_BRACKET) {
18292 push({ type: 'text', value: '\\' + value });
18293 continue;
18294 }
18295 /**
18296 * Left square bracket: '['
18297 */
18298 if (value === CHAR_LEFT_SQUARE_BRACKET) {
18299 brackets++;
18300 let next;
18301 while (index < length && (next = advance())) {
18302 value += next;
18303 if (next === CHAR_LEFT_SQUARE_BRACKET) {
18304 brackets++;
18305 continue;
18306 }
18307 if (next === CHAR_BACKSLASH) {
18308 value += advance();
18309 continue;
18310 }
18311 if (next === CHAR_RIGHT_SQUARE_BRACKET) {
18312 brackets--;
18313 if (brackets === 0) {
18314 break;
18315 }
18316 }
18317 }
18318 push({ type: 'text', value });
18319 continue;
18320 }
18321 /**
18322 * Parentheses
18323 */
18324 if (value === CHAR_LEFT_PARENTHESES) {
18325 block = push({ type: 'paren', nodes: [] });
18326 stack.push(block);
18327 push({ type: 'text', value });
18328 continue;
18329 }
18330 if (value === CHAR_RIGHT_PARENTHESES) {
18331 if (block.type !== 'paren') {
18332 push({ type: 'text', value });
18333 continue;
18334 }
18335 block = stack.pop();
18336 push({ type: 'text', value });
18337 block = stack[stack.length - 1];
18338 continue;
18339 }
18340 /**
18341 * Quotes: '|"|`
18342 */
18343 if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
18344 let open = value;
18345 let next;
18346 if (options.keepQuotes !== true) {
18347 value = '';
18348 }
18349 while (index < length && (next = advance())) {
18350 if (next === CHAR_BACKSLASH) {
18351 value += next + advance();
18352 continue;
18353 }
18354 if (next === open) {
18355 if (options.keepQuotes === true)
18356 value += next;
18357 break;
18358 }
18359 value += next;
18360 }
18361 push({ type: 'text', value });
18362 continue;
18363 }
18364 /**
18365 * Left curly brace: '{'
18366 */
18367 if (value === CHAR_LEFT_CURLY_BRACE) {
18368 depth++;
18369 let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
18370 let brace = {
18371 type: 'brace',
18372 open: true,
18373 close: false,
18374 dollar,
18375 depth,
18376 commas: 0,
18377 ranges: 0,
18378 nodes: []
18379 };
18380 block = push(brace);
18381 stack.push(block);
18382 push({ type: 'open', value });
18383 continue;
18384 }
18385 /**
18386 * Right curly brace: '}'
18387 */
18388 if (value === CHAR_RIGHT_CURLY_BRACE) {
18389 if (block.type !== 'brace') {
18390 push({ type: 'text', value });
18391 continue;
18392 }
18393 let type = 'close';
18394 block = stack.pop();
18395 block.close = true;
18396 push({ type, value });
18397 depth--;
18398 block = stack[stack.length - 1];
18399 continue;
18400 }
18401 /**
18402 * Comma: ','
18403 */
18404 if (value === CHAR_COMMA && depth > 0) {
18405 if (block.ranges > 0) {
18406 block.ranges = 0;
18407 let open = block.nodes.shift();
18408 block.nodes = [open, { type: 'text', value: stringify(block) }];
18409 }
18410 push({ type: 'comma', value });
18411 block.commas++;
18412 continue;
18413 }
18414 /**
18415 * Dot: '.'
18416 */
18417 if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
18418 let siblings = block.nodes;
18419 if (depth === 0 || siblings.length === 0) {
18420 push({ type: 'text', value });
18421 continue;
18422 }
18423 if (prev.type === 'dot') {
18424 block.range = [];
18425 prev.value += value;
18426 prev.type = 'range';
18427 if (block.nodes.length !== 3 && block.nodes.length !== 5) {
18428 block.invalid = true;
18429 block.ranges = 0;
18430 prev.type = 'text';
18431 continue;
18432 }
18433 block.ranges++;
18434 block.args = [];
18435 continue;
18436 }
18437 if (prev.type === 'range') {
18438 siblings.pop();
18439 let before = siblings[siblings.length - 1];
18440 before.value += prev.value + value;
18441 prev = before;
18442 block.ranges--;
18443 continue;
18444 }
18445 push({ type: 'dot', value });
18446 continue;
18447 }
18448 /**
18449 * Text
18450 */
18451 push({ type: 'text', value });
18452 }
18453 // Mark imbalanced braces and brackets as invalid
18454 do {
18455 block = stack.pop();
18456 if (block.type !== 'root') {
18457 block.nodes.forEach(node => {
18458 if (!node.nodes) {
18459 if (node.type === 'open')
18460 node.isOpen = true;
18461 if (node.type === 'close')
18462 node.isClose = true;
18463 if (!node.nodes)
18464 node.type = 'text';
18465 node.invalid = true;
18466 }
18467 });
18468 // get the location of the block on parent.nodes (block's siblings)
18469 let parent = stack[stack.length - 1];
18470 let index = parent.nodes.indexOf(block);
18471 // replace the (invalid) block with it's nodes
18472 parent.nodes.splice(index, 1, ...block.nodes);
18473 }
18474 } while (stack.length > 0);
18475 push({ type: 'eos' });
18476 return ast;
18477};
18478var parse_1 = parse;
18479
18480/**
18481 * Expand the given pattern or create a regex-compatible string.
18482 *
18483 * ```js
18484 * const braces = require('braces');
18485 * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
18486 * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
18487 * ```
18488 * @param {String} `str`
18489 * @param {Object} `options`
18490 * @return {String}
18491 * @api public
18492 */
18493const braces = (input, options = {}) => {
18494 let output = [];
18495 if (Array.isArray(input)) {
18496 for (let pattern of input) {
18497 let result = braces.create(pattern, options);
18498 if (Array.isArray(result)) {
18499 output.push(...result);
18500 }
18501 else {
18502 output.push(result);
18503 }
18504 }
18505 }
18506 else {
18507 output = [].concat(braces.create(input, options));
18508 }
18509 if (options && options.expand === true && options.nodupes === true) {
18510 output = [...new Set(output)];
18511 }
18512 return output;
18513};
18514/**
18515 * Parse the given `str` with the given `options`.
18516 *
18517 * ```js
18518 * // braces.parse(pattern, [, options]);
18519 * const ast = braces.parse('a/{b,c}/d');
18520 * console.log(ast);
18521 * ```
18522 * @param {String} pattern Brace pattern to parse
18523 * @param {Object} options
18524 * @return {Object} Returns an AST
18525 * @api public
18526 */
18527braces.parse = (input, options = {}) => parse_1(input, options);
18528/**
18529 * Creates a braces string from an AST, or an AST node.
18530 *
18531 * ```js
18532 * const braces = require('braces');
18533 * let ast = braces.parse('foo/{a,b}/bar');
18534 * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
18535 * ```
18536 * @param {String} `input` Brace pattern or AST.
18537 * @param {Object} `options`
18538 * @return {Array} Returns an array of expanded values.
18539 * @api public
18540 */
18541braces.stringify = (input, options = {}) => {
18542 if (typeof input === 'string') {
18543 return stringify(braces.parse(input, options), options);
18544 }
18545 return stringify(input, options);
18546};
18547/**
18548 * Compiles a brace pattern into a regex-compatible, optimized string.
18549 * This method is called by the main [braces](#braces) function by default.
18550 *
18551 * ```js
18552 * const braces = require('braces');
18553 * console.log(braces.compile('a/{b,c}/d'));
18554 * //=> ['a/(b|c)/d']
18555 * ```
18556 * @param {String} `input` Brace pattern or AST.
18557 * @param {Object} `options`
18558 * @return {Array} Returns an array of expanded values.
18559 * @api public
18560 */
18561braces.compile = (input, options = {}) => {
18562 if (typeof input === 'string') {
18563 input = braces.parse(input, options);
18564 }
18565 return compile_1(input, options);
18566};
18567/**
18568 * Expands a brace pattern into an array. This method is called by the
18569 * main [braces](#braces) function when `options.expand` is true. Before
18570 * using this method it's recommended that you read the [performance notes](#performance))
18571 * and advantages of using [.compile](#compile) instead.
18572 *
18573 * ```js
18574 * const braces = require('braces');
18575 * console.log(braces.expand('a/{b,c}/d'));
18576 * //=> ['a/b/d', 'a/c/d'];
18577 * ```
18578 * @param {String} `pattern` Brace pattern
18579 * @param {Object} `options`
18580 * @return {Array} Returns an array of expanded values.
18581 * @api public
18582 */
18583braces.expand = (input, options = {}) => {
18584 if (typeof input === 'string') {
18585 input = braces.parse(input, options);
18586 }
18587 let result = expand_1(input, options);
18588 // filter out empty strings if specified
18589 if (options.noempty === true) {
18590 result = result.filter(Boolean);
18591 }
18592 // filter out duplicates if specified
18593 if (options.nodupes === true) {
18594 result = [...new Set(result)];
18595 }
18596 return result;
18597};
18598/**
18599 * Processes a brace pattern and returns either an expanded array
18600 * (if `options.expand` is true), a highly optimized regex-compatible string.
18601 * This method is called by the main [braces](#braces) function.
18602 *
18603 * ```js
18604 * const braces = require('braces');
18605 * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
18606 * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
18607 * ```
18608 * @param {String} `pattern` Brace pattern
18609 * @param {Object} `options`
18610 * @return {Array} Returns an array of expanded values.
18611 * @api public
18612 */
18613braces.create = (input, options = {}) => {
18614 if (input === '' || input.length < 3) {
18615 return [input];
18616 }
18617 return options.expand !== true
18618 ? braces.compile(input, options)
18619 : braces.expand(input, options);
18620};
18621/**
18622 * Expose "braces"
18623 */
18624var braces_1 = braces;
18625
18626const WIN_SLASH = '\\\\/';
18627const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
18628/**
18629 * Posix glob regex
18630 */
18631const DOT_LITERAL = '\\.';
18632const PLUS_LITERAL = '\\+';
18633const QMARK_LITERAL = '\\?';
18634const SLASH_LITERAL = '\\/';
18635const ONE_CHAR = '(?=.)';
18636const QMARK = '[^/]';
18637const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
18638const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
18639const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
18640const NO_DOT = `(?!${DOT_LITERAL})`;
18641const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
18642const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
18643const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
18644const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
18645const STAR = `${QMARK}*?`;
18646const POSIX_CHARS = {
18647 DOT_LITERAL,
18648 PLUS_LITERAL,
18649 QMARK_LITERAL,
18650 SLASH_LITERAL,
18651 ONE_CHAR,
18652 QMARK,
18653 END_ANCHOR,
18654 DOTS_SLASH,
18655 NO_DOT,
18656 NO_DOTS,
18657 NO_DOT_SLASH,
18658 NO_DOTS_SLASH,
18659 QMARK_NO_DOT,
18660 STAR,
18661 START_ANCHOR
18662};
18663/**
18664 * Windows glob regex
18665 */
18666const 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}]|$)` });
18667/**
18668 * POSIX Bracket Regex
18669 */
18670const POSIX_REGEX_SOURCE = {
18671 alnum: 'a-zA-Z0-9',
18672 alpha: 'a-zA-Z',
18673 ascii: '\\x00-\\x7F',
18674 blank: ' \\t',
18675 cntrl: '\\x00-\\x1F\\x7F',
18676 digit: '0-9',
18677 graph: '\\x21-\\x7E',
18678 lower: 'a-z',
18679 print: '\\x20-\\x7E ',
18680 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
18681 space: ' \\t\\r\\n\\v\\f',
18682 upper: 'A-Z',
18683 word: 'A-Za-z0-9_',
18684 xdigit: 'A-Fa-f0-9'
18685};
18686var constants$1 = {
18687 MAX_LENGTH: 1024 * 64,
18688 POSIX_REGEX_SOURCE,
18689 // regular expressions
18690 REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
18691 REGEX_NON_SPECIAL_CHAR: /^[^@![\].,$*+?^{}()|\\/]+/,
18692 REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
18693 REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
18694 REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
18695 REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
18696 // Replace globs with equivalent patterns to reduce parsing time.
18697 REPLACEMENTS: {
18698 '***': '*',
18699 '**/**': '**',
18700 '**/**/**': '**'
18701 },
18702 // Digits
18703 CHAR_0: 48,
18704 CHAR_9: 57,
18705 // Alphabet chars.
18706 CHAR_UPPERCASE_A: 65,
18707 CHAR_LOWERCASE_A: 97,
18708 CHAR_UPPERCASE_Z: 90,
18709 CHAR_LOWERCASE_Z: 122,
18710 CHAR_LEFT_PARENTHESES: 40,
18711 CHAR_RIGHT_PARENTHESES: 41,
18712 CHAR_ASTERISK: 42,
18713 // Non-alphabetic chars.
18714 CHAR_AMPERSAND: 38,
18715 CHAR_AT: 64,
18716 CHAR_BACKWARD_SLASH: 92,
18717 CHAR_CARRIAGE_RETURN: 13,
18718 CHAR_CIRCUMFLEX_ACCENT: 94,
18719 CHAR_COLON: 58,
18720 CHAR_COMMA: 44,
18721 CHAR_DOT: 46,
18722 CHAR_DOUBLE_QUOTE: 34,
18723 CHAR_EQUAL: 61,
18724 CHAR_EXCLAMATION_MARK: 33,
18725 CHAR_FORM_FEED: 12,
18726 CHAR_FORWARD_SLASH: 47,
18727 CHAR_GRAVE_ACCENT: 96,
18728 CHAR_HASH: 35,
18729 CHAR_HYPHEN_MINUS: 45,
18730 CHAR_LEFT_ANGLE_BRACKET: 60,
18731 CHAR_LEFT_CURLY_BRACE: 123,
18732 CHAR_LEFT_SQUARE_BRACKET: 91,
18733 CHAR_LINE_FEED: 10,
18734 CHAR_NO_BREAK_SPACE: 160,
18735 CHAR_PERCENT: 37,
18736 CHAR_PLUS: 43,
18737 CHAR_QUESTION_MARK: 63,
18738 CHAR_RIGHT_ANGLE_BRACKET: 62,
18739 CHAR_RIGHT_CURLY_BRACE: 125,
18740 CHAR_RIGHT_SQUARE_BRACKET: 93,
18741 CHAR_SEMICOLON: 59,
18742 CHAR_SINGLE_QUOTE: 39,
18743 CHAR_SPACE: 32,
18744 CHAR_TAB: 9,
18745 CHAR_UNDERSCORE: 95,
18746 CHAR_VERTICAL_LINE: 124,
18747 CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
18748 SEP: path.sep,
18749 /**
18750 * Create EXTGLOB_CHARS
18751 */
18752 extglobChars(chars) {
18753 return {
18754 '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
18755 '?': { type: 'qmark', open: '(?:', close: ')?' },
18756 '+': { type: 'plus', open: '(?:', close: ')+' },
18757 '*': { type: 'star', open: '(?:', close: ')*' },
18758 '@': { type: 'at', open: '(?:', close: ')' }
18759 };
18760 },
18761 /**
18762 * Create GLOB_CHARS
18763 */
18764 globChars(win32) {
18765 return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
18766 }
18767};
18768
18769var utils$2 = index.createCommonjsModule(function (module, exports) {
18770 const win32 = process.platform === 'win32';
18771 const { REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL, REGEX_REMOVE_BACKSLASH } = constants$1;
18772 exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
18773 exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
18774 exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
18775 exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
18776 exports.toPosixSlashes = str => str.replace(/\\/g, '/');
18777 exports.removeBackslashes = str => {
18778 return str.replace(REGEX_REMOVE_BACKSLASH, match => {
18779 return match === '\\' ? '' : match;
18780 });
18781 };
18782 exports.supportsLookbehinds = () => {
18783 let segs = process.version.slice(1).split('.');
18784 if (segs.length === 3 && +segs[0] >= 9 || (+segs[0] === 8 && +segs[1] >= 10)) {
18785 return true;
18786 }
18787 return false;
18788 };
18789 exports.isWindows = options => {
18790 if (options && typeof options.windows === 'boolean') {
18791 return options.windows;
18792 }
18793 return win32 === true || path.sep === '\\';
18794 };
18795 exports.escapeLast = (input, char, lastIdx) => {
18796 let idx = input.lastIndexOf(char, lastIdx);
18797 if (idx === -1)
18798 return input;
18799 if (input[idx - 1] === '\\')
18800 return exports.escapeLast(input, char, idx - 1);
18801 return input.slice(0, idx) + '\\' + input.slice(idx);
18802 };
18803});
18804
18805const { CHAR_ASTERISK, /* * */ CHAR_AT, /* @ */ CHAR_BACKWARD_SLASH, /* \ */ CHAR_COMMA: CHAR_COMMA$1, /* , */ CHAR_DOT: CHAR_DOT$1, /* . */ CHAR_EXCLAMATION_MARK, /* ! */ CHAR_FORWARD_SLASH, /* / */ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ CHAR_PLUS, /* + */ CHAR_QUESTION_MARK, /* ? */ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */ } = constants$1;
18806const isPathSeparator = code => {
18807 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
18808};
18809/**
18810 * Quickly scans a glob pattern and returns an object with a handful of
18811 * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
18812 * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
18813 *
18814 * ```js
18815 * const pm = require('picomatch');
18816 * console.log(pm.scan('foo/bar/*.js'));
18817 * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
18818 * ```
18819 * @param {String} `str`
18820 * @param {Object} `options`
18821 * @return {Object} Returns an object with tokens and regex source string.
18822 * @api public
18823 */
18824var scan = (input, options) => {
18825 let opts = options || {};
18826 let length = input.length - 1;
18827 let index = -1;
18828 let start = 0;
18829 let lastIndex = 0;
18830 let isGlob = false;
18831 let backslashes = false;
18832 let negated = false;
18833 let braces = 0;
18834 let prev;
18835 let code;
18836 let braceEscaped = false;
18837 let eos = () => index >= length;
18838 let advance = () => {
18839 prev = code;
18840 return input.charCodeAt(++index);
18841 };
18842 while (index < length) {
18843 code = advance();
18844 let next;
18845 if (code === CHAR_BACKWARD_SLASH) {
18846 backslashes = true;
18847 next = advance();
18848 if (next === CHAR_LEFT_CURLY_BRACE$1) {
18849 braceEscaped = true;
18850 }
18851 continue;
18852 }
18853 if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
18854 braces++;
18855 while (!eos() && (next = advance())) {
18856 if (next === CHAR_BACKWARD_SLASH) {
18857 backslashes = true;
18858 next = advance();
18859 continue;
18860 }
18861 if (next === CHAR_LEFT_CURLY_BRACE$1) {
18862 braces++;
18863 continue;
18864 }
18865 if (!braceEscaped && next === CHAR_DOT$1 && (next = advance()) === CHAR_DOT$1) {
18866 isGlob = true;
18867 break;
18868 }
18869 if (!braceEscaped && next === CHAR_COMMA$1) {
18870 isGlob = true;
18871 break;
18872 }
18873 if (next === CHAR_RIGHT_CURLY_BRACE$1) {
18874 braces--;
18875 if (braces === 0) {
18876 braceEscaped = false;
18877 break;
18878 }
18879 }
18880 }
18881 }
18882 if (code === CHAR_FORWARD_SLASH) {
18883 if (prev === CHAR_DOT$1 && index === (start + 1)) {
18884 start += 2;
18885 continue;
18886 }
18887 lastIndex = index + 1;
18888 continue;
18889 }
18890 if (code === CHAR_ASTERISK) {
18891 isGlob = true;
18892 break;
18893 }
18894 if (code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK) {
18895 isGlob = true;
18896 break;
18897 }
18898 if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
18899 while (!eos() && (next = advance())) {
18900 if (next === CHAR_BACKWARD_SLASH) {
18901 backslashes = true;
18902 next = advance();
18903 continue;
18904 }
18905 if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
18906 isGlob = true;
18907 break;
18908 }
18909 }
18910 }
18911 let isExtglobChar = code === CHAR_PLUS
18912 || code === CHAR_AT
18913 || code === CHAR_EXCLAMATION_MARK;
18914 if (isExtglobChar && input.charCodeAt(index + 1) === CHAR_LEFT_PARENTHESES$1) {
18915 isGlob = true;
18916 break;
18917 }
18918 if (code === CHAR_EXCLAMATION_MARK && index === start) {
18919 negated = true;
18920 start++;
18921 continue;
18922 }
18923 if (code === CHAR_LEFT_PARENTHESES$1) {
18924 while (!eos() && (next = advance())) {
18925 if (next === CHAR_BACKWARD_SLASH) {
18926 backslashes = true;
18927 next = advance();
18928 continue;
18929 }
18930 if (next === CHAR_RIGHT_PARENTHESES$1) {
18931 isGlob = true;
18932 break;
18933 }
18934 }
18935 }
18936 if (isGlob) {
18937 break;
18938 }
18939 }
18940 let prefix = '';
18941 let orig = input;
18942 let base = input;
18943 let glob = '';
18944 if (start > 0) {
18945 prefix = input.slice(0, start);
18946 input = input.slice(start);
18947 lastIndex -= start;
18948 }
18949 if (base && isGlob === true && lastIndex > 0) {
18950 base = input.slice(0, lastIndex);
18951 glob = input.slice(lastIndex);
18952 }
18953 else if (isGlob === true) {
18954 base = '';
18955 glob = input;
18956 }
18957 else {
18958 base = input;
18959 }
18960 if (base && base !== '' && base !== '/' && base !== input) {
18961 if (isPathSeparator(base.charCodeAt(base.length - 1))) {
18962 base = base.slice(0, -1);
18963 }
18964 }
18965 if (opts.unescape === true) {
18966 if (glob)
18967 glob = utils$2.removeBackslashes(glob);
18968 if (base && backslashes === true) {
18969 base = utils$2.removeBackslashes(base);
18970 }
18971 }
18972 return { prefix, input: orig, base, glob, negated, isGlob };
18973};
18974
18975/**
18976 * Constants
18977 */
18978const { MAX_LENGTH: MAX_LENGTH$1, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, REGEX_NON_SPECIAL_CHAR, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$1;
18979/**
18980 * Helpers
18981 */
18982const expandRange = (args, options) => {
18983 if (typeof options.expandRange === 'function') {
18984 return options.expandRange(...args, options);
18985 }
18986 args.sort();
18987 let value = `[${args.join('-')}]`;
18988 try {
18989 }
18990 catch (ex) {
18991 return args.map(v => utils$2.escapeRegex(v)).join('..');
18992 }
18993 return value;
18994};
18995const negate = state => {
18996 let count = 1;
18997 while (state.peek() === '!' && (state.peek(2) !== '(' || state.peek(3) === '?')) {
18998 state.advance();
18999 state.start++;
19000 count++;
19001 }
19002 if (count % 2 === 0) {
19003 return false;
19004 }
19005 state.negated = true;
19006 state.start++;
19007 return true;
19008};
19009/**
19010 * Create the message for a syntax error
19011 */
19012const syntaxError = (type, char) => {
19013 return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
19014};
19015/**
19016 * Parse the given input string.
19017 * @param {String} input
19018 * @param {Object} options
19019 * @return {Object}
19020 */
19021const parse$1 = (input, options) => {
19022 if (typeof input !== 'string') {
19023 throw new TypeError('Expected a string');
19024 }
19025 input = REPLACEMENTS[input] || input;
19026 let opts = Object.assign({}, options);
19027 let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
19028 let len = input.length;
19029 if (len > max) {
19030 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
19031 }
19032 let bos = { type: 'bos', value: '', output: opts.prepend || '' };
19033 let tokens = [bos];
19034 let capture = opts.capture ? '' : '?:';
19035 let win32 = utils$2.isWindows(options);
19036 // create constants based on platform, for windows or posix
19037 const PLATFORM_CHARS = constants$1.globChars(win32);
19038 const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
19039 const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS;
19040 const globstar = (opts) => {
19041 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
19042 };
19043 let nodot = opts.dot ? '' : NO_DOT;
19044 let star = opts.bash === true ? globstar(opts) : STAR;
19045 let qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
19046 if (opts.capture) {
19047 star = `(${star})`;
19048 }
19049 // minimatch options support
19050 if (typeof opts.noext === 'boolean') {
19051 opts.noextglob = opts.noext;
19052 }
19053 let state = {
19054 index: -1,
19055 start: 0,
19056 consumed: '',
19057 output: '',
19058 backtrack: false,
19059 brackets: 0,
19060 braces: 0,
19061 parens: 0,
19062 quotes: 0,
19063 tokens
19064 };
19065 let extglobs = [];
19066 let stack = [];
19067 let prev = bos;
19068 let value;
19069 /**
19070 * Tokenizing helpers
19071 */
19072 const eos = () => state.index === len - 1;
19073 const peek = state.peek = (n = 1) => input[state.index + n];
19074 const advance = state.advance = () => input[++state.index];
19075 const append = token => {
19076 state.output += token.output != null ? token.output : token.value;
19077 state.consumed += token.value || '';
19078 };
19079 const increment = type => {
19080 state[type]++;
19081 stack.push(type);
19082 };
19083 const decrement = type => {
19084 state[type]--;
19085 stack.pop();
19086 };
19087 /**
19088 * Push tokens onto the tokens array. This helper speeds up
19089 * tokenizing by 1) helping us avoid backtracking as much as possible,
19090 * and 2) helping us avoid creating extra tokens when consecutive
19091 * characters are plain text. This improves performance and simplifies
19092 * lookbehinds.
19093 */
19094 const push = tok => {
19095 if (prev.type === 'globstar') {
19096 let isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
19097 let isExtglob = extglobs.length && (tok.type === 'pipe' || tok.type === 'paren');
19098 if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
19099 state.output = state.output.slice(0, -prev.output.length);
19100 prev.type = 'star';
19101 prev.value = '*';
19102 prev.output = star;
19103 state.output += prev.output;
19104 }
19105 }
19106 if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
19107 extglobs[extglobs.length - 1].inner += tok.value;
19108 }
19109 if (tok.value || tok.output)
19110 append(tok);
19111 if (prev && prev.type === 'text' && tok.type === 'text') {
19112 prev.value += tok.value;
19113 return;
19114 }
19115 tok.prev = prev;
19116 tokens.push(tok);
19117 prev = tok;
19118 };
19119 const extglobOpen = (type, value) => {
19120 let token = Object.assign({}, EXTGLOB_CHARS[value], { conditions: 1, inner: '' });
19121 token.prev = prev;
19122 token.parens = state.parens;
19123 token.output = state.output;
19124 let output = (opts.capture ? '(' : '') + token.open;
19125 push({ type, value, output: state.output ? '' : ONE_CHAR });
19126 push({ type: 'paren', extglob: true, value: advance(), output });
19127 increment('parens');
19128 extglobs.push(token);
19129 };
19130 const extglobClose = token => {
19131 let output = token.close + (opts.capture ? ')' : '');
19132 if (token.type === 'negate') {
19133 let extglobStar = star;
19134 if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
19135 extglobStar = globstar(opts);
19136 }
19137 if (extglobStar !== star || eos() || /^\)+$/.test(input.slice(state.index + 1))) {
19138 output = token.close = ')$))' + extglobStar;
19139 }
19140 if (token.prev.type === 'bos' && eos()) {
19141 state.negatedExtglob = true;
19142 }
19143 }
19144 push({ type: 'paren', extglob: true, value, output });
19145 decrement('parens');
19146 };
19147 if (opts.fastpaths !== false && !/(^[*!]|[/{[()\]}"])/.test(input)) {
19148 let backslashes = false;
19149 let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
19150 if (first === '\\') {
19151 backslashes = true;
19152 return m;
19153 }
19154 if (first === '?') {
19155 if (esc) {
19156 return esc + first + (rest ? QMARK.repeat(rest.length) : '');
19157 }
19158 if (index === 0) {
19159 return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
19160 }
19161 return QMARK.repeat(chars.length);
19162 }
19163 if (first === '.') {
19164 return DOT_LITERAL.repeat(chars.length);
19165 }
19166 if (first === '*') {
19167 if (esc) {
19168 return esc + first + (rest ? star : '');
19169 }
19170 return star;
19171 }
19172 return esc ? m : '\\' + m;
19173 });
19174 if (backslashes === true) {
19175 if (opts.unescape === true) {
19176 output = output.replace(/\\/g, '');
19177 }
19178 else {
19179 output = output.replace(/\\+/g, m => {
19180 return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
19181 });
19182 }
19183 }
19184 state.output = output;
19185 return state;
19186 }
19187 /**
19188 * Tokenize input until we reach end-of-string
19189 */
19190 while (!eos()) {
19191 value = advance();
19192 if (value === '\u0000') {
19193 continue;
19194 }
19195 /**
19196 * Escaped characters
19197 */
19198 if (value === '\\') {
19199 let next = peek();
19200 if (next === '/' && opts.bash !== true) {
19201 continue;
19202 }
19203 if (next === '.' || next === ';') {
19204 continue;
19205 }
19206 if (!next) {
19207 value += '\\';
19208 push({ type: 'text', value });
19209 continue;
19210 }
19211 // collapse slashes to reduce potential for exploits
19212 let match = /^\\+/.exec(input.slice(state.index + 1));
19213 let slashes = 0;
19214 if (match && match[0].length > 2) {
19215 slashes = match[0].length;
19216 state.index += slashes;
19217 if (slashes % 2 !== 0) {
19218 value += '\\';
19219 }
19220 }
19221 if (opts.unescape === true) {
19222 value = advance() || '';
19223 }
19224 else {
19225 value += advance() || '';
19226 }
19227 if (state.brackets === 0) {
19228 push({ type: 'text', value });
19229 continue;
19230 }
19231 }
19232 /**
19233 * If we're inside a regex character class, continue
19234 * until we reach the closing bracket.
19235 */
19236 if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
19237 if (opts.posix !== false && value === ':') {
19238 let inner = prev.value.slice(1);
19239 if (inner.includes('[')) {
19240 prev.posix = true;
19241 if (inner.includes(':')) {
19242 let idx = prev.value.lastIndexOf('[');
19243 let pre = prev.value.slice(0, idx);
19244 let rest = prev.value.slice(idx + 2);
19245 let posix = POSIX_REGEX_SOURCE$1[rest];
19246 if (posix) {
19247 prev.value = pre + posix;
19248 state.backtrack = true;
19249 advance();
19250 if (!bos.output && tokens.indexOf(prev) === 1) {
19251 bos.output = ONE_CHAR;
19252 }
19253 continue;
19254 }
19255 }
19256 }
19257 }
19258 if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
19259 value = '\\' + value;
19260 }
19261 if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
19262 value = '\\' + value;
19263 }
19264 if (opts.posix === true && value === '!' && prev.value === '[') {
19265 value = '^';
19266 }
19267 prev.value += value;
19268 append({ value });
19269 continue;
19270 }
19271 /**
19272 * If we're inside a quoted string, continue
19273 * until we reach the closing double quote.
19274 */
19275 if (state.quotes === 1 && value !== '"') {
19276 value = utils$2.escapeRegex(value);
19277 prev.value += value;
19278 append({ value });
19279 continue;
19280 }
19281 /**
19282 * Double quotes
19283 */
19284 if (value === '"') {
19285 state.quotes = state.quotes === 1 ? 0 : 1;
19286 if (opts.keepQuotes === true) {
19287 push({ type: 'text', value });
19288 }
19289 continue;
19290 }
19291 /**
19292 * Parentheses
19293 */
19294 if (value === '(') {
19295 push({ type: 'paren', value });
19296 increment('parens');
19297 continue;
19298 }
19299 if (value === ')') {
19300 if (state.parens === 0 && opts.strictBrackets === true) {
19301 throw new SyntaxError(syntaxError('opening', '('));
19302 }
19303 let extglob = extglobs[extglobs.length - 1];
19304 if (extglob && state.parens === extglob.parens + 1) {
19305 extglobClose(extglobs.pop());
19306 continue;
19307 }
19308 push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
19309 decrement('parens');
19310 continue;
19311 }
19312 /**
19313 * Brackets
19314 */
19315 if (value === '[') {
19316 if (opts.nobracket === true || !input.slice(state.index + 1).includes(']')) {
19317 if (opts.nobracket !== true && opts.strictBrackets === true) {
19318 throw new SyntaxError(syntaxError('closing', ']'));
19319 }
19320 value = '\\' + value;
19321 }
19322 else {
19323 increment('brackets');
19324 }
19325 push({ type: 'bracket', value });
19326 continue;
19327 }
19328 if (value === ']') {
19329 if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
19330 push({ type: 'text', value, output: '\\' + value });
19331 continue;
19332 }
19333 if (state.brackets === 0) {
19334 if (opts.strictBrackets === true) {
19335 throw new SyntaxError(syntaxError('opening', '['));
19336 }
19337 push({ type: 'text', value, output: '\\' + value });
19338 continue;
19339 }
19340 decrement('brackets');
19341 let prevValue = prev.value.slice(1);
19342 if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
19343 value = '/' + value;
19344 }
19345 prev.value += value;
19346 append({ value });
19347 // when literal brackets are explicitly disabled
19348 // assume we should match with a regex character class
19349 if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) {
19350 continue;
19351 }
19352 let escaped = utils$2.escapeRegex(prev.value);
19353 state.output = state.output.slice(0, -prev.value.length);
19354 // when literal brackets are explicitly enabled
19355 // assume we should escape the brackets to match literal characters
19356 if (opts.literalBrackets === true) {
19357 state.output += escaped;
19358 prev.value = escaped;
19359 continue;
19360 }
19361 // when the user specifies nothing, try to match both
19362 prev.value = `(${capture}${escaped}|${prev.value})`;
19363 state.output += prev.value;
19364 continue;
19365 }
19366 /**
19367 * Braces
19368 */
19369 if (value === '{' && opts.nobrace !== true) {
19370 push({ type: 'brace', value, output: '(' });
19371 increment('braces');
19372 continue;
19373 }
19374 if (value === '}') {
19375 if (opts.nobrace === true || state.braces === 0) {
19376 push({ type: 'text', value, output: '\\' + value });
19377 continue;
19378 }
19379 let output = ')';
19380 if (state.dots === true) {
19381 let arr = tokens.slice();
19382 let range = [];
19383 for (let i = arr.length - 1; i >= 0; i--) {
19384 tokens.pop();
19385 if (arr[i].type === 'brace') {
19386 break;
19387 }
19388 if (arr[i].type !== 'dots') {
19389 range.unshift(arr[i].value);
19390 }
19391 }
19392 output = expandRange(range, opts);
19393 state.backtrack = true;
19394 }
19395 push({ type: 'brace', value, output });
19396 decrement('braces');
19397 continue;
19398 }
19399 /**
19400 * Pipes
19401 */
19402 if (value === '|') {
19403 if (extglobs.length > 0) {
19404 extglobs[extglobs.length - 1].conditions++;
19405 }
19406 push({ type: 'text', value });
19407 continue;
19408 }
19409 /**
19410 * Commas
19411 */
19412 if (value === ',') {
19413 let output = value;
19414 if (state.braces > 0 && stack[stack.length - 1] === 'braces') {
19415 output = '|';
19416 }
19417 push({ type: 'comma', value, output });
19418 continue;
19419 }
19420 /**
19421 * Slashes
19422 */
19423 if (value === '/') {
19424 // if the beginning of the glob is "./", advance the start
19425 // to the current index, and don't add the "./" characters
19426 // to the state. This greatly simplifies lookbehinds when
19427 // checking for BOS characters like "!" and "." (not "./")
19428 if (prev.type === 'dot' && state.index === 1) {
19429 state.start = state.index + 1;
19430 state.consumed = '';
19431 state.output = '';
19432 tokens.pop();
19433 prev = bos; // reset "prev" to the first token
19434 continue;
19435 }
19436 push({ type: 'slash', value, output: SLASH_LITERAL });
19437 continue;
19438 }
19439 /**
19440 * Dots
19441 */
19442 if (value === '.') {
19443 if (state.braces > 0 && prev.type === 'dot') {
19444 if (prev.value === '.')
19445 prev.output = DOT_LITERAL;
19446 prev.type = 'dots';
19447 prev.output += value;
19448 prev.value += value;
19449 state.dots = true;
19450 continue;
19451 }
19452 push({ type: 'dot', value, output: DOT_LITERAL });
19453 continue;
19454 }
19455 /**
19456 * Question marks
19457 */
19458 if (value === '?') {
19459 if (prev && prev.type === 'paren') {
19460 let next = peek();
19461 let output = value;
19462 if (next === '<' && !utils$2.supportsLookbehinds()) {
19463 throw new Error('Node.js v10 or higher is required for regex lookbehinds');
19464 }
19465 if (prev.value === '(' && !/[!=<:]/.test(next) || (next === '<' && !/[!=]/.test(peek(2)))) {
19466 output = '\\' + value;
19467 }
19468 push({ type: 'text', value, output });
19469 continue;
19470 }
19471 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
19472 extglobOpen('qmark', value);
19473 continue;
19474 }
19475 if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
19476 push({ type: 'qmark', value, output: QMARK_NO_DOT });
19477 continue;
19478 }
19479 push({ type: 'qmark', value, output: QMARK });
19480 continue;
19481 }
19482 /**
19483 * Exclamation
19484 */
19485 if (value === '!') {
19486 if (opts.noextglob !== true && peek() === '(') {
19487 if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
19488 extglobOpen('negate', value);
19489 continue;
19490 }
19491 }
19492 if (opts.nonegate !== true && state.index === 0) {
19493 negate(state);
19494 continue;
19495 }
19496 }
19497 /**
19498 * Plus
19499 */
19500 if (value === '+') {
19501 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
19502 extglobOpen('plus', value);
19503 continue;
19504 }
19505 if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) {
19506 let output = prev.extglob === true ? '\\' + value : value;
19507 push({ type: 'plus', value, output });
19508 continue;
19509 }
19510 // use regex behavior inside parens
19511 if (state.parens > 0 && opts.regex !== false) {
19512 push({ type: 'plus', value });
19513 continue;
19514 }
19515 push({ type: 'plus', value: PLUS_LITERAL });
19516 continue;
19517 }
19518 /**
19519 * Plain text
19520 */
19521 if (value === '@') {
19522 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
19523 push({ type: 'at', value, output: '' });
19524 continue;
19525 }
19526 push({ type: 'text', value });
19527 continue;
19528 }
19529 /**
19530 * Plain text
19531 */
19532 if (value !== '*') {
19533 if (value === '$' || value === '^') {
19534 value = '\\' + value;
19535 }
19536 let match = REGEX_NON_SPECIAL_CHAR.exec(input.slice(state.index + 1));
19537 if (match) {
19538 value += match[0];
19539 state.index += match[0].length;
19540 }
19541 push({ type: 'text', value });
19542 continue;
19543 }
19544 /**
19545 * Stars
19546 */
19547 if (prev && (prev.type === 'globstar' || prev.star === true)) {
19548 prev.type = 'star';
19549 prev.star = true;
19550 prev.value += value;
19551 prev.output = star;
19552 state.backtrack = true;
19553 state.consumed += value;
19554 continue;
19555 }
19556 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
19557 extglobOpen('star', value);
19558 continue;
19559 }
19560 if (prev.type === 'star') {
19561 if (opts.noglobstar === true) {
19562 state.consumed += value;
19563 continue;
19564 }
19565 let prior = prev.prev;
19566 let before = prior.prev;
19567 let isStart = prior.type === 'slash' || prior.type === 'bos';
19568 let afterStar = before && (before.type === 'star' || before.type === 'globstar');
19569 if (opts.bash === true && (!isStart || (!eos() && peek() !== '/'))) {
19570 push({ type: 'star', value, output: '' });
19571 continue;
19572 }
19573 let isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
19574 let isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
19575 if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
19576 push({ type: 'star', value, output: '' });
19577 continue;
19578 }
19579 // strip consecutive `/**/`
19580 while (input.slice(state.index + 1, state.index + 4) === '/**') {
19581 let after = input[state.index + 4];
19582 if (after && after !== '/') {
19583 break;
19584 }
19585 state.consumed += '/**';
19586 state.index += 3;
19587 }
19588 if (prior.type === 'bos' && eos()) {
19589 prev.type = 'globstar';
19590 prev.value += value;
19591 prev.output = globstar(opts);
19592 state.output = prev.output;
19593 state.consumed += value;
19594 continue;
19595 }
19596 if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
19597 state.output = state.output.slice(0, -(prior.output + prev.output).length);
19598 prior.output = '(?:' + prior.output;
19599 prev.type = 'globstar';
19600 prev.output = globstar(opts) + '|$)';
19601 prev.value += value;
19602 state.output += prior.output + prev.output;
19603 state.consumed += value;
19604 continue;
19605 }
19606 let next = peek();
19607 if (prior.type === 'slash' && prior.prev.type !== 'bos' && next === '/') {
19608 let end = peek(2) !== void 0 ? '|$' : '';
19609 state.output = state.output.slice(0, -(prior.output + prev.output).length);
19610 prior.output = '(?:' + prior.output;
19611 prev.type = 'globstar';
19612 prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
19613 prev.value += value;
19614 state.output += prior.output + prev.output;
19615 state.consumed += value + advance();
19616 push({ type: 'slash', value, output: '' });
19617 continue;
19618 }
19619 if (prior.type === 'bos' && next === '/') {
19620 prev.type = 'globstar';
19621 prev.value += value;
19622 prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
19623 state.output = prev.output;
19624 state.consumed += value + advance();
19625 push({ type: 'slash', value, output: '' });
19626 continue;
19627 }
19628 // remove single star from output
19629 state.output = state.output.slice(0, -prev.output.length);
19630 // reset previous token to globstar
19631 prev.type = 'globstar';
19632 prev.output = globstar(opts);
19633 prev.value += value;
19634 // reset output with globstar
19635 state.output += prev.output;
19636 state.consumed += value;
19637 continue;
19638 }
19639 let token = { type: 'star', value, output: star };
19640 if (opts.bash === true) {
19641 token.output = '.*?';
19642 if (prev.type === 'bos' || prev.type === 'slash') {
19643 token.output = nodot + token.output;
19644 }
19645 push(token);
19646 continue;
19647 }
19648 if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
19649 token.output = value;
19650 push(token);
19651 continue;
19652 }
19653 if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
19654 if (prev.type === 'dot') {
19655 state.output += NO_DOT_SLASH;
19656 prev.output += NO_DOT_SLASH;
19657 }
19658 else if (opts.dot === true) {
19659 state.output += NO_DOTS_SLASH;
19660 prev.output += NO_DOTS_SLASH;
19661 }
19662 else {
19663 state.output += nodot;
19664 prev.output += nodot;
19665 }
19666 if (peek() !== '*') {
19667 state.output += ONE_CHAR;
19668 prev.output += ONE_CHAR;
19669 }
19670 }
19671 push(token);
19672 }
19673 while (state.brackets > 0) {
19674 if (opts.strictBrackets === true)
19675 throw new SyntaxError(syntaxError('closing', ']'));
19676 state.output = utils$2.escapeLast(state.output, '[');
19677 decrement('brackets');
19678 }
19679 while (state.parens > 0) {
19680 if (opts.strictBrackets === true)
19681 throw new SyntaxError(syntaxError('closing', ')'));
19682 state.output = utils$2.escapeLast(state.output, '(');
19683 decrement('parens');
19684 }
19685 while (state.braces > 0) {
19686 if (opts.strictBrackets === true)
19687 throw new SyntaxError(syntaxError('closing', '}'));
19688 state.output = utils$2.escapeLast(state.output, '{');
19689 decrement('braces');
19690 }
19691 if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
19692 push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
19693 }
19694 // rebuild the output if we had to backtrack at any point
19695 if (state.backtrack === true) {
19696 state.output = '';
19697 for (let token of state.tokens) {
19698 state.output += token.output != null ? token.output : token.value;
19699 if (token.suffix) {
19700 state.output += token.suffix;
19701 }
19702 }
19703 }
19704 return state;
19705};
19706/**
19707 * Fast paths for creating regular expressions for common glob patterns.
19708 * This can significantly speed up processing and has very little downside
19709 * impact when none of the fast paths match.
19710 */
19711parse$1.fastpaths = (input, options) => {
19712 let opts = Object.assign({}, options);
19713 let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
19714 let len = input.length;
19715 if (len > max) {
19716 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
19717 }
19718 input = REPLACEMENTS[input] || input;
19719 let win32 = utils$2.isWindows(options);
19720 // create constants based on platform, for windows or posix
19721 const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants$1.globChars(win32);
19722 let capture = opts.capture ? '' : '?:';
19723 let star = opts.bash === true ? '.*?' : STAR;
19724 let nodot = opts.dot ? NO_DOTS : NO_DOT;
19725 let slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
19726 if (opts.capture) {
19727 star = `(${star})`;
19728 }
19729 const globstar = (opts) => {
19730 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
19731 };
19732 const create = str => {
19733 switch (str) {
19734 case '*':
19735 return `${nodot}${ONE_CHAR}${star}`;
19736 case '.*':
19737 return `${DOT_LITERAL}${ONE_CHAR}${star}`;
19738 case '*.*':
19739 return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
19740 case '*/*':
19741 return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
19742 case '**':
19743 return nodot + globstar(opts);
19744 case '**/*':
19745 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
19746 case '**/*.*':
19747 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
19748 case '**/.*':
19749 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
19750 default: {
19751 let match = /^(.*?)\.(\w+)$/.exec(str);
19752 if (!match)
19753 return;
19754 let source = create(match[1]);
19755 if (!source)
19756 return;
19757 return source + DOT_LITERAL + match[2];
19758 }
19759 }
19760 };
19761 let output = create(input);
19762 if (output && opts.strictSlashes !== true) {
19763 output += `${SLASH_LITERAL}?`;
19764 }
19765 return output;
19766};
19767var parse_1$1 = parse$1;
19768
19769/**
19770 * Creates a matcher function from one or more glob patterns. The
19771 * returned function takes a string to match as its first argument,
19772 * and returns true if the string is a match. The returned matcher
19773 * function also takes a boolean as the second argument that, when true,
19774 * returns an object with additional information.
19775 *
19776 * ```js
19777 * const picomatch = require('picomatch');
19778 * // picomatch(glob[, options]);
19779 *
19780 * const isMatch = picomatch('*.!(*a)');
19781 * console.log(isMatch('a.a')); //=> false
19782 * console.log(isMatch('a.b')); //=> true
19783 * ```
19784 * @name picomatch
19785 * @param {String|Array} `globs` One or more glob patterns.
19786 * @param {Object=} `options`
19787 * @return {Function=} Returns a matcher function.
19788 * @api public
19789 */
19790const picomatch = (glob, options, returnState = false) => {
19791 if (Array.isArray(glob)) {
19792 let fns = glob.map(input => picomatch(input, options, returnState));
19793 return str => {
19794 for (let isMatch of fns) {
19795 let state = isMatch(str);
19796 if (state)
19797 return state;
19798 }
19799 return false;
19800 };
19801 }
19802 if (typeof glob !== 'string' || glob === '') {
19803 throw new TypeError('Expected pattern to be a non-empty string');
19804 }
19805 let opts = options || {};
19806 let posix = utils$2.isWindows(options);
19807 let regex = picomatch.makeRe(glob, options, false, true);
19808 let state = regex.state;
19809 delete regex.state;
19810 let isIgnored = () => false;
19811 if (opts.ignore) {
19812 let ignoreOpts = Object.assign({}, options, { ignore: null, onMatch: null, onResult: null });
19813 isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
19814 }
19815 const matcher = (input, returnObject = false) => {
19816 let { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
19817 let result = { glob, state, regex, posix, input, output, match, isMatch };
19818 if (typeof opts.onResult === 'function') {
19819 opts.onResult(result);
19820 }
19821 if (isMatch === false) {
19822 result.isMatch = false;
19823 return returnObject ? result : false;
19824 }
19825 if (isIgnored(input)) {
19826 if (typeof opts.onIgnore === 'function') {
19827 opts.onIgnore(result);
19828 }
19829 result.isMatch = false;
19830 return returnObject ? result : false;
19831 }
19832 if (typeof opts.onMatch === 'function') {
19833 opts.onMatch(result);
19834 }
19835 return returnObject ? result : true;
19836 };
19837 if (returnState) {
19838 matcher.state = state;
19839 }
19840 return matcher;
19841};
19842/**
19843 * Test `input` with the given `regex`. This is used by the main
19844 * `picomatch()` function to test the input string.
19845 *
19846 * ```js
19847 * const picomatch = require('picomatch');
19848 * // picomatch.test(input, regex[, options]);
19849 *
19850 * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
19851 * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
19852 * ```
19853 * @param {String} `input` String to test.
19854 * @param {RegExp} `regex`
19855 * @return {Object} Returns an object with matching info.
19856 * @api public
19857 */
19858picomatch.test = (input, regex, options, { glob, posix } = {}) => {
19859 if (typeof input !== 'string') {
19860 throw new TypeError('Expected input to be a string');
19861 }
19862 if (input === '') {
19863 return { isMatch: false, output: '' };
19864 }
19865 let opts = options || {};
19866 let format = opts.format || (posix ? utils$2.toPosixSlashes : null);
19867 let match = input === glob;
19868 let output = (match && format) ? format(input) : input;
19869 if (match === false) {
19870 output = format ? format(input) : input;
19871 match = output === glob;
19872 }
19873 if (match === false || opts.capture === true) {
19874 if (opts.matchBase === true || opts.basename === true) {
19875 match = picomatch.matchBase(input, regex, options, posix);
19876 }
19877 else {
19878 match = regex.exec(output);
19879 }
19880 }
19881 return { isMatch: !!match, match, output };
19882};
19883/**
19884 * Match the basename of a filepath.
19885 *
19886 * ```js
19887 * const picomatch = require('picomatch');
19888 * // picomatch.matchBase(input, glob[, options]);
19889 * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
19890 * ```
19891 * @param {String} `input` String to test.
19892 * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
19893 * @return {Boolean}
19894 * @api public
19895 */
19896picomatch.matchBase = (input, glob, options, posix = utils$2.isWindows(options)) => {
19897 let regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
19898 return regex.test(path.basename(input));
19899};
19900/**
19901 * Returns true if **any** of the given glob `patterns` match the specified `string`.
19902 *
19903 * ```js
19904 * const picomatch = require('picomatch');
19905 * // picomatch.isMatch(string, patterns[, options]);
19906 *
19907 * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
19908 * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
19909 * ```
19910 * @param {String|Array} str The string to test.
19911 * @param {String|Array} patterns One or more glob patterns to use for matching.
19912 * @param {Object} [options] See available [options](#options).
19913 * @return {Boolean} Returns true if any patterns match `str`
19914 * @api public
19915 */
19916picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
19917/**
19918 * Parse a glob pattern to create the source string for a regular
19919 * expression.
19920 *
19921 * ```js
19922 * const picomatch = require('picomatch');
19923 * const result = picomatch.parse(glob[, options]);
19924 * ```
19925 * @param {String} `glob`
19926 * @param {Object} `options`
19927 * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
19928 * @api public
19929 */
19930picomatch.parse = (glob, options) => parse_1$1(glob, options);
19931/**
19932 * Scan a glob pattern to separate the pattern into segments.
19933 *
19934 * ```js
19935 * const picomatch = require('picomatch');
19936 * // picomatch.scan(input[, options]);
19937 *
19938 * const result = picomatch.scan('!./foo/*.js');
19939 * console.log(result);
19940 * // { prefix: '!./',
19941 * // input: '!./foo/*.js',
19942 * // base: 'foo',
19943 * // glob: '*.js',
19944 * // negated: true,
19945 * // isGlob: true }
19946 * ```
19947 * @param {String} `input` Glob pattern to scan.
19948 * @param {Object} `options`
19949 * @return {Object} Returns an object with
19950 * @api public
19951 */
19952picomatch.scan = (input, options) => scan(input, options);
19953/**
19954 * Create a regular expression from a glob pattern.
19955 *
19956 * ```js
19957 * const picomatch = require('picomatch');
19958 * // picomatch.makeRe(input[, options]);
19959 *
19960 * console.log(picomatch.makeRe('*.js'));
19961 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
19962 * ```
19963 * @param {String} `input` A glob pattern to convert to regex.
19964 * @param {Object} `options`
19965 * @return {RegExp} Returns a regex created from the given pattern.
19966 * @api public
19967 */
19968picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
19969 if (!input || typeof input !== 'string') {
19970 throw new TypeError('Expected a non-empty string');
19971 }
19972 let opts = options || {};
19973 let prepend = opts.contains ? '' : '^';
19974 let append = opts.contains ? '' : '$';
19975 let state = { negated: false, fastpaths: true };
19976 let prefix = '';
19977 let output;
19978 if (input.startsWith('./')) {
19979 input = input.slice(2);
19980 prefix = state.prefix = './';
19981 }
19982 if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
19983 output = parse_1$1.fastpaths(input, options);
19984 }
19985 if (output === void 0) {
19986 state = picomatch.parse(input, options);
19987 state.prefix = prefix + (state.prefix || '');
19988 output = state.output;
19989 }
19990 if (returnOutput === true) {
19991 return output;
19992 }
19993 let source = `${prepend}(?:${output})${append}`;
19994 if (state && state.negated === true) {
19995 source = `^(?!${source}).*$`;
19996 }
19997 let regex = picomatch.toRegex(source, options);
19998 if (returnState === true) {
19999 regex.state = state;
20000 }
20001 return regex;
20002};
20003/**
20004 * Create a regular expression from the given regex source string.
20005 *
20006 * ```js
20007 * const picomatch = require('picomatch');
20008 * // picomatch.toRegex(source[, options]);
20009 *
20010 * const { output } = picomatch.parse('*.js');
20011 * console.log(picomatch.toRegex(output));
20012 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
20013 * ```
20014 * @param {String} `source` Regular expression source string.
20015 * @param {Object} `options`
20016 * @return {RegExp}
20017 * @api public
20018 */
20019picomatch.toRegex = (source, options) => {
20020 try {
20021 let opts = options || {};
20022 return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
20023 }
20024 catch (err) {
20025 if (options && options.debug === true)
20026 throw err;
20027 return /$^/;
20028 }
20029};
20030/**
20031 * Picomatch constants.
20032 * @return {Object}
20033 */
20034picomatch.constants = constants$1;
20035/**
20036 * Expose "picomatch"
20037 */
20038var picomatch_1 = picomatch;
20039
20040var picomatch$1 = picomatch_1;
20041
20042const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');
20043/**
20044 * Returns an array of strings that match one or more glob patterns.
20045 *
20046 * ```js
20047 * const mm = require('micromatch');
20048 * // mm(list, patterns[, options]);
20049 *
20050 * console.log(mm(['a.js', 'a.txt'], ['*.js']));
20051 * //=> [ 'a.js' ]
20052 * ```
20053 * @param {String|Array<string>} list List of strings to match.
20054 * @param {String|Array<string>} patterns One or more glob patterns to use for matching.
20055 * @param {Object} options See available [options](#options)
20056 * @return {Array} Returns an array of matches
20057 * @summary false
20058 * @api public
20059 */
20060const micromatch = (list, patterns, options) => {
20061 patterns = [].concat(patterns);
20062 list = [].concat(list);
20063 let omit = new Set();
20064 let keep = new Set();
20065 let items = new Set();
20066 let negatives = 0;
20067 let onResult = state => {
20068 items.add(state.output);
20069 if (options && options.onResult) {
20070 options.onResult(state);
20071 }
20072 };
20073 for (let i = 0; i < patterns.length; i++) {
20074 let isMatch = picomatch$1(String(patterns[i]), Object.assign({}, options, { onResult }), true);
20075 let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
20076 if (negated)
20077 negatives++;
20078 for (let item of list) {
20079 let matched = isMatch(item, true);
20080 let match = negated ? !matched.isMatch : matched.isMatch;
20081 if (!match)
20082 continue;
20083 if (negated) {
20084 omit.add(matched.output);
20085 }
20086 else {
20087 omit.delete(matched.output);
20088 keep.add(matched.output);
20089 }
20090 }
20091 }
20092 let result = negatives === patterns.length ? [...items] : [...keep];
20093 let matches = result.filter(item => !omit.has(item));
20094 if (options && matches.length === 0) {
20095 if (options.failglob === true) {
20096 throw new Error(`No matches found for "${patterns.join(', ')}"`);
20097 }
20098 if (options.nonull === true || options.nullglob === true) {
20099 return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
20100 }
20101 }
20102 return matches;
20103};
20104/**
20105 * Backwards compatibility
20106 */
20107micromatch.match = micromatch;
20108/**
20109 * Returns a matcher function from the given glob `pattern` and `options`.
20110 * The returned function takes a string to match as its only argument and returns
20111 * true if the string is a match.
20112 *
20113 * ```js
20114 * const mm = require('micromatch');
20115 * // mm.matcher(pattern[, options]);
20116 *
20117 * const isMatch = mm.matcher('*.!(*a)');
20118 * console.log(isMatch('a.a')); //=> false
20119 * console.log(isMatch('a.b')); //=> true
20120 * ```
20121 * @param {String} `pattern` Glob pattern
20122 * @param {Object} `options`
20123 * @return {Function} Returns a matcher function.
20124 * @api public
20125 */
20126micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);
20127/**
20128 * Returns true if **any** of the given glob `patterns` match the specified `string`.
20129 *
20130 * ```js
20131 * const mm = require('micromatch');
20132 * // mm.isMatch(string, patterns[, options]);
20133 *
20134 * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
20135 * console.log(mm.isMatch('a.a', 'b.*')); //=> false
20136 * ```
20137 * @param {String} str The string to test.
20138 * @param {String|Array} patterns One or more glob patterns to use for matching.
20139 * @param {Object} [options] See available [options](#options).
20140 * @return {Boolean} Returns true if any patterns match `str`
20141 * @api public
20142 */
20143micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
20144/**
20145 * Backwards compatibility
20146 */
20147micromatch.any = micromatch.isMatch;
20148/**
20149 * Returns a list of strings that _**do not match any**_ of the given `patterns`.
20150 *
20151 * ```js
20152 * const mm = require('micromatch');
20153 * // mm.not(list, patterns[, options]);
20154 *
20155 * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
20156 * //=> ['b.b', 'c.c']
20157 * ```
20158 * @param {Array} `list` Array of strings to match.
20159 * @param {String|Array} `patterns` One or more glob pattern to use for matching.
20160 * @param {Object} `options` See available [options](#options) for changing how matches are performed
20161 * @return {Array} Returns an array of strings that **do not match** the given patterns.
20162 * @api public
20163 */
20164micromatch.not = (list, patterns, options = {}) => {
20165 patterns = [].concat(patterns).map(String);
20166 let result = new Set();
20167 let items = [];
20168 let onResult = state => {
20169 if (options.onResult)
20170 options.onResult(state);
20171 items.push(state.output);
20172 };
20173 let matches = micromatch(list, patterns, Object.assign({}, options, { onResult }));
20174 for (let item of items) {
20175 if (!matches.includes(item)) {
20176 result.add(item);
20177 }
20178 }
20179 return [...result];
20180};
20181/**
20182 * Returns true if the given `string` contains the given pattern. Similar
20183 * to [.isMatch](#isMatch) but the pattern can match any part of the string.
20184 *
20185 * ```js
20186 * var mm = require('micromatch');
20187 * // mm.contains(string, pattern[, options]);
20188 *
20189 * console.log(mm.contains('aa/bb/cc', '*b'));
20190 * //=> true
20191 * console.log(mm.contains('aa/bb/cc', '*d'));
20192 * //=> false
20193 * ```
20194 * @param {String} `str` The string to match.
20195 * @param {String|Array} `patterns` Glob pattern to use for matching.
20196 * @param {Object} `options` See available [options](#options) for changing how matches are performed
20197 * @return {Boolean} Returns true if the patter matches any part of `str`.
20198 * @api public
20199 */
20200micromatch.contains = (str, pattern, options) => {
20201 if (typeof str !== 'string') {
20202 throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
20203 }
20204 if (Array.isArray(pattern)) {
20205 return pattern.some(p => micromatch.contains(str, p, options));
20206 }
20207 if (typeof pattern === 'string') {
20208 if (isEmptyString(str) || isEmptyString(pattern)) {
20209 return false;
20210 }
20211 if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
20212 return true;
20213 }
20214 }
20215 return micromatch.isMatch(str, pattern, Object.assign({}, options, { contains: true }));
20216};
20217/**
20218 * Filter the keys of the given object with the given `glob` pattern
20219 * and `options`. Does not attempt to match nested keys. If you need this feature,
20220 * use [glob-object][] instead.
20221 *
20222 * ```js
20223 * const mm = require('micromatch');
20224 * // mm.matchKeys(object, patterns[, options]);
20225 *
20226 * const obj = { aa: 'a', ab: 'b', ac: 'c' };
20227 * console.log(mm.matchKeys(obj, '*b'));
20228 * //=> { ab: 'b' }
20229 * ```
20230 * @param {Object} `object` The object with keys to filter.
20231 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
20232 * @param {Object} `options` See available [options](#options) for changing how matches are performed
20233 * @return {Object} Returns an object with only keys that match the given patterns.
20234 * @api public
20235 */
20236micromatch.matchKeys = (obj, patterns, options) => {
20237 if (!utils$2.isObject(obj)) {
20238 throw new TypeError('Expected the first argument to be an object');
20239 }
20240 let keys = micromatch(Object.keys(obj), patterns, options);
20241 let res = {};
20242 for (let key of keys)
20243 res[key] = obj[key];
20244 return res;
20245};
20246/**
20247 * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
20248 *
20249 * ```js
20250 * const mm = require('micromatch');
20251 * // mm.some(list, patterns[, options]);
20252 *
20253 * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
20254 * // true
20255 * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
20256 * // false
20257 * ```
20258 * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
20259 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
20260 * @param {Object} `options` See available [options](#options) for changing how matches are performed
20261 * @return {Boolean} Returns true if any patterns match `str`
20262 * @api public
20263 */
20264micromatch.some = (list, patterns, options) => {
20265 let items = [].concat(list);
20266 for (let pattern of [].concat(patterns)) {
20267 let isMatch = picomatch$1(String(pattern), options);
20268 if (items.some(item => isMatch(item))) {
20269 return true;
20270 }
20271 }
20272 return false;
20273};
20274/**
20275 * Returns true if every string in the given `list` matches
20276 * any of the given glob `patterns`.
20277 *
20278 * ```js
20279 * const mm = require('micromatch');
20280 * // mm.every(list, patterns[, options]);
20281 *
20282 * console.log(mm.every('foo.js', ['foo.js']));
20283 * // true
20284 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
20285 * // true
20286 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
20287 * // false
20288 * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
20289 * // false
20290 * ```
20291 * @param {String|Array} `list` The string or array of strings to test.
20292 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
20293 * @param {Object} `options` See available [options](#options) for changing how matches are performed
20294 * @return {Boolean} Returns true if any patterns match `str`
20295 * @api public
20296 */
20297micromatch.every = (list, patterns, options) => {
20298 let items = [].concat(list);
20299 for (let pattern of [].concat(patterns)) {
20300 let isMatch = picomatch$1(String(pattern), options);
20301 if (!items.every(item => isMatch(item))) {
20302 return false;
20303 }
20304 }
20305 return true;
20306};
20307/**
20308 * Returns true if **all** of the given `patterns` match
20309 * the specified string.
20310 *
20311 * ```js
20312 * const mm = require('micromatch');
20313 * // mm.all(string, patterns[, options]);
20314 *
20315 * console.log(mm.all('foo.js', ['foo.js']));
20316 * // true
20317 *
20318 * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
20319 * // false
20320 *
20321 * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
20322 * // true
20323 *
20324 * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
20325 * // true
20326 * ```
20327 * @param {String|Array} `str` The string to test.
20328 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
20329 * @param {Object} `options` See available [options](#options) for changing how matches are performed
20330 * @return {Boolean} Returns true if any patterns match `str`
20331 * @api public
20332 */
20333micromatch.all = (str, patterns, options) => {
20334 if (typeof str !== 'string') {
20335 throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
20336 }
20337 return [].concat(patterns).every(p => picomatch$1(p, options)(str));
20338};
20339/**
20340 * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
20341 *
20342 * ```js
20343 * const mm = require('micromatch');
20344 * // mm.capture(pattern, string[, options]);
20345 *
20346 * console.log(mm.capture('test/*.js', 'test/foo.js'));
20347 * //=> ['foo']
20348 * console.log(mm.capture('test/*.js', 'foo/bar.css'));
20349 * //=> null
20350 * ```
20351 * @param {String} `glob` Glob pattern to use for matching.
20352 * @param {String} `input` String to match
20353 * @param {Object} `options` See available [options](#options) for changing how matches are performed
20354 * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
20355 * @api public
20356 */
20357micromatch.capture = (glob, input, options) => {
20358 let posix = utils$2.isWindows(options);
20359 let regex = picomatch$1.makeRe(String(glob), Object.assign({}, options, { capture: true }));
20360 let match = regex.exec(posix ? utils$2.toPosixSlashes(input) : input);
20361 if (match) {
20362 return match.slice(1).map(v => v === void 0 ? '' : v);
20363 }
20364};
20365/**
20366 * Create a regular expression from the given glob `pattern`.
20367 *
20368 * ```js
20369 * const mm = require('micromatch');
20370 * // mm.makeRe(pattern[, options]);
20371 *
20372 * console.log(mm.makeRe('*.js'));
20373 * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
20374 * ```
20375 * @param {String} `pattern` A glob pattern to convert to regex.
20376 * @param {Object} `options`
20377 * @return {RegExp} Returns a regex created from the given pattern.
20378 * @api public
20379 */
20380micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);
20381/**
20382 * Scan a glob pattern to separate the pattern into segments. Used
20383 * by the [split](#split) method.
20384 *
20385 * ```js
20386 * const mm = require('micromatch');
20387 * const state = mm.scan(pattern[, options]);
20388 * ```
20389 * @param {String} `pattern`
20390 * @param {Object} `options`
20391 * @return {Object} Returns an object with
20392 * @api public
20393 */
20394micromatch.scan = (...args) => picomatch$1.scan(...args);
20395/**
20396 * Parse a glob pattern to create the source string for a regular
20397 * expression.
20398 *
20399 * ```js
20400 * const mm = require('micromatch');
20401 * const state = mm(pattern[, options]);
20402 * ```
20403 * @param {String} `glob`
20404 * @param {Object} `options`
20405 * @return {Object} Returns an object with useful properties and output to be used as regex source string.
20406 * @api public
20407 */
20408micromatch.parse = (patterns, options) => {
20409 let res = [];
20410 for (let pattern of [].concat(patterns || [])) {
20411 for (let str of braces_1(String(pattern), options)) {
20412 res.push(picomatch$1.parse(str, options));
20413 }
20414 }
20415 return res;
20416};
20417/**
20418 * Process the given brace `pattern`.
20419 *
20420 * ```js
20421 * const { braces } = require('micromatch');
20422 * console.log(braces('foo/{a,b,c}/bar'));
20423 * //=> [ 'foo/(a|b|c)/bar' ]
20424 *
20425 * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
20426 * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
20427 * ```
20428 * @param {String} `pattern` String with brace pattern to process.
20429 * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
20430 * @return {Array}
20431 * @api public
20432 */
20433micromatch.braces = (pattern, options) => {
20434 if (typeof pattern !== 'string')
20435 throw new TypeError('Expected a string');
20436 if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
20437 return [pattern];
20438 }
20439 return braces_1(pattern, options);
20440};
20441/**
20442 * Expand braces
20443 */
20444micromatch.braceExpand = (pattern, options) => {
20445 if (typeof pattern !== 'string')
20446 throw new TypeError('Expected a string');
20447 return micromatch.braces(pattern, Object.assign({}, options, { expand: true }));
20448};
20449/**
20450 * Expose micromatch
20451 */
20452var micromatch_1 = micromatch;
20453
20454function ensureArray$1(thing) {
20455 if (Array.isArray(thing))
20456 return thing;
20457 if (thing == undefined)
20458 return [];
20459 return [thing];
20460}
20461
20462function getMatcherString(id, resolutionBase) {
20463 if (resolutionBase === false) {
20464 return id;
20465 }
20466 return path.resolve(...(typeof resolutionBase === 'string' ? [resolutionBase, id] : [id]));
20467}
20468const createFilter = function createFilter(include, exclude, options) {
20469 const resolutionBase = options && options.resolve;
20470 const getMatcher = (id) => {
20471 return id instanceof RegExp
20472 ? id
20473 : {
20474 test: micromatch_1.matcher(getMatcherString(id, resolutionBase)
20475 .split(path.sep)
20476 .join('/'), { dot: true })
20477 };
20478 };
20479 const includeMatchers = ensureArray$1(include).map(getMatcher);
20480 const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
20481 return function (id) {
20482 if (typeof id !== 'string')
20483 return false;
20484 if (/\0/.test(id))
20485 return false;
20486 id = id.split(path.sep).join('/');
20487 for (let i = 0; i < excludeMatchers.length; ++i) {
20488 const matcher = excludeMatchers[i];
20489 if (matcher.test(id))
20490 return false;
20491 }
20492 for (let i = 0; i < includeMatchers.length; ++i) {
20493 const matcher = includeMatchers[i];
20494 if (matcher.test(id))
20495 return true;
20496 }
20497 return !includeMatchers.length;
20498 };
20499};
20500
20501let chokidar;
20502try {
20503 chokidar = index.relative('chokidar', process.cwd());
20504}
20505catch (err) {
20506 chokidar = null;
20507}
20508var chokidar$1 = chokidar;
20509
20510const opts = { encoding: 'utf-8', persistent: true };
20511const watchers = new Map();
20512function addTask(id, task, chokidarOptions, chokidarOptionsHash, isTransformDependency) {
20513 if (!watchers.has(chokidarOptionsHash))
20514 watchers.set(chokidarOptionsHash, new Map());
20515 const group = watchers.get(chokidarOptionsHash);
20516 const watcher = group.get(id) || new FileWatcher(id, chokidarOptions, group);
20517 if (!watcher.fsWatcher) {
20518 if (isTransformDependency)
20519 throw new Error(`Transform dependency ${id} does not exist.`);
20520 }
20521 else {
20522 watcher.addTask(task, isTransformDependency);
20523 }
20524}
20525function deleteTask(id, target, chokidarOptionsHash) {
20526 const group = watchers.get(chokidarOptionsHash);
20527 const watcher = group.get(id);
20528 if (watcher)
20529 watcher.deleteTask(target, group);
20530}
20531class FileWatcher {
20532 constructor(id, chokidarOptions, group) {
20533 this.id = id;
20534 this.tasks = new Set();
20535 this.transformDependencyTasks = new Set();
20536 let modifiedTime;
20537 try {
20538 const stats = fs.statSync(id);
20539 modifiedTime = +stats.mtime;
20540 }
20541 catch (err) {
20542 if (err.code === 'ENOENT') {
20543 // can't watch files that don't exist (e.g. injected
20544 // by plugins somehow)
20545 return;
20546 }
20547 else {
20548 throw err;
20549 }
20550 }
20551 const handleWatchEvent = (event) => {
20552 if (event === 'rename' || event === 'unlink') {
20553 this.close();
20554 group.delete(id);
20555 this.trigger(id);
20556 }
20557 else {
20558 let stats;
20559 try {
20560 stats = fs.statSync(id);
20561 }
20562 catch (err) {
20563 if (err.code === 'ENOENT') {
20564 modifiedTime = -1;
20565 this.trigger(id);
20566 return;
20567 }
20568 throw err;
20569 }
20570 // debounce
20571 if (+stats.mtime - modifiedTime > 15)
20572 this.trigger(id);
20573 }
20574 };
20575 this.fsWatcher = chokidarOptions
20576 ? chokidar$1.watch(id, chokidarOptions).on('all', handleWatchEvent)
20577 : fs.watch(id, opts, handleWatchEvent);
20578 group.set(id, this);
20579 }
20580 addTask(task, isTransformDependency = false) {
20581 if (isTransformDependency)
20582 this.transformDependencyTasks.add(task);
20583 else
20584 this.tasks.add(task);
20585 }
20586 close() {
20587 if (this.fsWatcher)
20588 this.fsWatcher.close();
20589 }
20590 deleteTask(task, group) {
20591 let deleted = this.tasks.delete(task);
20592 deleted = this.transformDependencyTasks.delete(task) || deleted;
20593 if (deleted && this.tasks.size === 0 && this.transformDependencyTasks.size === 0) {
20594 group.delete(this.id);
20595 this.close();
20596 }
20597 }
20598 trigger(id) {
20599 this.tasks.forEach(task => {
20600 task.invalidate(id, false);
20601 });
20602 this.transformDependencyTasks.forEach(task => {
20603 task.invalidate(id, true);
20604 });
20605 }
20606}
20607
20608const DELAY = 200;
20609class Watcher {
20610 constructor(configs) {
20611 this.buildTimeout = null;
20612 this.invalidatedIds = new Set();
20613 this.rerun = false;
20614 this.succeeded = false;
20615 this.emitter = new (class extends events.EventEmitter {
20616 constructor(close) {
20617 super();
20618 this.close = close;
20619 // Allows more than 10 bundles to be watched without
20620 // showing the `MaxListenersExceededWarning` to the user.
20621 this.setMaxListeners(Infinity);
20622 }
20623 })(this.close.bind(this));
20624 this.tasks = (Array.isArray(configs) ? configs : configs ? [configs] : []).map(config => new Task(this, config));
20625 this.running = true;
20626 process.nextTick(() => this.run());
20627 }
20628 close() {
20629 if (this.buildTimeout)
20630 clearTimeout(this.buildTimeout);
20631 this.tasks.forEach(task => {
20632 task.close();
20633 });
20634 this.emitter.removeAllListeners();
20635 }
20636 emit(event, value) {
20637 this.emitter.emit(event, value);
20638 }
20639 invalidate(id) {
20640 if (id) {
20641 this.invalidatedIds.add(id);
20642 }
20643 if (this.running) {
20644 this.rerun = true;
20645 return;
20646 }
20647 if (this.buildTimeout)
20648 clearTimeout(this.buildTimeout);
20649 this.buildTimeout = setTimeout(() => {
20650 this.buildTimeout = null;
20651 this.invalidatedIds.forEach(id => this.emit('change', id));
20652 this.invalidatedIds.clear();
20653 this.emit('restart');
20654 this.run();
20655 }, DELAY);
20656 }
20657 run() {
20658 this.running = true;
20659 this.emit('event', {
20660 code: 'START'
20661 });
20662 let taskPromise = Promise.resolve();
20663 for (const task of this.tasks)
20664 taskPromise = taskPromise.then(() => task.run());
20665 return taskPromise
20666 .then(() => {
20667 this.succeeded = true;
20668 this.running = false;
20669 this.emit('event', {
20670 code: 'END'
20671 });
20672 })
20673 .catch(error => {
20674 this.running = false;
20675 this.emit('event', {
20676 code: this.succeeded ? 'ERROR' : 'FATAL',
20677 error
20678 });
20679 })
20680 .then(() => {
20681 if (this.rerun) {
20682 this.rerun = false;
20683 this.invalidate();
20684 }
20685 });
20686 }
20687}
20688class Task {
20689 constructor(watcher, config) {
20690 this.watchFiles = [];
20691 this.invalidated = true;
20692 this.cache = null;
20693 this.watcher = watcher;
20694 this.closed = false;
20695 this.watched = new Set();
20696 const { inputOptions, outputOptions } = index.mergeOptions({
20697 config
20698 });
20699 this.inputOptions = inputOptions;
20700 this.outputs = outputOptions;
20701 this.outputFiles = this.outputs.map(output => {
20702 if (output.file || output.dir)
20703 return path.resolve(output.file || output.dir);
20704 return undefined;
20705 });
20706 const watchOptions = inputOptions.watch || {};
20707 if ('useChokidar' in watchOptions)
20708 watchOptions.chokidar = watchOptions.useChokidar;
20709 let chokidarOptions = 'chokidar' in watchOptions ? watchOptions.chokidar : !!chokidar$1;
20710 if (chokidarOptions) {
20711 chokidarOptions = Object.assign({}, (chokidarOptions === true ? {} : chokidarOptions), { disableGlobbing: true, ignoreInitial: true });
20712 }
20713 if (chokidarOptions && !chokidar$1) {
20714 throw new Error(`watch.chokidar was provided, but chokidar could not be found. Have you installed it?`);
20715 }
20716 this.chokidarOptions = chokidarOptions;
20717 this.chokidarOptionsHash = JSON.stringify(chokidarOptions);
20718 this.filter = createFilter(watchOptions.include, watchOptions.exclude);
20719 }
20720 close() {
20721 this.closed = true;
20722 this.watched.forEach(id => {
20723 deleteTask(id, this, this.chokidarOptionsHash);
20724 });
20725 }
20726 invalidate(id, isTransformDependency) {
20727 this.invalidated = true;
20728 if (isTransformDependency) {
20729 this.cache.modules.forEach(module => {
20730 if (!module.transformDependencies || module.transformDependencies.indexOf(id) === -1)
20731 return;
20732 // effective invalidation
20733 module.originalCode = null;
20734 });
20735 }
20736 this.watcher.invalidate(id);
20737 }
20738 run() {
20739 if (!this.invalidated)
20740 return;
20741 this.invalidated = false;
20742 const options = Object.assign({}, this.inputOptions, { cache: this.cache });
20743 const start = Date.now();
20744 this.watcher.emit('event', {
20745 code: 'BUNDLE_START',
20746 input: this.inputOptions.input,
20747 output: this.outputFiles
20748 });
20749 setWatcher(this.watcher.emitter);
20750 return rollup(options)
20751 .then(result => {
20752 if (this.closed)
20753 return undefined;
20754 const previouslyWatched = this.watched;
20755 const watched = (this.watched = new Set());
20756 this.cache = result.cache;
20757 this.watchFiles = result.watchFiles;
20758 for (const module of this.cache.modules) {
20759 if (module.transformDependencies) {
20760 module.transformDependencies.forEach(depId => {
20761 watched.add(depId);
20762 this.watchFile(depId, true);
20763 });
20764 }
20765 }
20766 for (const id of this.watchFiles) {
20767 watched.add(id);
20768 this.watchFile(id);
20769 }
20770 for (const id of previouslyWatched) {
20771 if (!watched.has(id))
20772 deleteTask(id, this, this.chokidarOptionsHash);
20773 }
20774 return Promise.all(this.outputs.map(output => result.write(output))).then(() => result);
20775 })
20776 .then((result) => {
20777 this.watcher.emit('event', {
20778 code: 'BUNDLE_END',
20779 duration: Date.now() - start,
20780 input: this.inputOptions.input,
20781 output: this.outputFiles,
20782 result
20783 });
20784 })
20785 .catch((error) => {
20786 if (this.closed)
20787 return;
20788 if (this.cache) {
20789 // this is necessary to ensure that any 'renamed' files
20790 // continue to be watched following an error
20791 if (this.cache.modules) {
20792 this.cache.modules.forEach(module => {
20793 if (module.transformDependencies) {
20794 module.transformDependencies.forEach(depId => {
20795 this.watchFile(depId, true);
20796 });
20797 }
20798 });
20799 }
20800 this.watchFiles.forEach(id => {
20801 this.watchFile(id);
20802 });
20803 }
20804 throw error;
20805 });
20806 }
20807 watchFile(id, isTransformDependency = false) {
20808 if (!this.filter(id))
20809 return;
20810 if (this.outputFiles.some(file => file === id)) {
20811 throw new Error('Cannot import the generated bundle');
20812 }
20813 // this is necessary to ensure that any 'renamed' files
20814 // continue to be watched following an error
20815 addTask(id, this, this.chokidarOptions, this.chokidarOptionsHash, isTransformDependency);
20816 }
20817}
20818function watch(configs) {
20819 return new Watcher(configs).emitter;
20820}
20821
20822exports.VERSION = index.version;
20823exports.rollup = rollup;
20824exports.watch = watch;
20825//# sourceMappingURL=rollup.js.map