UNPKG

628 kBJavaScriptView Raw
1/*
2 @license
3 Rollup.js v1.25.2
4 Wed, 23 Oct 2019 05:48:50 GMT - commit b123169865e670d3b961d5afaef090aa4e019fef
5
6
7 https://github.com/rollup/rollup
8
9 Released under the MIT License.
10*/
11import util from 'util';
12import path, { relative as relative$1, extname, basename, dirname, resolve, sep } from 'path';
13import { writeFile as writeFile$1, readdirSync, mkdirSync, readFile as readFile$1, lstatSync, realpathSync, statSync, watch as watch$1 } from 'fs';
14import * as acorn__default from 'acorn';
15import { Parser } from 'acorn';
16import { EventEmitter } from 'events';
17import module from 'module';
18
19/*! *****************************************************************************
20Copyright (c) Microsoft Corporation. All rights reserved.
21Licensed under the Apache License, Version 2.0 (the "License"); you may not use
22this file except in compliance with the License. You may obtain a copy of the
23License at http://www.apache.org/licenses/LICENSE-2.0
24
25THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
26KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
27WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
28MERCHANTABLITY OR NON-INFRINGEMENT.
29
30See the Apache Version 2.0 License for specific language governing permissions
31and limitations under the License.
32***************************************************************************** */
33function __awaiter(thisArg, _arguments, P, generator) {
34 return new (P || (P = Promise))(function (resolve, reject) {
35 function fulfilled(value) { try {
36 step(generator.next(value));
37 }
38 catch (e) {
39 reject(e);
40 } }
41 function rejected(value) { try {
42 step(generator["throw"](value));
43 }
44 catch (e) {
45 reject(e);
46 } }
47 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
48 step((generator = generator.apply(thisArg, _arguments || [])).next());
49 });
50}
51
52var version = "1.25.2";
53
54var minimalisticAssert = assert;
55function assert(val, msg) {
56 if (!val)
57 throw new Error(msg || 'Assertion failed');
58}
59assert.equal = function assertEqual(l, r, msg) {
60 if (l != r)
61 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
62};
63
64function createCommonjsModule(fn, module) {
65 return module = { exports: {} }, fn(module, module.exports), module.exports;
66}
67
68var inherits_browser = createCommonjsModule(function (module) {
69 if (typeof Object.create === 'function') {
70 // implementation from standard node.js 'util' module
71 module.exports = function inherits(ctor, superCtor) {
72 ctor.super_ = superCtor;
73 ctor.prototype = Object.create(superCtor.prototype, {
74 constructor: {
75 value: ctor,
76 enumerable: false,
77 writable: true,
78 configurable: true
79 }
80 });
81 };
82 }
83 else {
84 // old school shim for old browsers
85 module.exports = function inherits(ctor, superCtor) {
86 ctor.super_ = superCtor;
87 var TempCtor = function () { };
88 TempCtor.prototype = superCtor.prototype;
89 ctor.prototype = new TempCtor();
90 ctor.prototype.constructor = ctor;
91 };
92 }
93});
94
95var inherits = createCommonjsModule(function (module) {
96 try {
97 var util$1 = util;
98 if (typeof util$1.inherits !== 'function')
99 throw '';
100 module.exports = util$1.inherits;
101 }
102 catch (e) {
103 module.exports = inherits_browser;
104 }
105});
106
107var inherits_1 = inherits;
108function isSurrogatePair(msg, i) {
109 if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
110 return false;
111 }
112 if (i < 0 || i + 1 >= msg.length) {
113 return false;
114 }
115 return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
116}
117function toArray(msg, enc) {
118 if (Array.isArray(msg))
119 return msg.slice();
120 if (!msg)
121 return [];
122 var res = [];
123 if (typeof msg === 'string') {
124 if (!enc) {
125 // Inspired by stringToUtf8ByteArray() in closure-library by Google
126 // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
127 // Apache License 2.0
128 // https://github.com/google/closure-library/blob/master/LICENSE
129 var p = 0;
130 for (var i = 0; i < msg.length; i++) {
131 var c = msg.charCodeAt(i);
132 if (c < 128) {
133 res[p++] = c;
134 }
135 else if (c < 2048) {
136 res[p++] = (c >> 6) | 192;
137 res[p++] = (c & 63) | 128;
138 }
139 else if (isSurrogatePair(msg, i)) {
140 c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
141 res[p++] = (c >> 18) | 240;
142 res[p++] = ((c >> 12) & 63) | 128;
143 res[p++] = ((c >> 6) & 63) | 128;
144 res[p++] = (c & 63) | 128;
145 }
146 else {
147 res[p++] = (c >> 12) | 224;
148 res[p++] = ((c >> 6) & 63) | 128;
149 res[p++] = (c & 63) | 128;
150 }
151 }
152 }
153 else if (enc === 'hex') {
154 msg = msg.replace(/[^a-z0-9]+/ig, '');
155 if (msg.length % 2 !== 0)
156 msg = '0' + msg;
157 for (i = 0; i < msg.length; i += 2)
158 res.push(parseInt(msg[i] + msg[i + 1], 16));
159 }
160 }
161 else {
162 for (i = 0; i < msg.length; i++)
163 res[i] = msg[i] | 0;
164 }
165 return res;
166}
167var toArray_1 = toArray;
168function toHex(msg) {
169 var res = '';
170 for (var i = 0; i < msg.length; i++)
171 res += zero2(msg[i].toString(16));
172 return res;
173}
174var toHex_1 = toHex;
175function htonl(w) {
176 var res = (w >>> 24) |
177 ((w >>> 8) & 0xff00) |
178 ((w << 8) & 0xff0000) |
179 ((w & 0xff) << 24);
180 return res >>> 0;
181}
182var htonl_1 = htonl;
183function toHex32(msg, endian) {
184 var res = '';
185 for (var i = 0; i < msg.length; i++) {
186 var w = msg[i];
187 if (endian === 'little')
188 w = htonl(w);
189 res += zero8(w.toString(16));
190 }
191 return res;
192}
193var toHex32_1 = toHex32;
194function zero2(word) {
195 if (word.length === 1)
196 return '0' + word;
197 else
198 return word;
199}
200var zero2_1 = zero2;
201function zero8(word) {
202 if (word.length === 7)
203 return '0' + word;
204 else if (word.length === 6)
205 return '00' + word;
206 else if (word.length === 5)
207 return '000' + word;
208 else if (word.length === 4)
209 return '0000' + word;
210 else if (word.length === 3)
211 return '00000' + word;
212 else if (word.length === 2)
213 return '000000' + word;
214 else if (word.length === 1)
215 return '0000000' + word;
216 else
217 return word;
218}
219var zero8_1 = zero8;
220function join32(msg, start, end, endian) {
221 var len = end - start;
222 minimalisticAssert(len % 4 === 0);
223 var res = new Array(len / 4);
224 for (var i = 0, k = start; i < res.length; i++, k += 4) {
225 var w;
226 if (endian === 'big')
227 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
228 else
229 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
230 res[i] = w >>> 0;
231 }
232 return res;
233}
234var join32_1 = join32;
235function split32(msg, endian) {
236 var res = new Array(msg.length * 4);
237 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
238 var m = msg[i];
239 if (endian === 'big') {
240 res[k] = m >>> 24;
241 res[k + 1] = (m >>> 16) & 0xff;
242 res[k + 2] = (m >>> 8) & 0xff;
243 res[k + 3] = m & 0xff;
244 }
245 else {
246 res[k + 3] = m >>> 24;
247 res[k + 2] = (m >>> 16) & 0xff;
248 res[k + 1] = (m >>> 8) & 0xff;
249 res[k] = m & 0xff;
250 }
251 }
252 return res;
253}
254var split32_1 = split32;
255function rotr32(w, b) {
256 return (w >>> b) | (w << (32 - b));
257}
258var rotr32_1 = rotr32;
259function rotl32(w, b) {
260 return (w << b) | (w >>> (32 - b));
261}
262var rotl32_1 = rotl32;
263function sum32(a, b) {
264 return (a + b) >>> 0;
265}
266var sum32_1 = sum32;
267function sum32_3(a, b, c) {
268 return (a + b + c) >>> 0;
269}
270var sum32_3_1 = sum32_3;
271function sum32_4(a, b, c, d) {
272 return (a + b + c + d) >>> 0;
273}
274var sum32_4_1 = sum32_4;
275function sum32_5(a, b, c, d, e) {
276 return (a + b + c + d + e) >>> 0;
277}
278var sum32_5_1 = sum32_5;
279function sum64(buf, pos, ah, al) {
280 var bh = buf[pos];
281 var bl = buf[pos + 1];
282 var lo = (al + bl) >>> 0;
283 var hi = (lo < al ? 1 : 0) + ah + bh;
284 buf[pos] = hi >>> 0;
285 buf[pos + 1] = lo;
286}
287var sum64_1 = sum64;
288function sum64_hi(ah, al, bh, bl) {
289 var lo = (al + bl) >>> 0;
290 var hi = (lo < al ? 1 : 0) + ah + bh;
291 return hi >>> 0;
292}
293var sum64_hi_1 = sum64_hi;
294function sum64_lo(ah, al, bh, bl) {
295 var lo = al + bl;
296 return lo >>> 0;
297}
298var sum64_lo_1 = sum64_lo;
299function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
300 var carry = 0;
301 var lo = al;
302 lo = (lo + bl) >>> 0;
303 carry += lo < al ? 1 : 0;
304 lo = (lo + cl) >>> 0;
305 carry += lo < cl ? 1 : 0;
306 lo = (lo + dl) >>> 0;
307 carry += lo < dl ? 1 : 0;
308 var hi = ah + bh + ch + dh + carry;
309 return hi >>> 0;
310}
311var sum64_4_hi_1 = sum64_4_hi;
312function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
313 var lo = al + bl + cl + dl;
314 return lo >>> 0;
315}
316var sum64_4_lo_1 = sum64_4_lo;
317function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
318 var carry = 0;
319 var lo = al;
320 lo = (lo + bl) >>> 0;
321 carry += lo < al ? 1 : 0;
322 lo = (lo + cl) >>> 0;
323 carry += lo < cl ? 1 : 0;
324 lo = (lo + dl) >>> 0;
325 carry += lo < dl ? 1 : 0;
326 lo = (lo + el) >>> 0;
327 carry += lo < el ? 1 : 0;
328 var hi = ah + bh + ch + dh + eh + carry;
329 return hi >>> 0;
330}
331var sum64_5_hi_1 = sum64_5_hi;
332function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
333 var lo = al + bl + cl + dl + el;
334 return lo >>> 0;
335}
336var sum64_5_lo_1 = sum64_5_lo;
337function rotr64_hi(ah, al, num) {
338 var r = (al << (32 - num)) | (ah >>> num);
339 return r >>> 0;
340}
341var rotr64_hi_1 = rotr64_hi;
342function rotr64_lo(ah, al, num) {
343 var r = (ah << (32 - num)) | (al >>> num);
344 return r >>> 0;
345}
346var rotr64_lo_1 = rotr64_lo;
347function shr64_hi(ah, al, num) {
348 return ah >>> num;
349}
350var shr64_hi_1 = shr64_hi;
351function shr64_lo(ah, al, num) {
352 var r = (ah << (32 - num)) | (al >>> num);
353 return r >>> 0;
354}
355var shr64_lo_1 = shr64_lo;
356var utils = {
357 inherits: inherits_1,
358 toArray: toArray_1,
359 toHex: toHex_1,
360 htonl: htonl_1,
361 toHex32: toHex32_1,
362 zero2: zero2_1,
363 zero8: zero8_1,
364 join32: join32_1,
365 split32: split32_1,
366 rotr32: rotr32_1,
367 rotl32: rotl32_1,
368 sum32: sum32_1,
369 sum32_3: sum32_3_1,
370 sum32_4: sum32_4_1,
371 sum32_5: sum32_5_1,
372 sum64: sum64_1,
373 sum64_hi: sum64_hi_1,
374 sum64_lo: sum64_lo_1,
375 sum64_4_hi: sum64_4_hi_1,
376 sum64_4_lo: sum64_4_lo_1,
377 sum64_5_hi: sum64_5_hi_1,
378 sum64_5_lo: sum64_5_lo_1,
379 rotr64_hi: rotr64_hi_1,
380 rotr64_lo: rotr64_lo_1,
381 shr64_hi: shr64_hi_1,
382 shr64_lo: shr64_lo_1
383};
384
385function BlockHash() {
386 this.pending = null;
387 this.pendingTotal = 0;
388 this.blockSize = this.constructor.blockSize;
389 this.outSize = this.constructor.outSize;
390 this.hmacStrength = this.constructor.hmacStrength;
391 this.padLength = this.constructor.padLength / 8;
392 this.endian = 'big';
393 this._delta8 = this.blockSize / 8;
394 this._delta32 = this.blockSize / 32;
395}
396var BlockHash_1 = BlockHash;
397BlockHash.prototype.update = function update(msg, enc) {
398 // Convert message to array, pad it, and join into 32bit blocks
399 msg = utils.toArray(msg, enc);
400 if (!this.pending)
401 this.pending = msg;
402 else
403 this.pending = this.pending.concat(msg);
404 this.pendingTotal += msg.length;
405 // Enough data, try updating
406 if (this.pending.length >= this._delta8) {
407 msg = this.pending;
408 // Process pending data in blocks
409 var r = msg.length % this._delta8;
410 this.pending = msg.slice(msg.length - r, msg.length);
411 if (this.pending.length === 0)
412 this.pending = null;
413 msg = utils.join32(msg, 0, msg.length - r, this.endian);
414 for (var i = 0; i < msg.length; i += this._delta32)
415 this._update(msg, i, i + this._delta32);
416 }
417 return this;
418};
419BlockHash.prototype.digest = function digest(enc) {
420 this.update(this._pad());
421 minimalisticAssert(this.pending === null);
422 return this._digest(enc);
423};
424BlockHash.prototype._pad = function pad() {
425 var len = this.pendingTotal;
426 var bytes = this._delta8;
427 var k = bytes - ((len + this.padLength) % bytes);
428 var res = new Array(k + this.padLength);
429 res[0] = 0x80;
430 for (var i = 1; i < k; i++)
431 res[i] = 0;
432 // Append length
433 len <<= 3;
434 if (this.endian === 'big') {
435 for (var t = 8; t < this.padLength; t++)
436 res[i++] = 0;
437 res[i++] = 0;
438 res[i++] = 0;
439 res[i++] = 0;
440 res[i++] = 0;
441 res[i++] = (len >>> 24) & 0xff;
442 res[i++] = (len >>> 16) & 0xff;
443 res[i++] = (len >>> 8) & 0xff;
444 res[i++] = len & 0xff;
445 }
446 else {
447 res[i++] = len & 0xff;
448 res[i++] = (len >>> 8) & 0xff;
449 res[i++] = (len >>> 16) & 0xff;
450 res[i++] = (len >>> 24) & 0xff;
451 res[i++] = 0;
452 res[i++] = 0;
453 res[i++] = 0;
454 res[i++] = 0;
455 for (t = 8; t < this.padLength; t++)
456 res[i++] = 0;
457 }
458 return res;
459};
460var common = {
461 BlockHash: BlockHash_1
462};
463
464var rotr32$1 = utils.rotr32;
465function ft_1(s, x, y, z) {
466 if (s === 0)
467 return ch32(x, y, z);
468 if (s === 1 || s === 3)
469 return p32(x, y, z);
470 if (s === 2)
471 return maj32(x, y, z);
472}
473var ft_1_1 = ft_1;
474function ch32(x, y, z) {
475 return (x & y) ^ ((~x) & z);
476}
477var ch32_1 = ch32;
478function maj32(x, y, z) {
479 return (x & y) ^ (x & z) ^ (y & z);
480}
481var maj32_1 = maj32;
482function p32(x, y, z) {
483 return x ^ y ^ z;
484}
485var p32_1 = p32;
486function s0_256(x) {
487 return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22);
488}
489var s0_256_1 = s0_256;
490function s1_256(x) {
491 return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25);
492}
493var s1_256_1 = s1_256;
494function g0_256(x) {
495 return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3);
496}
497var g0_256_1 = g0_256;
498function g1_256(x) {
499 return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10);
500}
501var g1_256_1 = g1_256;
502var common$1 = {
503 ft_1: ft_1_1,
504 ch32: ch32_1,
505 maj32: maj32_1,
506 p32: p32_1,
507 s0_256: s0_256_1,
508 s1_256: s1_256_1,
509 g0_256: g0_256_1,
510 g1_256: g1_256_1
511};
512
513var sum32$1 = utils.sum32;
514var sum32_4$1 = utils.sum32_4;
515var sum32_5$1 = utils.sum32_5;
516var ch32$1 = common$1.ch32;
517var maj32$1 = common$1.maj32;
518var s0_256$1 = common$1.s0_256;
519var s1_256$1 = common$1.s1_256;
520var g0_256$1 = common$1.g0_256;
521var g1_256$1 = common$1.g1_256;
522var BlockHash$1 = common.BlockHash;
523var sha256_K = [
524 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
525 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
526 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
527 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
528 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
529 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
530 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
531 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
532 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
533 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
534 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
535 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
536 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
537 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
538 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
539 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
540];
541function SHA256() {
542 if (!(this instanceof SHA256))
543 return new SHA256();
544 BlockHash$1.call(this);
545 this.h = [
546 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
547 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
548 ];
549 this.k = sha256_K;
550 this.W = new Array(64);
551}
552utils.inherits(SHA256, BlockHash$1);
553var _256 = SHA256;
554SHA256.blockSize = 512;
555SHA256.outSize = 256;
556SHA256.hmacStrength = 192;
557SHA256.padLength = 64;
558SHA256.prototype._update = function _update(msg, start) {
559 var W = this.W;
560 for (var i = 0; i < 16; i++)
561 W[i] = msg[start + i];
562 for (; i < W.length; i++)
563 W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]);
564 var a = this.h[0];
565 var b = this.h[1];
566 var c = this.h[2];
567 var d = this.h[3];
568 var e = this.h[4];
569 var f = this.h[5];
570 var g = this.h[6];
571 var h = this.h[7];
572 minimalisticAssert(this.k.length === W.length);
573 for (i = 0; i < W.length; i++) {
574 var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]);
575 var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c));
576 h = g;
577 g = f;
578 f = e;
579 e = sum32$1(d, T1);
580 d = c;
581 c = b;
582 b = a;
583 a = sum32$1(T1, T2);
584 }
585 this.h[0] = sum32$1(this.h[0], a);
586 this.h[1] = sum32$1(this.h[1], b);
587 this.h[2] = sum32$1(this.h[2], c);
588 this.h[3] = sum32$1(this.h[3], d);
589 this.h[4] = sum32$1(this.h[4], e);
590 this.h[5] = sum32$1(this.h[5], f);
591 this.h[6] = sum32$1(this.h[6], g);
592 this.h[7] = sum32$1(this.h[7], h);
593};
594SHA256.prototype._digest = function digest(enc) {
595 if (enc === 'hex')
596 return utils.toHex32(this.h, 'big');
597 else
598 return utils.split32(this.h, 'big');
599};
600
601var charToInteger = {};
602var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
603for (var i = 0; i < chars.length; i++) {
604 charToInteger[chars.charCodeAt(i)] = i;
605}
606function decode(mappings) {
607 var generatedCodeColumn = 0; // first field
608 var sourceFileIndex = 0; // second field
609 var sourceCodeLine = 0; // third field
610 var sourceCodeColumn = 0; // fourth field
611 var nameIndex = 0; // fifth field
612 var decoded = [];
613 var line = [];
614 var segment = [];
615 for (var i = 0, j = 0, shift = 0, value = 0, len = mappings.length; i < len; i++) {
616 var c = mappings.charCodeAt(i);
617 if (c === 44) { // ","
618 if (segment.length)
619 line.push(segment);
620 segment = [];
621 j = 0;
622 }
623 else if (c === 59) { // ";"
624 if (segment.length)
625 line.push(segment);
626 segment = [];
627 j = 0;
628 decoded.push(line);
629 line = [];
630 generatedCodeColumn = 0;
631 }
632 else {
633 var integer = charToInteger[c];
634 if (integer === undefined) {
635 throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
636 }
637 var hasContinuationBit = integer & 32;
638 integer &= 31;
639 value += integer << shift;
640 if (hasContinuationBit) {
641 shift += 5;
642 }
643 else {
644 var shouldNegate = value & 1;
645 value >>>= 1;
646 if (shouldNegate) {
647 value = -value;
648 if (value === 0)
649 value = -0x80000000;
650 }
651 if (j == 0) {
652 generatedCodeColumn += value;
653 segment.push(generatedCodeColumn);
654 }
655 else if (j === 1) {
656 sourceFileIndex += value;
657 segment.push(sourceFileIndex);
658 }
659 else if (j === 2) {
660 sourceCodeLine += value;
661 segment.push(sourceCodeLine);
662 }
663 else if (j === 3) {
664 sourceCodeColumn += value;
665 segment.push(sourceCodeColumn);
666 }
667 else if (j === 4) {
668 nameIndex += value;
669 segment.push(nameIndex);
670 }
671 j++;
672 value = shift = 0; // reset
673 }
674 }
675 }
676 if (segment.length)
677 line.push(segment);
678 decoded.push(line);
679 return decoded;
680}
681function encode(decoded) {
682 var sourceFileIndex = 0; // second field
683 var sourceCodeLine = 0; // third field
684 var sourceCodeColumn = 0; // fourth field
685 var nameIndex = 0; // fifth field
686 var mappings = '';
687 for (var i = 0; i < decoded.length; i++) {
688 var line = decoded[i];
689 if (i > 0)
690 mappings += ';';
691 if (line.length === 0)
692 continue;
693 var generatedCodeColumn = 0; // first field
694 var lineMappings = [];
695 for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
696 var segment = line_1[_i];
697 var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
698 generatedCodeColumn = segment[0];
699 if (segment.length > 1) {
700 segmentMappings +=
701 encodeInteger(segment[1] - sourceFileIndex) +
702 encodeInteger(segment[2] - sourceCodeLine) +
703 encodeInteger(segment[3] - sourceCodeColumn);
704 sourceFileIndex = segment[1];
705 sourceCodeLine = segment[2];
706 sourceCodeColumn = segment[3];
707 }
708 if (segment.length === 5) {
709 segmentMappings += encodeInteger(segment[4] - nameIndex);
710 nameIndex = segment[4];
711 }
712 lineMappings.push(segmentMappings);
713 }
714 mappings += lineMappings.join(',');
715 }
716 return mappings;
717}
718function encodeInteger(num) {
719 var result = '';
720 num = num < 0 ? (-num << 1) | 1 : num << 1;
721 do {
722 var clamped = num & 31;
723 num >>>= 5;
724 if (num > 0) {
725 clamped |= 32;
726 }
727 result += chars[clamped];
728 } while (num > 0);
729 return result;
730}
731
732var Chunk = function Chunk(start, end, content) {
733 this.start = start;
734 this.end = end;
735 this.original = content;
736 this.intro = '';
737 this.outro = '';
738 this.content = content;
739 this.storeName = false;
740 this.edited = false;
741 // we make these non-enumerable, for sanity while debugging
742 Object.defineProperties(this, {
743 previous: { writable: true, value: null },
744 next: { writable: true, value: null }
745 });
746};
747Chunk.prototype.appendLeft = function appendLeft(content) {
748 this.outro += content;
749};
750Chunk.prototype.appendRight = function appendRight(content) {
751 this.intro = this.intro + content;
752};
753Chunk.prototype.clone = function clone() {
754 var chunk = new Chunk(this.start, this.end, this.original);
755 chunk.intro = this.intro;
756 chunk.outro = this.outro;
757 chunk.content = this.content;
758 chunk.storeName = this.storeName;
759 chunk.edited = this.edited;
760 return chunk;
761};
762Chunk.prototype.contains = function contains(index) {
763 return this.start < index && index < this.end;
764};
765Chunk.prototype.eachNext = function eachNext(fn) {
766 var chunk = this;
767 while (chunk) {
768 fn(chunk);
769 chunk = chunk.next;
770 }
771};
772Chunk.prototype.eachPrevious = function eachPrevious(fn) {
773 var chunk = this;
774 while (chunk) {
775 fn(chunk);
776 chunk = chunk.previous;
777 }
778};
779Chunk.prototype.edit = function edit(content, storeName, contentOnly) {
780 this.content = content;
781 if (!contentOnly) {
782 this.intro = '';
783 this.outro = '';
784 }
785 this.storeName = storeName;
786 this.edited = true;
787 return this;
788};
789Chunk.prototype.prependLeft = function prependLeft(content) {
790 this.outro = content + this.outro;
791};
792Chunk.prototype.prependRight = function prependRight(content) {
793 this.intro = content + this.intro;
794};
795Chunk.prototype.split = function split(index) {
796 var sliceIndex = index - this.start;
797 var originalBefore = this.original.slice(0, sliceIndex);
798 var originalAfter = this.original.slice(sliceIndex);
799 this.original = originalBefore;
800 var newChunk = new Chunk(index, this.end, originalAfter);
801 newChunk.outro = this.outro;
802 this.outro = '';
803 this.end = index;
804 if (this.edited) {
805 // TODO is this block necessary?...
806 newChunk.edit('', false);
807 this.content = '';
808 }
809 else {
810 this.content = originalBefore;
811 }
812 newChunk.next = this.next;
813 if (newChunk.next) {
814 newChunk.next.previous = newChunk;
815 }
816 newChunk.previous = this;
817 this.next = newChunk;
818 return newChunk;
819};
820Chunk.prototype.toString = function toString() {
821 return this.intro + this.content + this.outro;
822};
823Chunk.prototype.trimEnd = function trimEnd(rx) {
824 this.outro = this.outro.replace(rx, '');
825 if (this.outro.length) {
826 return true;
827 }
828 var trimmed = this.content.replace(rx, '');
829 if (trimmed.length) {
830 if (trimmed !== this.content) {
831 this.split(this.start + trimmed.length).edit('', undefined, true);
832 }
833 return true;
834 }
835 else {
836 this.edit('', undefined, true);
837 this.intro = this.intro.replace(rx, '');
838 if (this.intro.length) {
839 return true;
840 }
841 }
842};
843Chunk.prototype.trimStart = function trimStart(rx) {
844 this.intro = this.intro.replace(rx, '');
845 if (this.intro.length) {
846 return true;
847 }
848 var trimmed = this.content.replace(rx, '');
849 if (trimmed.length) {
850 if (trimmed !== this.content) {
851 this.split(this.end - trimmed.length);
852 this.edit('', undefined, true);
853 }
854 return true;
855 }
856 else {
857 this.edit('', undefined, true);
858 this.outro = this.outro.replace(rx, '');
859 if (this.outro.length) {
860 return true;
861 }
862 }
863};
864var btoa = function () {
865 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
866};
867if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
868 btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
869}
870else if (typeof Buffer === 'function') {
871 btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
872}
873var SourceMap = function SourceMap(properties) {
874 this.version = 3;
875 this.file = properties.file;
876 this.sources = properties.sources;
877 this.sourcesContent = properties.sourcesContent;
878 this.names = properties.names;
879 this.mappings = encode(properties.mappings);
880};
881SourceMap.prototype.toString = function toString() {
882 return JSON.stringify(this);
883};
884SourceMap.prototype.toUrl = function toUrl() {
885 return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
886};
887function guessIndent(code) {
888 var lines = code.split('\n');
889 var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
890 var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
891 if (tabbed.length === 0 && spaced.length === 0) {
892 return null;
893 }
894 // More lines tabbed than spaced? Assume tabs, and
895 // default to tabs in the case of a tie (or nothing
896 // to go on)
897 if (tabbed.length >= spaced.length) {
898 return '\t';
899 }
900 // Otherwise, we need to guess the multiple
901 var min = spaced.reduce(function (previous, current) {
902 var numSpaces = /^ +/.exec(current)[0].length;
903 return Math.min(numSpaces, previous);
904 }, Infinity);
905 return new Array(min + 1).join(' ');
906}
907function getRelativePath(from, to) {
908 var fromParts = from.split(/[/\\]/);
909 var toParts = to.split(/[/\\]/);
910 fromParts.pop(); // get dirname
911 while (fromParts[0] === toParts[0]) {
912 fromParts.shift();
913 toParts.shift();
914 }
915 if (fromParts.length) {
916 var i = fromParts.length;
917 while (i--) {
918 fromParts[i] = '..';
919 }
920 }
921 return fromParts.concat(toParts).join('/');
922}
923var toString = Object.prototype.toString;
924function isObject(thing) {
925 return toString.call(thing) === '[object Object]';
926}
927function getLocator(source) {
928 var originalLines = source.split('\n');
929 var lineOffsets = [];
930 for (var i = 0, pos = 0; i < originalLines.length; i++) {
931 lineOffsets.push(pos);
932 pos += originalLines[i].length + 1;
933 }
934 return function locate(index) {
935 var i = 0;
936 var j = lineOffsets.length;
937 while (i < j) {
938 var m = (i + j) >> 1;
939 if (index < lineOffsets[m]) {
940 j = m;
941 }
942 else {
943 i = m + 1;
944 }
945 }
946 var line = i - 1;
947 var column = index - lineOffsets[line];
948 return { line: line, column: column };
949 };
950}
951var Mappings = function Mappings(hires) {
952 this.hires = hires;
953 this.generatedCodeLine = 0;
954 this.generatedCodeColumn = 0;
955 this.raw = [];
956 this.rawSegments = this.raw[this.generatedCodeLine] = [];
957 this.pending = null;
958};
959Mappings.prototype.addEdit = function addEdit(sourceIndex, content, loc, nameIndex) {
960 if (content.length) {
961 var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
962 if (nameIndex >= 0) {
963 segment.push(nameIndex);
964 }
965 this.rawSegments.push(segment);
966 }
967 else if (this.pending) {
968 this.rawSegments.push(this.pending);
969 }
970 this.advance(content);
971 this.pending = null;
972};
973Mappings.prototype.addUneditedChunk = function addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
974 var this$1 = this;
975 var originalCharIndex = chunk.start;
976 var first = true;
977 while (originalCharIndex < chunk.end) {
978 if (this$1.hires || first || sourcemapLocations[originalCharIndex]) {
979 this$1.rawSegments.push([this$1.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
980 }
981 if (original[originalCharIndex] === '\n') {
982 loc.line += 1;
983 loc.column = 0;
984 this$1.generatedCodeLine += 1;
985 this$1.raw[this$1.generatedCodeLine] = this$1.rawSegments = [];
986 this$1.generatedCodeColumn = 0;
987 }
988 else {
989 loc.column += 1;
990 this$1.generatedCodeColumn += 1;
991 }
992 originalCharIndex += 1;
993 first = false;
994 }
995 this.pending = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
996};
997Mappings.prototype.advance = function advance(str) {
998 var this$1 = this;
999 if (!str) {
1000 return;
1001 }
1002 var lines = str.split('\n');
1003 if (lines.length > 1) {
1004 for (var i = 0; i < lines.length - 1; i++) {
1005 this$1.generatedCodeLine++;
1006 this$1.raw[this$1.generatedCodeLine] = this$1.rawSegments = [];
1007 }
1008 this.generatedCodeColumn = 0;
1009 }
1010 this.generatedCodeColumn += lines[lines.length - 1].length;
1011};
1012var n = '\n';
1013var warned = {
1014 insertLeft: false,
1015 insertRight: false,
1016 storeName: false
1017};
1018var MagicString = function MagicString(string, options) {
1019 if (options === void 0)
1020 options = {};
1021 var chunk = new Chunk(0, string.length, string);
1022 Object.defineProperties(this, {
1023 original: { writable: true, value: string },
1024 outro: { writable: true, value: '' },
1025 intro: { writable: true, value: '' },
1026 firstChunk: { writable: true, value: chunk },
1027 lastChunk: { writable: true, value: chunk },
1028 lastSearchedChunk: { writable: true, value: chunk },
1029 byStart: { writable: true, value: {} },
1030 byEnd: { writable: true, value: {} },
1031 filename: { writable: true, value: options.filename },
1032 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
1033 sourcemapLocations: { writable: true, value: {} },
1034 storedNames: { writable: true, value: {} },
1035 indentStr: { writable: true, value: guessIndent(string) }
1036 });
1037 this.byStart[0] = chunk;
1038 this.byEnd[string.length] = chunk;
1039};
1040MagicString.prototype.addSourcemapLocation = function addSourcemapLocation(char) {
1041 this.sourcemapLocations[char] = true;
1042};
1043MagicString.prototype.append = function append(content) {
1044 if (typeof content !== 'string') {
1045 throw new TypeError('outro content must be a string');
1046 }
1047 this.outro += content;
1048 return this;
1049};
1050MagicString.prototype.appendLeft = function appendLeft(index, content) {
1051 if (typeof content !== 'string') {
1052 throw new TypeError('inserted content must be a string');
1053 }
1054 this._split(index);
1055 var chunk = this.byEnd[index];
1056 if (chunk) {
1057 chunk.appendLeft(content);
1058 }
1059 else {
1060 this.intro += content;
1061 }
1062 return this;
1063};
1064MagicString.prototype.appendRight = function appendRight(index, content) {
1065 if (typeof content !== 'string') {
1066 throw new TypeError('inserted content must be a string');
1067 }
1068 this._split(index);
1069 var chunk = this.byStart[index];
1070 if (chunk) {
1071 chunk.appendRight(content);
1072 }
1073 else {
1074 this.outro += content;
1075 }
1076 return this;
1077};
1078MagicString.prototype.clone = function clone() {
1079 var cloned = new MagicString(this.original, { filename: this.filename });
1080 var originalChunk = this.firstChunk;
1081 var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
1082 while (originalChunk) {
1083 cloned.byStart[clonedChunk.start] = clonedChunk;
1084 cloned.byEnd[clonedChunk.end] = clonedChunk;
1085 var nextOriginalChunk = originalChunk.next;
1086 var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
1087 if (nextClonedChunk) {
1088 clonedChunk.next = nextClonedChunk;
1089 nextClonedChunk.previous = clonedChunk;
1090 clonedChunk = nextClonedChunk;
1091 }
1092 originalChunk = nextOriginalChunk;
1093 }
1094 cloned.lastChunk = clonedChunk;
1095 if (this.indentExclusionRanges) {
1096 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
1097 }
1098 Object.keys(this.sourcemapLocations).forEach(function (loc) {
1099 cloned.sourcemapLocations[loc] = true;
1100 });
1101 cloned.intro = this.intro;
1102 cloned.outro = this.outro;
1103 return cloned;
1104};
1105MagicString.prototype.generateDecodedMap = function generateDecodedMap(options) {
1106 var this$1 = this;
1107 options = options || {};
1108 var sourceIndex = 0;
1109 var names = Object.keys(this.storedNames);
1110 var mappings = new Mappings(options.hires);
1111 var locate = getLocator(this.original);
1112 if (this.intro) {
1113 mappings.advance(this.intro);
1114 }
1115 this.firstChunk.eachNext(function (chunk) {
1116 var loc = locate(chunk.start);
1117 if (chunk.intro.length) {
1118 mappings.advance(chunk.intro);
1119 }
1120 if (chunk.edited) {
1121 mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
1122 }
1123 else {
1124 mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
1125 }
1126 if (chunk.outro.length) {
1127 mappings.advance(chunk.outro);
1128 }
1129 });
1130 return {
1131 file: options.file ? options.file.split(/[/\\]/).pop() : null,
1132 sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
1133 sourcesContent: options.includeContent ? [this.original] : [null],
1134 names: names,
1135 mappings: mappings.raw
1136 };
1137};
1138MagicString.prototype.generateMap = function generateMap(options) {
1139 return new SourceMap(this.generateDecodedMap(options));
1140};
1141MagicString.prototype.getIndentString = function getIndentString() {
1142 return this.indentStr === null ? '\t' : this.indentStr;
1143};
1144MagicString.prototype.indent = function indent(indentStr, options) {
1145 var this$1 = this;
1146 var pattern = /^[^\r\n]/gm;
1147 if (isObject(indentStr)) {
1148 options = indentStr;
1149 indentStr = undefined;
1150 }
1151 indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
1152 if (indentStr === '') {
1153 return this;
1154 } // noop
1155 options = options || {};
1156 // Process exclusion ranges
1157 var isExcluded = {};
1158 if (options.exclude) {
1159 var exclusions = typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
1160 exclusions.forEach(function (exclusion) {
1161 for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
1162 isExcluded[i] = true;
1163 }
1164 });
1165 }
1166 var shouldIndentNextCharacter = options.indentStart !== false;
1167 var replacer = function (match) {
1168 if (shouldIndentNextCharacter) {
1169 return ("" + indentStr + match);
1170 }
1171 shouldIndentNextCharacter = true;
1172 return match;
1173 };
1174 this.intro = this.intro.replace(pattern, replacer);
1175 var charIndex = 0;
1176 var chunk = this.firstChunk;
1177 while (chunk) {
1178 var end = chunk.end;
1179 if (chunk.edited) {
1180 if (!isExcluded[charIndex]) {
1181 chunk.content = chunk.content.replace(pattern, replacer);
1182 if (chunk.content.length) {
1183 shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
1184 }
1185 }
1186 }
1187 else {
1188 charIndex = chunk.start;
1189 while (charIndex < end) {
1190 if (!isExcluded[charIndex]) {
1191 var char = this$1.original[charIndex];
1192 if (char === '\n') {
1193 shouldIndentNextCharacter = true;
1194 }
1195 else if (char !== '\r' && shouldIndentNextCharacter) {
1196 shouldIndentNextCharacter = false;
1197 if (charIndex === chunk.start) {
1198 chunk.prependRight(indentStr);
1199 }
1200 else {
1201 this$1._splitChunk(chunk, charIndex);
1202 chunk = chunk.next;
1203 chunk.prependRight(indentStr);
1204 }
1205 }
1206 }
1207 charIndex += 1;
1208 }
1209 }
1210 charIndex = chunk.end;
1211 chunk = chunk.next;
1212 }
1213 this.outro = this.outro.replace(pattern, replacer);
1214 return this;
1215};
1216MagicString.prototype.insert = function insert() {
1217 throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
1218};
1219MagicString.prototype.insertLeft = function insertLeft(index, content) {
1220 if (!warned.insertLeft) {
1221 console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
1222 warned.insertLeft = true;
1223 }
1224 return this.appendLeft(index, content);
1225};
1226MagicString.prototype.insertRight = function insertRight(index, content) {
1227 if (!warned.insertRight) {
1228 console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
1229 warned.insertRight = true;
1230 }
1231 return this.prependRight(index, content);
1232};
1233MagicString.prototype.move = function move(start, end, index) {
1234 if (index >= start && index <= end) {
1235 throw new Error('Cannot move a selection inside itself');
1236 }
1237 this._split(start);
1238 this._split(end);
1239 this._split(index);
1240 var first = this.byStart[start];
1241 var last = this.byEnd[end];
1242 var oldLeft = first.previous;
1243 var oldRight = last.next;
1244 var newRight = this.byStart[index];
1245 if (!newRight && last === this.lastChunk) {
1246 return this;
1247 }
1248 var newLeft = newRight ? newRight.previous : this.lastChunk;
1249 if (oldLeft) {
1250 oldLeft.next = oldRight;
1251 }
1252 if (oldRight) {
1253 oldRight.previous = oldLeft;
1254 }
1255 if (newLeft) {
1256 newLeft.next = first;
1257 }
1258 if (newRight) {
1259 newRight.previous = last;
1260 }
1261 if (!first.previous) {
1262 this.firstChunk = last.next;
1263 }
1264 if (!last.next) {
1265 this.lastChunk = first.previous;
1266 this.lastChunk.next = null;
1267 }
1268 first.previous = newLeft;
1269 last.next = newRight || null;
1270 if (!newLeft) {
1271 this.firstChunk = first;
1272 }
1273 if (!newRight) {
1274 this.lastChunk = last;
1275 }
1276 return this;
1277};
1278MagicString.prototype.overwrite = function overwrite(start, end, content, options) {
1279 var this$1 = this;
1280 if (typeof content !== 'string') {
1281 throw new TypeError('replacement content must be a string');
1282 }
1283 while (start < 0) {
1284 start += this$1.original.length;
1285 }
1286 while (end < 0) {
1287 end += this$1.original.length;
1288 }
1289 if (end > this.original.length) {
1290 throw new Error('end is out of bounds');
1291 }
1292 if (start === end) {
1293 throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead');
1294 }
1295 this._split(start);
1296 this._split(end);
1297 if (options === true) {
1298 if (!warned.storeName) {
1299 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
1300 warned.storeName = true;
1301 }
1302 options = { storeName: true };
1303 }
1304 var storeName = options !== undefined ? options.storeName : false;
1305 var contentOnly = options !== undefined ? options.contentOnly : false;
1306 if (storeName) {
1307 var original = this.original.slice(start, end);
1308 this.storedNames[original] = true;
1309 }
1310 var first = this.byStart[start];
1311 var last = this.byEnd[end];
1312 if (first) {
1313 if (end > first.end && first.next !== this.byStart[first.end]) {
1314 throw new Error('Cannot overwrite across a split point');
1315 }
1316 first.edit(content, storeName, contentOnly);
1317 if (first !== last) {
1318 var chunk = first.next;
1319 while (chunk !== last) {
1320 chunk.edit('', false);
1321 chunk = chunk.next;
1322 }
1323 chunk.edit('', false);
1324 }
1325 }
1326 else {
1327 // must be inserting at the end
1328 var newChunk = new Chunk(start, end, '').edit(content, storeName);
1329 // TODO last chunk in the array may not be the last chunk, if it's moved...
1330 last.next = newChunk;
1331 newChunk.previous = last;
1332 }
1333 return this;
1334};
1335MagicString.prototype.prepend = function prepend(content) {
1336 if (typeof content !== 'string') {
1337 throw new TypeError('outro content must be a string');
1338 }
1339 this.intro = content + this.intro;
1340 return this;
1341};
1342MagicString.prototype.prependLeft = function prependLeft(index, content) {
1343 if (typeof content !== 'string') {
1344 throw new TypeError('inserted content must be a string');
1345 }
1346 this._split(index);
1347 var chunk = this.byEnd[index];
1348 if (chunk) {
1349 chunk.prependLeft(content);
1350 }
1351 else {
1352 this.intro = content + this.intro;
1353 }
1354 return this;
1355};
1356MagicString.prototype.prependRight = function prependRight(index, content) {
1357 if (typeof content !== 'string') {
1358 throw new TypeError('inserted content must be a string');
1359 }
1360 this._split(index);
1361 var chunk = this.byStart[index];
1362 if (chunk) {
1363 chunk.prependRight(content);
1364 }
1365 else {
1366 this.outro = content + this.outro;
1367 }
1368 return this;
1369};
1370MagicString.prototype.remove = function remove(start, end) {
1371 var this$1 = this;
1372 while (start < 0) {
1373 start += this$1.original.length;
1374 }
1375 while (end < 0) {
1376 end += this$1.original.length;
1377 }
1378 if (start === end) {
1379 return this;
1380 }
1381 if (start < 0 || end > this.original.length) {
1382 throw new Error('Character is out of bounds');
1383 }
1384 if (start > end) {
1385 throw new Error('end must be greater than start');
1386 }
1387 this._split(start);
1388 this._split(end);
1389 var chunk = this.byStart[start];
1390 while (chunk) {
1391 chunk.intro = '';
1392 chunk.outro = '';
1393 chunk.edit('');
1394 chunk = end > chunk.end ? this$1.byStart[chunk.end] : null;
1395 }
1396 return this;
1397};
1398MagicString.prototype.lastChar = function lastChar() {
1399 if (this.outro.length) {
1400 return this.outro[this.outro.length - 1];
1401 }
1402 var chunk = this.lastChunk;
1403 do {
1404 if (chunk.outro.length) {
1405 return chunk.outro[chunk.outro.length - 1];
1406 }
1407 if (chunk.content.length) {
1408 return chunk.content[chunk.content.length - 1];
1409 }
1410 if (chunk.intro.length) {
1411 return chunk.intro[chunk.intro.length - 1];
1412 }
1413 } while (chunk = chunk.previous);
1414 if (this.intro.length) {
1415 return this.intro[this.intro.length - 1];
1416 }
1417 return '';
1418};
1419MagicString.prototype.lastLine = function lastLine() {
1420 var lineIndex = this.outro.lastIndexOf(n);
1421 if (lineIndex !== -1) {
1422 return this.outro.substr(lineIndex + 1);
1423 }
1424 var lineStr = this.outro;
1425 var chunk = this.lastChunk;
1426 do {
1427 if (chunk.outro.length > 0) {
1428 lineIndex = chunk.outro.lastIndexOf(n);
1429 if (lineIndex !== -1) {
1430 return chunk.outro.substr(lineIndex + 1) + lineStr;
1431 }
1432 lineStr = chunk.outro + lineStr;
1433 }
1434 if (chunk.content.length > 0) {
1435 lineIndex = chunk.content.lastIndexOf(n);
1436 if (lineIndex !== -1) {
1437 return chunk.content.substr(lineIndex + 1) + lineStr;
1438 }
1439 lineStr = chunk.content + lineStr;
1440 }
1441 if (chunk.intro.length > 0) {
1442 lineIndex = chunk.intro.lastIndexOf(n);
1443 if (lineIndex !== -1) {
1444 return chunk.intro.substr(lineIndex + 1) + lineStr;
1445 }
1446 lineStr = chunk.intro + lineStr;
1447 }
1448 } while (chunk = chunk.previous);
1449 lineIndex = this.intro.lastIndexOf(n);
1450 if (lineIndex !== -1) {
1451 return this.intro.substr(lineIndex + 1) + lineStr;
1452 }
1453 return this.intro + lineStr;
1454};
1455MagicString.prototype.slice = function slice(start, end) {
1456 var this$1 = this;
1457 if (start === void 0)
1458 start = 0;
1459 if (end === void 0)
1460 end = this.original.length;
1461 while (start < 0) {
1462 start += this$1.original.length;
1463 }
1464 while (end < 0) {
1465 end += this$1.original.length;
1466 }
1467 var result = '';
1468 // find start chunk
1469 var chunk = this.firstChunk;
1470 while (chunk && (chunk.start > start || chunk.end <= start)) {
1471 // found end chunk before start
1472 if (chunk.start < end && chunk.end >= end) {
1473 return result;
1474 }
1475 chunk = chunk.next;
1476 }
1477 if (chunk && chunk.edited && chunk.start !== start) {
1478 throw new Error(("Cannot use replaced character " + start + " as slice start anchor."));
1479 }
1480 var startChunk = chunk;
1481 while (chunk) {
1482 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1483 result += chunk.intro;
1484 }
1485 var containsEnd = chunk.start < end && chunk.end >= end;
1486 if (containsEnd && chunk.edited && chunk.end !== end) {
1487 throw new Error(("Cannot use replaced character " + end + " as slice end anchor."));
1488 }
1489 var sliceStart = startChunk === chunk ? start - chunk.start : 0;
1490 var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1491 result += chunk.content.slice(sliceStart, sliceEnd);
1492 if (chunk.outro && (!containsEnd || chunk.end === end)) {
1493 result += chunk.outro;
1494 }
1495 if (containsEnd) {
1496 break;
1497 }
1498 chunk = chunk.next;
1499 }
1500 return result;
1501};
1502// TODO deprecate this? not really very useful
1503MagicString.prototype.snip = function snip(start, end) {
1504 var clone = this.clone();
1505 clone.remove(0, start);
1506 clone.remove(end, clone.original.length);
1507 return clone;
1508};
1509MagicString.prototype._split = function _split(index) {
1510 var this$1 = this;
1511 if (this.byStart[index] || this.byEnd[index]) {
1512 return;
1513 }
1514 var chunk = this.lastSearchedChunk;
1515 var searchForward = index > chunk.end;
1516 while (chunk) {
1517 if (chunk.contains(index)) {
1518 return this$1._splitChunk(chunk, index);
1519 }
1520 chunk = searchForward ? this$1.byStart[chunk.end] : this$1.byEnd[chunk.start];
1521 }
1522};
1523MagicString.prototype._splitChunk = function _splitChunk(chunk, index) {
1524 if (chunk.edited && chunk.content.length) {
1525 // zero-length edited chunks are a special case (overlapping replacements)
1526 var loc = getLocator(this.original)(index);
1527 throw new Error(("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")"));
1528 }
1529 var newChunk = chunk.split(index);
1530 this.byEnd[index] = chunk;
1531 this.byStart[index] = newChunk;
1532 this.byEnd[newChunk.end] = newChunk;
1533 if (chunk === this.lastChunk) {
1534 this.lastChunk = newChunk;
1535 }
1536 this.lastSearchedChunk = chunk;
1537 return true;
1538};
1539MagicString.prototype.toString = function toString() {
1540 var str = this.intro;
1541 var chunk = this.firstChunk;
1542 while (chunk) {
1543 str += chunk.toString();
1544 chunk = chunk.next;
1545 }
1546 return str + this.outro;
1547};
1548MagicString.prototype.isEmpty = function isEmpty() {
1549 var chunk = this.firstChunk;
1550 do {
1551 if (chunk.intro.length && chunk.intro.trim() ||
1552 chunk.content.length && chunk.content.trim() ||
1553 chunk.outro.length && chunk.outro.trim()) {
1554 return false;
1555 }
1556 } while (chunk = chunk.next);
1557 return true;
1558};
1559MagicString.prototype.length = function length() {
1560 var chunk = this.firstChunk;
1561 var length = 0;
1562 do {
1563 length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1564 } while (chunk = chunk.next);
1565 return length;
1566};
1567MagicString.prototype.trimLines = function trimLines() {
1568 return this.trim('[\\r\\n]');
1569};
1570MagicString.prototype.trim = function trim(charType) {
1571 return this.trimStart(charType).trimEnd(charType);
1572};
1573MagicString.prototype.trimEndAborted = function trimEndAborted(charType) {
1574 var this$1 = this;
1575 var rx = new RegExp((charType || '\\s') + '+$');
1576 this.outro = this.outro.replace(rx, '');
1577 if (this.outro.length) {
1578 return true;
1579 }
1580 var chunk = this.lastChunk;
1581 do {
1582 var end = chunk.end;
1583 var aborted = chunk.trimEnd(rx);
1584 // if chunk was trimmed, we have a new lastChunk
1585 if (chunk.end !== end) {
1586 if (this$1.lastChunk === chunk) {
1587 this$1.lastChunk = chunk.next;
1588 }
1589 this$1.byEnd[chunk.end] = chunk;
1590 this$1.byStart[chunk.next.start] = chunk.next;
1591 this$1.byEnd[chunk.next.end] = chunk.next;
1592 }
1593 if (aborted) {
1594 return true;
1595 }
1596 chunk = chunk.previous;
1597 } while (chunk);
1598 return false;
1599};
1600MagicString.prototype.trimEnd = function trimEnd(charType) {
1601 this.trimEndAborted(charType);
1602 return this;
1603};
1604MagicString.prototype.trimStartAborted = function trimStartAborted(charType) {
1605 var this$1 = this;
1606 var rx = new RegExp('^' + (charType || '\\s') + '+');
1607 this.intro = this.intro.replace(rx, '');
1608 if (this.intro.length) {
1609 return true;
1610 }
1611 var chunk = this.firstChunk;
1612 do {
1613 var end = chunk.end;
1614 var aborted = chunk.trimStart(rx);
1615 if (chunk.end !== end) {
1616 // special case...
1617 if (chunk === this$1.lastChunk) {
1618 this$1.lastChunk = chunk.next;
1619 }
1620 this$1.byEnd[chunk.end] = chunk;
1621 this$1.byStart[chunk.next.start] = chunk.next;
1622 this$1.byEnd[chunk.next.end] = chunk.next;
1623 }
1624 if (aborted) {
1625 return true;
1626 }
1627 chunk = chunk.next;
1628 } while (chunk);
1629 return false;
1630};
1631MagicString.prototype.trimStart = function trimStart(charType) {
1632 this.trimStartAborted(charType);
1633 return this;
1634};
1635var hasOwnProp = Object.prototype.hasOwnProperty;
1636var Bundle = function Bundle(options) {
1637 if (options === void 0)
1638 options = {};
1639 this.intro = options.intro || '';
1640 this.separator = options.separator !== undefined ? options.separator : '\n';
1641 this.sources = [];
1642 this.uniqueSources = [];
1643 this.uniqueSourceIndexByFilename = {};
1644};
1645Bundle.prototype.addSource = function addSource(source) {
1646 if (source instanceof MagicString) {
1647 return this.addSource({
1648 content: source,
1649 filename: source.filename,
1650 separator: this.separator
1651 });
1652 }
1653 if (!isObject(source) || !source.content) {
1654 throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
1655 }
1656 ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
1657 if (!hasOwnProp.call(source, option)) {
1658 source[option] = source.content[option];
1659 }
1660 });
1661 if (source.separator === undefined) {
1662 // TODO there's a bunch of this sort of thing, needs cleaning up
1663 source.separator = this.separator;
1664 }
1665 if (source.filename) {
1666 if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
1667 this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
1668 this.uniqueSources.push({ filename: source.filename, content: source.content.original });
1669 }
1670 else {
1671 var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
1672 if (source.content.original !== uniqueSource.content) {
1673 throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
1674 }
1675 }
1676 }
1677 this.sources.push(source);
1678 return this;
1679};
1680Bundle.prototype.append = function append(str, options) {
1681 this.addSource({
1682 content: new MagicString(str),
1683 separator: (options && options.separator) || ''
1684 });
1685 return this;
1686};
1687Bundle.prototype.clone = function clone() {
1688 var bundle = new Bundle({
1689 intro: this.intro,
1690 separator: this.separator
1691 });
1692 this.sources.forEach(function (source) {
1693 bundle.addSource({
1694 filename: source.filename,
1695 content: source.content.clone(),
1696 separator: source.separator
1697 });
1698 });
1699 return bundle;
1700};
1701Bundle.prototype.generateDecodedMap = function generateDecodedMap(options) {
1702 var this$1 = this;
1703 if (options === void 0)
1704 options = {};
1705 var names = [];
1706 this.sources.forEach(function (source) {
1707 Object.keys(source.content.storedNames).forEach(function (name) {
1708 if (!~names.indexOf(name)) {
1709 names.push(name);
1710 }
1711 });
1712 });
1713 var mappings = new Mappings(options.hires);
1714 if (this.intro) {
1715 mappings.advance(this.intro);
1716 }
1717 this.sources.forEach(function (source, i) {
1718 if (i > 0) {
1719 mappings.advance(this$1.separator);
1720 }
1721 var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[source.filename] : -1;
1722 var magicString = source.content;
1723 var locate = getLocator(magicString.original);
1724 if (magicString.intro) {
1725 mappings.advance(magicString.intro);
1726 }
1727 magicString.firstChunk.eachNext(function (chunk) {
1728 var loc = locate(chunk.start);
1729 if (chunk.intro.length) {
1730 mappings.advance(chunk.intro);
1731 }
1732 if (source.filename) {
1733 if (chunk.edited) {
1734 mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
1735 }
1736 else {
1737 mappings.addUneditedChunk(sourceIndex, chunk, magicString.original, loc, magicString.sourcemapLocations);
1738 }
1739 }
1740 else {
1741 mappings.advance(chunk.content);
1742 }
1743 if (chunk.outro.length) {
1744 mappings.advance(chunk.outro);
1745 }
1746 });
1747 if (magicString.outro) {
1748 mappings.advance(magicString.outro);
1749 }
1750 });
1751 return {
1752 file: options.file ? options.file.split(/[/\\]/).pop() : null,
1753 sources: this.uniqueSources.map(function (source) {
1754 return options.file ? getRelativePath(options.file, source.filename) : source.filename;
1755 }),
1756 sourcesContent: this.uniqueSources.map(function (source) {
1757 return options.includeContent ? source.content : null;
1758 }),
1759 names: names,
1760 mappings: mappings.raw
1761 };
1762};
1763Bundle.prototype.generateMap = function generateMap(options) {
1764 return new SourceMap(this.generateDecodedMap(options));
1765};
1766Bundle.prototype.getIndentString = function getIndentString() {
1767 var indentStringCounts = {};
1768 this.sources.forEach(function (source) {
1769 var indentStr = source.content.indentStr;
1770 if (indentStr === null) {
1771 return;
1772 }
1773 if (!indentStringCounts[indentStr]) {
1774 indentStringCounts[indentStr] = 0;
1775 }
1776 indentStringCounts[indentStr] += 1;
1777 });
1778 return (Object.keys(indentStringCounts).sort(function (a, b) {
1779 return indentStringCounts[a] - indentStringCounts[b];
1780 })[0] || '\t');
1781};
1782Bundle.prototype.indent = function indent(indentStr) {
1783 var this$1 = this;
1784 if (!arguments.length) {
1785 indentStr = this.getIndentString();
1786 }
1787 if (indentStr === '') {
1788 return this;
1789 } // noop
1790 var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
1791 this.sources.forEach(function (source, i) {
1792 var separator = source.separator !== undefined ? source.separator : this$1.separator;
1793 var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
1794 source.content.indent(indentStr, {
1795 exclude: source.indentExclusionRanges,
1796 indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
1797 });
1798 trailingNewline = source.content.lastChar() === '\n';
1799 });
1800 if (this.intro) {
1801 this.intro =
1802 indentStr +
1803 this.intro.replace(/^[^\n]/gm, function (match, index) {
1804 return index > 0 ? indentStr + match : match;
1805 });
1806 }
1807 return this;
1808};
1809Bundle.prototype.prepend = function prepend(str) {
1810 this.intro = str + this.intro;
1811 return this;
1812};
1813Bundle.prototype.toString = function toString() {
1814 var this$1 = this;
1815 var body = this.sources
1816 .map(function (source, i) {
1817 var separator = source.separator !== undefined ? source.separator : this$1.separator;
1818 var str = (i > 0 ? separator : '') + source.content.toString();
1819 return str;
1820 })
1821 .join('');
1822 return this.intro + body;
1823};
1824Bundle.prototype.isEmpty = function isEmpty() {
1825 if (this.intro.length && this.intro.trim()) {
1826 return false;
1827 }
1828 if (this.sources.some(function (source) { return !source.content.isEmpty(); })) {
1829 return false;
1830 }
1831 return true;
1832};
1833Bundle.prototype.length = function length() {
1834 return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
1835};
1836Bundle.prototype.trimLines = function trimLines() {
1837 return this.trim('[\\r\\n]');
1838};
1839Bundle.prototype.trim = function trim(charType) {
1840 return this.trimStart(charType).trimEnd(charType);
1841};
1842Bundle.prototype.trimStart = function trimStart(charType) {
1843 var this$1 = this;
1844 var rx = new RegExp('^' + (charType || '\\s') + '+');
1845 this.intro = this.intro.replace(rx, '');
1846 if (!this.intro) {
1847 var source;
1848 var i = 0;
1849 do {
1850 source = this$1.sources[i++];
1851 if (!source) {
1852 break;
1853 }
1854 } while (!source.content.trimStartAborted(charType));
1855 }
1856 return this;
1857};
1858Bundle.prototype.trimEnd = function trimEnd(charType) {
1859 var this$1 = this;
1860 var rx = new RegExp((charType || '\\s') + '+$');
1861 var source;
1862 var i = this.sources.length - 1;
1863 do {
1864 source = this$1.sources[i--];
1865 if (!source) {
1866 this$1.intro = this$1.intro.replace(rx, '');
1867 break;
1868 }
1869 } while (!source.content.trimEndAborted(charType));
1870 return this;
1871};
1872
1873function relative(from, to) {
1874 const fromParts = from.split(/[/\\]/).filter(Boolean);
1875 const toParts = to.split(/[/\\]/).filter(Boolean);
1876 if (fromParts[0] === '.')
1877 fromParts.shift();
1878 if (toParts[0] === '.')
1879 toParts.shift();
1880 while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
1881 fromParts.shift();
1882 toParts.shift();
1883 }
1884 while (toParts[0] === '..' && fromParts.length > 0) {
1885 toParts.shift();
1886 fromParts.pop();
1887 }
1888 while (fromParts.pop()) {
1889 toParts.unshift('..');
1890 }
1891 return toParts.join('/');
1892}
1893
1894const UnknownKey = Symbol('Unknown Key');
1895const EMPTY_PATH = [];
1896const UNKNOWN_PATH = [UnknownKey];
1897const EntitiesKey = Symbol('Entities');
1898class PathTracker {
1899 constructor() {
1900 this.entityPaths = Object.create(null, { [EntitiesKey]: { value: new Set() } });
1901 }
1902 getEntities(path) {
1903 let currentPaths = this.entityPaths;
1904 for (const pathSegment of path) {
1905 currentPaths = currentPaths[pathSegment] =
1906 currentPaths[pathSegment] ||
1907 Object.create(null, { [EntitiesKey]: { value: new Set() } });
1908 }
1909 return currentPaths[EntitiesKey];
1910 }
1911}
1912const EMPTY_IMMUTABLE_TRACKER = new PathTracker();
1913
1914const BROKEN_FLOW_NONE = 0;
1915const BROKEN_FLOW_BREAK_CONTINUE = 1;
1916const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
1917function createInclusionContext() {
1918 return {
1919 brokenFlow: BROKEN_FLOW_NONE,
1920 includedLabels: new Set()
1921 };
1922}
1923function createHasEffectsContext() {
1924 return {
1925 accessed: new PathTracker(),
1926 assigned: new PathTracker(),
1927 brokenFlow: BROKEN_FLOW_NONE,
1928 called: new PathTracker(),
1929 ignore: {
1930 breaks: false,
1931 continues: false,
1932 labels: new Set(),
1933 returnAwaitYield: false
1934 },
1935 includedLabels: new Set(),
1936 instantiated: new PathTracker(),
1937 replacedVariableInits: new Map()
1938 };
1939}
1940
1941const BLANK = Object.create(null);
1942
1943const BlockStatement = 'BlockStatement';
1944const CallExpression = 'CallExpression';
1945const ExportAllDeclaration = 'ExportAllDeclaration';
1946const ExpressionStatement = 'ExpressionStatement';
1947const FunctionExpression = 'FunctionExpression';
1948const Identifier = 'Identifier';
1949const ImportDefaultSpecifier = 'ImportDefaultSpecifier';
1950const ImportNamespaceSpecifier = 'ImportNamespaceSpecifier';
1951const Program = 'Program';
1952const Property = 'Property';
1953const ReturnStatement = 'ReturnStatement';
1954const VariableDeclaration = 'VariableDeclaration';
1955
1956function treeshakeNode(node, code, start, end) {
1957 code.remove(start, end);
1958 if (node.annotations) {
1959 for (const annotation of node.annotations) {
1960 if (annotation.start < start) {
1961 code.remove(annotation.start, annotation.end);
1962 }
1963 else {
1964 return;
1965 }
1966 }
1967 }
1968}
1969function removeAnnotations(node, code) {
1970 if (!node.annotations && node.parent.type === ExpressionStatement) {
1971 node = node.parent;
1972 }
1973 if (node.annotations) {
1974 for (const annotation of node.annotations) {
1975 code.remove(annotation.start, annotation.end);
1976 }
1977 }
1978}
1979
1980const NO_SEMICOLON = { isNoStatement: true };
1981// This assumes there are only white-space and comments between start and the string we are looking for
1982function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
1983 let searchPos, charCodeAfterSlash;
1984 searchPos = code.indexOf(searchString, start);
1985 while (true) {
1986 start = code.indexOf('/', start);
1987 if (start === -1 || start > searchPos)
1988 return searchPos;
1989 charCodeAfterSlash = code.charCodeAt(++start);
1990 ++start;
1991 // With our assumption, '/' always starts a comment. Determine comment type:
1992 start =
1993 charCodeAfterSlash === 47 /*"/"*/
1994 ? code.indexOf('\n', start) + 1
1995 : code.indexOf('*/', start) + 2;
1996 if (start > searchPos) {
1997 searchPos = code.indexOf(searchString, start);
1998 }
1999 }
2000}
2001// This assumes "code" only contains white-space and comments
2002function findFirstLineBreakOutsideComment(code) {
2003 let lineBreakPos, charCodeAfterSlash, start = 0;
2004 lineBreakPos = code.indexOf('\n', start);
2005 while (true) {
2006 start = code.indexOf('/', start);
2007 if (start === -1 || start > lineBreakPos)
2008 return lineBreakPos;
2009 // With our assumption, '/' always starts a comment. Determine comment type:
2010 charCodeAfterSlash = code.charCodeAt(++start);
2011 if (charCodeAfterSlash === 47 /*"/"*/)
2012 return lineBreakPos;
2013 start = code.indexOf('*/', start + 2) + 2;
2014 if (start > lineBreakPos) {
2015 lineBreakPos = code.indexOf('\n', start);
2016 }
2017 }
2018}
2019function renderStatementList(statements, code, start, end, options) {
2020 let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
2021 let nextNode = statements[0];
2022 let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
2023 if (nextNodeNeedsBoundaries) {
2024 nextNodeStart =
2025 start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start)) + 1;
2026 }
2027 for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
2028 currentNode = nextNode;
2029 currentNodeStart = nextNodeStart;
2030 currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
2031 nextNode = statements[nextIndex];
2032 nextNodeNeedsBoundaries =
2033 nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
2034 if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
2035 nextNodeStart =
2036 currentNode.end +
2037 findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start)) +
2038 1;
2039 if (currentNode.included) {
2040 currentNodeNeedsBoundaries
2041 ? currentNode.render(code, options, {
2042 end: nextNodeStart,
2043 start: currentNodeStart
2044 })
2045 : currentNode.render(code, options);
2046 }
2047 else {
2048 treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
2049 }
2050 }
2051 else {
2052 currentNode.render(code, options);
2053 }
2054 }
2055}
2056// This assumes that the first character is not part of the first node
2057function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
2058 const splitUpNodes = [];
2059 let node, nextNode, nextNodeStart, contentEnd, char;
2060 let separator = start - 1;
2061 for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
2062 nextNode = nodes[nextIndex];
2063 if (node !== undefined) {
2064 separator =
2065 node.end +
2066 findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
2067 }
2068 nextNodeStart = contentEnd =
2069 separator +
2070 2 +
2071 findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start));
2072 while (((char = code.original.charCodeAt(nextNodeStart)),
2073 char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
2074 nextNodeStart++;
2075 if (node !== undefined) {
2076 splitUpNodes.push({
2077 contentEnd,
2078 end: nextNodeStart,
2079 node,
2080 separator,
2081 start
2082 });
2083 }
2084 node = nextNode;
2085 start = nextNodeStart;
2086 }
2087 splitUpNodes.push({
2088 contentEnd: end,
2089 end,
2090 node: node,
2091 separator: null,
2092 start
2093 });
2094 return splitUpNodes;
2095}
2096// This assumes there are only white-space and comments between start and end
2097function removeLineBreaks(code, start, end) {
2098 while (true) {
2099 const lineBreakPos = findFirstLineBreakOutsideComment(code.original.slice(start, end));
2100 if (lineBreakPos === -1) {
2101 break;
2102 }
2103 start = start + lineBreakPos + 1;
2104 code.remove(start - 1, start);
2105 }
2106}
2107
2108const chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
2109const base = 64;
2110function toBase64(num) {
2111 let outStr = '';
2112 do {
2113 const curDigit = num % base;
2114 num = Math.floor(num / base);
2115 outStr = chars$1[curDigit] + outStr;
2116 } while (num !== 0);
2117 return outStr;
2118}
2119
2120// Verified on IE 6/7 that these keywords can't be used for object properties without escaping:
2121// break case catch class const continue debugger default delete do
2122// else enum export extends false finally for function if import
2123// in instanceof new null return super switch this throw true
2124// try typeof var void while with
2125const RESERVED_NAMES = Object.assign(Object.create(null), {
2126 await: true,
2127 break: true,
2128 case: true,
2129 catch: true,
2130 class: true,
2131 const: true,
2132 continue: true,
2133 debugger: true,
2134 default: true,
2135 delete: true,
2136 do: true,
2137 else: true,
2138 enum: true,
2139 eval: true,
2140 export: true,
2141 extends: true,
2142 false: true,
2143 finally: true,
2144 for: true,
2145 function: true,
2146 if: true,
2147 implements: true,
2148 import: true,
2149 in: true,
2150 instanceof: true,
2151 interface: true,
2152 let: true,
2153 new: true,
2154 null: true,
2155 package: true,
2156 private: true,
2157 protected: true,
2158 public: true,
2159 return: true,
2160 static: true,
2161 super: true,
2162 switch: true,
2163 this: true,
2164 throw: true,
2165 true: true,
2166 try: true,
2167 typeof: true,
2168 undefined: true,
2169 var: true,
2170 void: true,
2171 while: true,
2172 with: true,
2173 yield: true
2174});
2175
2176function getSafeName(baseName, usedNames) {
2177 let safeName = baseName;
2178 let count = 1;
2179 while (usedNames.has(safeName) || RESERVED_NAMES[safeName]) {
2180 safeName = `${baseName}$${toBase64(count++)}`;
2181 }
2182 usedNames.add(safeName);
2183 return safeName;
2184}
2185
2186const NO_ARGS = [];
2187
2188function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
2189 return Object.create(inheritedDescriptions, memberDescriptions);
2190}
2191const UnknownValue = Symbol('Unknown Value');
2192const UNKNOWN_EXPRESSION = {
2193 deoptimizePath: () => { },
2194 getLiteralValueAtPath: () => UnknownValue,
2195 getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
2196 hasEffectsWhenAccessedAtPath: path => path.length > 0,
2197 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2198 hasEffectsWhenCalledAtPath: () => true,
2199 include: () => { },
2200 includeCallArguments(context, args) {
2201 for (const arg of args) {
2202 arg.include(context, false);
2203 }
2204 },
2205 included: true,
2206 toString: () => '[[UNKNOWN]]'
2207};
2208const UNDEFINED_EXPRESSION = {
2209 deoptimizePath: () => { },
2210 getLiteralValueAtPath: () => undefined,
2211 getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
2212 hasEffectsWhenAccessedAtPath: path => path.length > 0,
2213 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2214 hasEffectsWhenCalledAtPath: () => true,
2215 include: () => { },
2216 includeCallArguments() { },
2217 included: true,
2218 toString: () => 'undefined'
2219};
2220const returnsUnknown = {
2221 value: {
2222 callsArgs: null,
2223 mutatesSelf: false,
2224 returns: null,
2225 returnsPrimitive: UNKNOWN_EXPRESSION
2226 }
2227};
2228const mutatesSelfReturnsUnknown = {
2229 value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: null, mutatesSelf: true }
2230};
2231const callsArgReturnsUnknown = {
2232 value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: [0], mutatesSelf: false }
2233};
2234class UnknownArrayExpression {
2235 constructor() {
2236 this.included = false;
2237 }
2238 deoptimizePath() { }
2239 getLiteralValueAtPath() {
2240 return UnknownValue;
2241 }
2242 getReturnExpressionWhenCalledAtPath(path) {
2243 if (path.length === 1) {
2244 return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
2245 }
2246 return UNKNOWN_EXPRESSION;
2247 }
2248 hasEffectsWhenAccessedAtPath(path) {
2249 return path.length > 1;
2250 }
2251 hasEffectsWhenAssignedAtPath(path) {
2252 return path.length > 1;
2253 }
2254 hasEffectsWhenCalledAtPath(path, callOptions, context) {
2255 if (path.length === 1) {
2256 return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
2257 }
2258 return true;
2259 }
2260 include() {
2261 this.included = true;
2262 }
2263 includeCallArguments(context, args) {
2264 for (const arg of args) {
2265 arg.include(context, false);
2266 }
2267 }
2268 toString() {
2269 return '[[UNKNOWN ARRAY]]';
2270 }
2271}
2272const returnsArray = {
2273 value: {
2274 callsArgs: null,
2275 mutatesSelf: false,
2276 returns: UnknownArrayExpression,
2277 returnsPrimitive: null
2278 }
2279};
2280const mutatesSelfReturnsArray = {
2281 value: {
2282 callsArgs: null,
2283 mutatesSelf: true,
2284 returns: UnknownArrayExpression,
2285 returnsPrimitive: null
2286 }
2287};
2288const callsArgReturnsArray = {
2289 value: {
2290 callsArgs: [0],
2291 mutatesSelf: false,
2292 returns: UnknownArrayExpression,
2293 returnsPrimitive: null
2294 }
2295};
2296const callsArgMutatesSelfReturnsArray = {
2297 value: {
2298 callsArgs: [0],
2299 mutatesSelf: true,
2300 returns: UnknownArrayExpression,
2301 returnsPrimitive: null
2302 }
2303};
2304const UNKNOWN_LITERAL_BOOLEAN = {
2305 deoptimizePath: () => { },
2306 getLiteralValueAtPath: () => UnknownValue,
2307 getReturnExpressionWhenCalledAtPath: path => {
2308 if (path.length === 1) {
2309 return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
2310 }
2311 return UNKNOWN_EXPRESSION;
2312 },
2313 hasEffectsWhenAccessedAtPath: path => path.length > 1,
2314 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2315 hasEffectsWhenCalledAtPath: path => {
2316 if (path.length === 1) {
2317 const subPath = path[0];
2318 return typeof subPath !== 'string' || !literalBooleanMembers[subPath];
2319 }
2320 return true;
2321 },
2322 include: () => { },
2323 includeCallArguments(context, args) {
2324 for (const arg of args) {
2325 arg.include(context, false);
2326 }
2327 },
2328 included: true,
2329 toString: () => '[[UNKNOWN BOOLEAN]]'
2330};
2331const returnsBoolean = {
2332 value: {
2333 callsArgs: null,
2334 mutatesSelf: false,
2335 returns: null,
2336 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
2337 }
2338};
2339const callsArgReturnsBoolean = {
2340 value: {
2341 callsArgs: [0],
2342 mutatesSelf: false,
2343 returns: null,
2344 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
2345 }
2346};
2347const UNKNOWN_LITERAL_NUMBER = {
2348 deoptimizePath: () => { },
2349 getLiteralValueAtPath: () => UnknownValue,
2350 getReturnExpressionWhenCalledAtPath: path => {
2351 if (path.length === 1) {
2352 return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
2353 }
2354 return UNKNOWN_EXPRESSION;
2355 },
2356 hasEffectsWhenAccessedAtPath: path => path.length > 1,
2357 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2358 hasEffectsWhenCalledAtPath: path => {
2359 if (path.length === 1) {
2360 const subPath = path[0];
2361 return typeof subPath !== 'string' || !literalNumberMembers[subPath];
2362 }
2363 return true;
2364 },
2365 include: () => { },
2366 includeCallArguments(context, args) {
2367 for (const arg of args) {
2368 arg.include(context, false);
2369 }
2370 },
2371 included: true,
2372 toString: () => '[[UNKNOWN NUMBER]]'
2373};
2374const returnsNumber = {
2375 value: {
2376 callsArgs: null,
2377 mutatesSelf: false,
2378 returns: null,
2379 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2380 }
2381};
2382const mutatesSelfReturnsNumber = {
2383 value: {
2384 callsArgs: null,
2385 mutatesSelf: true,
2386 returns: null,
2387 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2388 }
2389};
2390const callsArgReturnsNumber = {
2391 value: {
2392 callsArgs: [0],
2393 mutatesSelf: false,
2394 returns: null,
2395 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2396 }
2397};
2398const UNKNOWN_LITERAL_STRING = {
2399 deoptimizePath: () => { },
2400 getLiteralValueAtPath: () => UnknownValue,
2401 getReturnExpressionWhenCalledAtPath: path => {
2402 if (path.length === 1) {
2403 return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
2404 }
2405 return UNKNOWN_EXPRESSION;
2406 },
2407 hasEffectsWhenAccessedAtPath: path => path.length > 1,
2408 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2409 hasEffectsWhenCalledAtPath: (path, callOptions, context) => {
2410 if (path.length === 1) {
2411 return hasMemberEffectWhenCalled(literalStringMembers, path[0], true, callOptions, context);
2412 }
2413 return true;
2414 },
2415 include: () => { },
2416 includeCallArguments(context, args) {
2417 for (const arg of args) {
2418 arg.include(context, false);
2419 }
2420 },
2421 included: true,
2422 toString: () => '[[UNKNOWN STRING]]'
2423};
2424const returnsString = {
2425 value: {
2426 callsArgs: null,
2427 mutatesSelf: false,
2428 returns: null,
2429 returnsPrimitive: UNKNOWN_LITERAL_STRING
2430 }
2431};
2432class UnknownObjectExpression {
2433 constructor() {
2434 this.included = false;
2435 }
2436 deoptimizePath() { }
2437 getLiteralValueAtPath() {
2438 return UnknownValue;
2439 }
2440 getReturnExpressionWhenCalledAtPath(path) {
2441 if (path.length === 1) {
2442 return getMemberReturnExpressionWhenCalled(objectMembers, path[0]);
2443 }
2444 return UNKNOWN_EXPRESSION;
2445 }
2446 hasEffectsWhenAccessedAtPath(path) {
2447 return path.length > 1;
2448 }
2449 hasEffectsWhenAssignedAtPath(path) {
2450 return path.length > 1;
2451 }
2452 hasEffectsWhenCalledAtPath(path, callOptions, context) {
2453 if (path.length === 1) {
2454 return hasMemberEffectWhenCalled(objectMembers, path[0], this.included, callOptions, context);
2455 }
2456 return true;
2457 }
2458 include() {
2459 this.included = true;
2460 }
2461 includeCallArguments(context, args) {
2462 for (const arg of args) {
2463 arg.include(context, false);
2464 }
2465 }
2466 toString() {
2467 return '[[UNKNOWN OBJECT]]';
2468 }
2469}
2470const objectMembers = assembleMemberDescriptions({
2471 hasOwnProperty: returnsBoolean,
2472 isPrototypeOf: returnsBoolean,
2473 propertyIsEnumerable: returnsBoolean,
2474 toLocaleString: returnsString,
2475 toString: returnsString,
2476 valueOf: returnsUnknown
2477});
2478const arrayMembers = assembleMemberDescriptions({
2479 concat: returnsArray,
2480 copyWithin: mutatesSelfReturnsArray,
2481 every: callsArgReturnsBoolean,
2482 fill: mutatesSelfReturnsArray,
2483 filter: callsArgReturnsArray,
2484 find: callsArgReturnsUnknown,
2485 findIndex: callsArgReturnsNumber,
2486 forEach: callsArgReturnsUnknown,
2487 includes: returnsBoolean,
2488 indexOf: returnsNumber,
2489 join: returnsString,
2490 lastIndexOf: returnsNumber,
2491 map: callsArgReturnsArray,
2492 pop: mutatesSelfReturnsUnknown,
2493 push: mutatesSelfReturnsNumber,
2494 reduce: callsArgReturnsUnknown,
2495 reduceRight: callsArgReturnsUnknown,
2496 reverse: mutatesSelfReturnsArray,
2497 shift: mutatesSelfReturnsUnknown,
2498 slice: returnsArray,
2499 some: callsArgReturnsBoolean,
2500 sort: callsArgMutatesSelfReturnsArray,
2501 splice: mutatesSelfReturnsArray,
2502 unshift: mutatesSelfReturnsNumber
2503}, objectMembers);
2504const literalBooleanMembers = assembleMemberDescriptions({
2505 valueOf: returnsBoolean
2506}, objectMembers);
2507const literalNumberMembers = assembleMemberDescriptions({
2508 toExponential: returnsString,
2509 toFixed: returnsString,
2510 toLocaleString: returnsString,
2511 toPrecision: returnsString,
2512 valueOf: returnsNumber
2513}, objectMembers);
2514const literalStringMembers = assembleMemberDescriptions({
2515 charAt: returnsString,
2516 charCodeAt: returnsNumber,
2517 codePointAt: returnsNumber,
2518 concat: returnsString,
2519 endsWith: returnsBoolean,
2520 includes: returnsBoolean,
2521 indexOf: returnsNumber,
2522 lastIndexOf: returnsNumber,
2523 localeCompare: returnsNumber,
2524 match: returnsBoolean,
2525 normalize: returnsString,
2526 padEnd: returnsString,
2527 padStart: returnsString,
2528 repeat: returnsString,
2529 replace: {
2530 value: {
2531 callsArgs: [1],
2532 mutatesSelf: false,
2533 returns: null,
2534 returnsPrimitive: UNKNOWN_LITERAL_STRING
2535 }
2536 },
2537 search: returnsNumber,
2538 slice: returnsString,
2539 split: returnsArray,
2540 startsWith: returnsBoolean,
2541 substr: returnsString,
2542 substring: returnsString,
2543 toLocaleLowerCase: returnsString,
2544 toLocaleUpperCase: returnsString,
2545 toLowerCase: returnsString,
2546 toUpperCase: returnsString,
2547 trim: returnsString,
2548 valueOf: returnsString
2549}, objectMembers);
2550function getLiteralMembersForValue(value) {
2551 switch (typeof value) {
2552 case 'boolean':
2553 return literalBooleanMembers;
2554 case 'number':
2555 return literalNumberMembers;
2556 case 'string':
2557 return literalStringMembers;
2558 default:
2559 return Object.create(null);
2560 }
2561}
2562function hasMemberEffectWhenCalled(members, memberName, parentIncluded, callOptions, context) {
2563 if (typeof memberName !== 'string' ||
2564 !members[memberName] ||
2565 (members[memberName].mutatesSelf && parentIncluded))
2566 return true;
2567 if (!members[memberName].callsArgs)
2568 return false;
2569 for (const argIndex of members[memberName].callsArgs) {
2570 if (callOptions.args[argIndex] &&
2571 callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, {
2572 args: NO_ARGS,
2573 withNew: false
2574 }, context))
2575 return true;
2576 }
2577 return false;
2578}
2579function getMemberReturnExpressionWhenCalled(members, memberName) {
2580 if (typeof memberName !== 'string' || !members[memberName])
2581 return UNKNOWN_EXPRESSION;
2582 return members[memberName].returnsPrimitive !== null
2583 ? members[memberName].returnsPrimitive
2584 : new members[memberName].returns();
2585}
2586
2587class Variable {
2588 constructor(name) {
2589 this.alwaysRendered = false;
2590 this.exportName = null;
2591 this.included = false;
2592 this.isId = false;
2593 this.isReassigned = false;
2594 this.renderBaseName = null;
2595 this.renderName = null;
2596 this.safeExportName = null;
2597 this.name = name;
2598 }
2599 /**
2600 * Binds identifiers that reference this variable to this variable.
2601 * Necessary to be able to change variable names.
2602 */
2603 addReference(_identifier) { }
2604 deoptimizePath(_path) { }
2605 getBaseVariableName() {
2606 return this.renderBaseName || this.renderName || this.name;
2607 }
2608 getLiteralValueAtPath(_path, _recursionTracker, _origin) {
2609 return UnknownValue;
2610 }
2611 getName() {
2612 const name = this.renderName || this.name;
2613 return this.renderBaseName ? `${this.renderBaseName}.${name}` : name;
2614 }
2615 getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
2616 return UNKNOWN_EXPRESSION;
2617 }
2618 hasEffectsWhenAccessedAtPath(path, _context) {
2619 return path.length > 0;
2620 }
2621 hasEffectsWhenAssignedAtPath(_path, _context) {
2622 return true;
2623 }
2624 hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
2625 return true;
2626 }
2627 /**
2628 * Marks this variable as being part of the bundle, which is usually the case when one of
2629 * its identifiers becomes part of the bundle. Returns true if it has not been included
2630 * previously.
2631 * Once a variable is included, it should take care all its declarations are included.
2632 */
2633 include(_context) {
2634 this.included = true;
2635 }
2636 includeCallArguments(context, args) {
2637 for (const arg of args) {
2638 arg.include(context, false);
2639 }
2640 }
2641 markCalledFromTryStatement() { }
2642 setRenderNames(baseName, name) {
2643 this.renderBaseName = baseName;
2644 this.renderName = name;
2645 }
2646 setSafeName(name) {
2647 this.renderName = name;
2648 }
2649 toString() {
2650 return this.name;
2651 }
2652}
2653
2654class ExternalVariable extends Variable {
2655 constructor(module, name) {
2656 super(name);
2657 this.module = module;
2658 this.isNamespace = name === '*';
2659 this.referenced = false;
2660 }
2661 addReference(identifier) {
2662 this.referenced = true;
2663 if (this.name === 'default' || this.name === '*') {
2664 this.module.suggestName(identifier.name);
2665 }
2666 }
2667 include() {
2668 if (!this.included) {
2669 this.included = true;
2670 this.module.used = true;
2671 }
2672 }
2673}
2674
2675const 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(' ');
2676const 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(' ');
2677const blacklisted = Object.create(null);
2678reservedWords.concat(builtins).forEach(word => (blacklisted[word] = true));
2679const illegalCharacters = /[^$_a-zA-Z0-9]/g;
2680const startsWithDigit = (str) => /\d/.test(str[0]);
2681function isLegal(str) {
2682 if (startsWithDigit(str) || blacklisted[str]) {
2683 return false;
2684 }
2685 return !illegalCharacters.test(str);
2686}
2687function makeLegal(str) {
2688 str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
2689 if (startsWithDigit(str) || blacklisted[str])
2690 str = `_${str}`;
2691 return str || '_';
2692}
2693
2694const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
2695const relativePath = /^\.?\.\//;
2696function isAbsolute(path) {
2697 return absolutePath.test(path);
2698}
2699function isRelative(path) {
2700 return relativePath.test(path);
2701}
2702function normalize(path) {
2703 if (path.indexOf('\\') == -1)
2704 return path;
2705 return path.replace(/\\/g, '/');
2706}
2707
2708class ExternalModule {
2709 constructor(graph, id, moduleSideEffects) {
2710 this.exportsNames = false;
2711 this.exportsNamespace = false;
2712 this.mostCommonSuggestion = 0;
2713 this.reexported = false;
2714 this.renderPath = undefined;
2715 this.renormalizeRenderPath = false;
2716 this.used = false;
2717 this.graph = graph;
2718 this.id = id;
2719 this.execIndex = Infinity;
2720 this.moduleSideEffects = moduleSideEffects;
2721 const parts = id.split(/[\\/]/);
2722 this.variableName = makeLegal(parts.pop());
2723 this.nameSuggestions = Object.create(null);
2724 this.declarations = Object.create(null);
2725 this.exportedVariables = new Map();
2726 }
2727 getVariableForExportName(name) {
2728 if (name === '*') {
2729 this.exportsNamespace = true;
2730 }
2731 else if (name !== 'default') {
2732 this.exportsNames = true;
2733 }
2734 let declaration = this.declarations[name];
2735 if (declaration)
2736 return declaration;
2737 this.declarations[name] = declaration = new ExternalVariable(this, name);
2738 this.exportedVariables.set(declaration, name);
2739 return declaration;
2740 }
2741 setRenderPath(options, inputBase) {
2742 this.renderPath = '';
2743 if (options.paths) {
2744 this.renderPath =
2745 typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
2746 }
2747 if (!this.renderPath) {
2748 if (!isAbsolute(this.id)) {
2749 this.renderPath = this.id;
2750 }
2751 else {
2752 this.renderPath = normalize(relative$1(inputBase, this.id));
2753 this.renormalizeRenderPath = true;
2754 }
2755 }
2756 return this.renderPath;
2757 }
2758 suggestName(name) {
2759 if (!this.nameSuggestions[name])
2760 this.nameSuggestions[name] = 0;
2761 this.nameSuggestions[name] += 1;
2762 if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
2763 this.mostCommonSuggestion = this.nameSuggestions[name];
2764 this.variableName = name;
2765 }
2766 }
2767 warnUnusedImports() {
2768 const unused = Object.keys(this.declarations).filter(name => {
2769 if (name === '*')
2770 return false;
2771 const declaration = this.declarations[name];
2772 return !declaration.included && !this.reexported && !declaration.referenced;
2773 });
2774 if (unused.length === 0)
2775 return;
2776 const names = unused.length === 1
2777 ? `'${unused[0]}' is`
2778 : `${unused
2779 .slice(0, -1)
2780 .map(name => `'${name}'`)
2781 .join(', ')} and '${unused.slice(-1)}' are`;
2782 this.graph.warn({
2783 code: 'UNUSED_EXTERNAL_IMPORT',
2784 message: `${names} imported from external module '${this.id}' but never used`,
2785 names: unused,
2786 source: this.id
2787 });
2788 }
2789}
2790
2791function markModuleAndImpureDependenciesAsExecuted(baseModule) {
2792 baseModule.isExecuted = true;
2793 const modules = [baseModule];
2794 const visitedModules = new Set();
2795 for (const module of modules) {
2796 for (const dependency of module.dependencies) {
2797 if (!(dependency instanceof ExternalModule) &&
2798 !dependency.isExecuted &&
2799 dependency.moduleSideEffects &&
2800 !visitedModules.has(dependency.id)) {
2801 dependency.isExecuted = true;
2802 visitedModules.add(dependency.id);
2803 modules.push(dependency);
2804 }
2805 }
2806 }
2807}
2808
2809// To avoid infinite recursions
2810const MAX_PATH_DEPTH = 7;
2811class LocalVariable extends Variable {
2812 constructor(name, declarator, init, context) {
2813 super(name);
2814 this.additionalInitializers = null;
2815 this.calledFromTryStatement = false;
2816 this.expressionsToBeDeoptimized = [];
2817 this.declarations = declarator ? [declarator] : [];
2818 this.init = init;
2819 this.deoptimizationTracker = context.deoptimizationTracker;
2820 this.module = context.module;
2821 }
2822 addDeclaration(identifier, init) {
2823 this.declarations.push(identifier);
2824 if (this.additionalInitializers === null) {
2825 this.additionalInitializers = this.init === null ? [] : [this.init];
2826 this.init = UNKNOWN_EXPRESSION;
2827 this.isReassigned = true;
2828 }
2829 if (init !== null) {
2830 this.additionalInitializers.push(init);
2831 }
2832 }
2833 consolidateInitializers() {
2834 if (this.additionalInitializers !== null) {
2835 for (const initializer of this.additionalInitializers) {
2836 initializer.deoptimizePath(UNKNOWN_PATH);
2837 }
2838 this.additionalInitializers = null;
2839 }
2840 }
2841 deoptimizePath(path) {
2842 if (path.length > MAX_PATH_DEPTH || this.isReassigned)
2843 return;
2844 const trackedEntities = this.deoptimizationTracker.getEntities(path);
2845 if (trackedEntities.has(this))
2846 return;
2847 trackedEntities.add(this);
2848 if (path.length === 0) {
2849 if (!this.isReassigned) {
2850 this.isReassigned = true;
2851 for (const expression of this.expressionsToBeDeoptimized) {
2852 expression.deoptimizeCache();
2853 }
2854 if (this.init) {
2855 this.init.deoptimizePath(UNKNOWN_PATH);
2856 }
2857 }
2858 }
2859 else if (this.init) {
2860 this.init.deoptimizePath(path);
2861 }
2862 }
2863 getLiteralValueAtPath(path, recursionTracker, origin) {
2864 if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
2865 return UnknownValue;
2866 }
2867 const trackedEntities = recursionTracker.getEntities(path);
2868 if (trackedEntities.has(this.init)) {
2869 return UnknownValue;
2870 }
2871 this.expressionsToBeDeoptimized.push(origin);
2872 trackedEntities.add(this.init);
2873 const value = this.init.getLiteralValueAtPath(path, recursionTracker, origin);
2874 trackedEntities.delete(this.init);
2875 return value;
2876 }
2877 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
2878 if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
2879 return UNKNOWN_EXPRESSION;
2880 }
2881 const trackedEntities = recursionTracker.getEntities(path);
2882 if (trackedEntities.has(this.init)) {
2883 return UNKNOWN_EXPRESSION;
2884 }
2885 this.expressionsToBeDeoptimized.push(origin);
2886 trackedEntities.add(this.init);
2887 const value = this.init.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
2888 trackedEntities.delete(this.init);
2889 return value;
2890 }
2891 hasEffectsWhenAccessedAtPath(path, context) {
2892 if (path.length === 0)
2893 return false;
2894 if (this.isReassigned || path.length > MAX_PATH_DEPTH)
2895 return true;
2896 const trackedExpressions = context.accessed.getEntities(path);
2897 if (trackedExpressions.has(this))
2898 return false;
2899 trackedExpressions.add(this);
2900 return (this.init && this.init.hasEffectsWhenAccessedAtPath(path, context));
2901 }
2902 hasEffectsWhenAssignedAtPath(path, context) {
2903 if (this.included || path.length > MAX_PATH_DEPTH)
2904 return true;
2905 if (path.length === 0)
2906 return false;
2907 if (this.isReassigned)
2908 return true;
2909 const trackedExpressions = context.assigned.getEntities(path);
2910 if (trackedExpressions.has(this))
2911 return false;
2912 trackedExpressions.add(this);
2913 return (this.init && this.init.hasEffectsWhenAssignedAtPath(path, context));
2914 }
2915 hasEffectsWhenCalledAtPath(path, callOptions, context) {
2916 if (path.length > MAX_PATH_DEPTH || this.isReassigned)
2917 return true;
2918 const trackedExpressions = (callOptions.withNew
2919 ? context.instantiated
2920 : context.called).getEntities(path);
2921 if (trackedExpressions.has(this))
2922 return false;
2923 trackedExpressions.add(this);
2924 return (this.init &&
2925 this.init.hasEffectsWhenCalledAtPath(path, callOptions, context));
2926 }
2927 include(context) {
2928 if (!this.included) {
2929 this.included = true;
2930 if (!this.module.isExecuted) {
2931 markModuleAndImpureDependenciesAsExecuted(this.module);
2932 }
2933 for (const declaration of this.declarations) {
2934 // If node is a default export, it can save a tree-shaking run to include the full declaration now
2935 if (!declaration.included)
2936 declaration.include(context, false);
2937 let node = declaration.parent;
2938 while (!node.included) {
2939 // We do not want to properly include parents in case they are part of a dead branch
2940 // in which case .include() might pull in more dead code
2941 node.included = true;
2942 if (node.type === Program)
2943 break;
2944 node = node.parent;
2945 }
2946 }
2947 }
2948 }
2949 includeCallArguments(context, args) {
2950 if (this.isReassigned) {
2951 for (const arg of args) {
2952 arg.include(context, false);
2953 }
2954 }
2955 else if (this.init) {
2956 this.init.includeCallArguments(context, args);
2957 }
2958 }
2959 markCalledFromTryStatement() {
2960 this.calledFromTryStatement = true;
2961 }
2962}
2963
2964class Scope {
2965 constructor() {
2966 this.children = [];
2967 this.variables = new Map();
2968 }
2969 addDeclaration(identifier, context, init = null, _isHoisted) {
2970 const name = identifier.name;
2971 let variable = this.variables.get(name);
2972 if (variable) {
2973 variable.addDeclaration(identifier, init);
2974 }
2975 else {
2976 variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
2977 this.variables.set(name, variable);
2978 }
2979 return variable;
2980 }
2981 contains(name) {
2982 return this.variables.has(name);
2983 }
2984 findVariable(_name) {
2985 throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
2986 }
2987}
2988
2989class ChildScope extends Scope {
2990 constructor(parent) {
2991 super();
2992 this.accessedOutsideVariables = new Map();
2993 this.parent = parent;
2994 parent.children.push(this);
2995 }
2996 addAccessedGlobalsByFormat(globalsByFormat) {
2997 let accessedGlobalVariablesByFormat = this.accessedGlobalVariablesByFormat;
2998 if (!accessedGlobalVariablesByFormat) {
2999 accessedGlobalVariablesByFormat = this.accessedGlobalVariablesByFormat = new Map();
3000 }
3001 for (const format of Object.keys(globalsByFormat)) {
3002 let accessedGlobalVariables = accessedGlobalVariablesByFormat.get(format);
3003 if (!accessedGlobalVariables) {
3004 accessedGlobalVariables = new Set();
3005 accessedGlobalVariablesByFormat.set(format, accessedGlobalVariables);
3006 }
3007 for (const name of globalsByFormat[format]) {
3008 accessedGlobalVariables.add(name);
3009 }
3010 }
3011 if (this.parent instanceof ChildScope) {
3012 this.parent.addAccessedGlobalsByFormat(globalsByFormat);
3013 }
3014 }
3015 addNamespaceMemberAccess(name, variable) {
3016 this.accessedOutsideVariables.set(name, variable);
3017 if (this.parent instanceof ChildScope) {
3018 this.parent.addNamespaceMemberAccess(name, variable);
3019 }
3020 }
3021 addReturnExpression(expression) {
3022 this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
3023 }
3024 contains(name) {
3025 return this.variables.has(name) || this.parent.contains(name);
3026 }
3027 deconflict(format) {
3028 const usedNames = new Set();
3029 for (const variable of this.accessedOutsideVariables.values()) {
3030 if (variable.included) {
3031 usedNames.add(variable.getBaseVariableName());
3032 if (variable.exportName && format === 'system') {
3033 usedNames.add('exports');
3034 }
3035 }
3036 }
3037 const accessedGlobalVariables = this.accessedGlobalVariablesByFormat && this.accessedGlobalVariablesByFormat.get(format);
3038 if (accessedGlobalVariables) {
3039 for (const name of accessedGlobalVariables) {
3040 usedNames.add(name);
3041 }
3042 }
3043 for (const [name, variable] of this.variables) {
3044 if (variable.included || variable.alwaysRendered) {
3045 variable.setSafeName(getSafeName(name, usedNames));
3046 }
3047 }
3048 for (const scope of this.children) {
3049 scope.deconflict(format);
3050 }
3051 }
3052 findLexicalBoundary() {
3053 return this.parent instanceof ChildScope ? this.parent.findLexicalBoundary() : this;
3054 }
3055 findVariable(name) {
3056 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
3057 if (knownVariable) {
3058 return knownVariable;
3059 }
3060 const variable = this.parent.findVariable(name);
3061 this.accessedOutsideVariables.set(name, variable);
3062 return variable;
3063 }
3064}
3065
3066function getLocator$1(source, options) {
3067 if (options === void 0) {
3068 options = {};
3069 }
3070 var offsetLine = options.offsetLine || 0;
3071 var offsetColumn = options.offsetColumn || 0;
3072 var originalLines = source.split('\n');
3073 var start = 0;
3074 var lineRanges = originalLines.map(function (line, i) {
3075 var end = start + line.length + 1;
3076 var range = { start: start, end: end, line: i };
3077 start = end;
3078 return range;
3079 });
3080 var i = 0;
3081 function rangeContains(range, index) {
3082 return range.start <= index && index < range.end;
3083 }
3084 function getLocation(range, index) {
3085 return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
3086 }
3087 function locate(search, startIndex) {
3088 if (typeof search === 'string') {
3089 search = source.indexOf(search, startIndex || 0);
3090 }
3091 var range = lineRanges[i];
3092 var d = search >= range.end ? 1 : -1;
3093 while (range) {
3094 if (rangeContains(range, search))
3095 return getLocation(range, search);
3096 i += d;
3097 range = lineRanges[i];
3098 }
3099 }
3100 return locate;
3101}
3102function locate(source, search, options) {
3103 if (typeof options === 'number') {
3104 throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
3105 }
3106 return getLocator$1(source, options)(search, options && options.startIndex);
3107}
3108
3109const keys = {
3110 Literal: [],
3111 Program: ['body']
3112};
3113function getAndCreateKeys(esTreeNode) {
3114 keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object');
3115 return keys[esTreeNode.type];
3116}
3117
3118const INCLUDE_PARAMETERS = 'variables';
3119class NodeBase {
3120 constructor(esTreeNode, parent, parentScope) {
3121 this.included = false;
3122 this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
3123 this.parent = parent;
3124 this.context = parent.context;
3125 this.createScope(parentScope);
3126 this.parseNode(esTreeNode);
3127 this.initialise();
3128 this.context.magicString.addSourcemapLocation(this.start);
3129 this.context.magicString.addSourcemapLocation(this.end);
3130 }
3131 /**
3132 * Override this to bind assignments to variables and do any initialisations that
3133 * require the scopes to be populated with variables.
3134 */
3135 bind() {
3136 for (const key of this.keys) {
3137 const value = this[key];
3138 if (value === null || key === 'annotations')
3139 continue;
3140 if (Array.isArray(value)) {
3141 for (const child of value) {
3142 if (child !== null)
3143 child.bind();
3144 }
3145 }
3146 else {
3147 value.bind();
3148 }
3149 }
3150 }
3151 /**
3152 * Override if this node should receive a different scope than the parent scope.
3153 */
3154 createScope(parentScope) {
3155 this.scope = parentScope;
3156 }
3157 declare(_kind, _init) {
3158 return [];
3159 }
3160 deoptimizePath(_path) { }
3161 getLiteralValueAtPath(_path, _recursionTracker, _origin) {
3162 return UnknownValue;
3163 }
3164 getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
3165 return UNKNOWN_EXPRESSION;
3166 }
3167 hasEffects(context) {
3168 for (const key of this.keys) {
3169 const value = this[key];
3170 if (value === null || key === 'annotations')
3171 continue;
3172 if (Array.isArray(value)) {
3173 for (const child of value) {
3174 if (child !== null && child.hasEffects(context))
3175 return true;
3176 }
3177 }
3178 else if (value.hasEffects(context))
3179 return true;
3180 }
3181 return false;
3182 }
3183 hasEffectsWhenAccessedAtPath(path, _context) {
3184 return path.length > 0;
3185 }
3186 hasEffectsWhenAssignedAtPath(_path, _context) {
3187 return true;
3188 }
3189 hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
3190 return true;
3191 }
3192 include(context, includeChildrenRecursively) {
3193 this.included = true;
3194 for (const key of this.keys) {
3195 const value = this[key];
3196 if (value === null || key === 'annotations')
3197 continue;
3198 if (Array.isArray(value)) {
3199 for (const child of value) {
3200 if (child !== null)
3201 child.include(context, includeChildrenRecursively);
3202 }
3203 }
3204 else {
3205 value.include(context, includeChildrenRecursively);
3206 }
3207 }
3208 }
3209 includeCallArguments(context, args) {
3210 for (const arg of args) {
3211 arg.include(context, false);
3212 }
3213 }
3214 includeWithAllDeclaredVariables(includeChildrenRecursively, context) {
3215 this.include(context, includeChildrenRecursively);
3216 }
3217 /**
3218 * Override to perform special initialisation steps after the scope is initialised
3219 */
3220 initialise() { }
3221 insertSemicolon(code) {
3222 if (code.original[this.end - 1] !== ';') {
3223 code.appendLeft(this.end, ';');
3224 }
3225 }
3226 locate() {
3227 // useful for debugging
3228 const location = locate(this.context.code, this.start, { offsetLine: 1 });
3229 location.file = this.context.fileName;
3230 location.toString = () => JSON.stringify(location);
3231 return location;
3232 }
3233 parseNode(esTreeNode) {
3234 for (const key of Object.keys(esTreeNode)) {
3235 // That way, we can override this function to add custom initialisation and then call super.parseNode
3236 if (this.hasOwnProperty(key))
3237 continue;
3238 const value = esTreeNode[key];
3239 if (typeof value !== 'object' || value === null || key === 'annotations') {
3240 this[key] = value;
3241 }
3242 else if (Array.isArray(value)) {
3243 this[key] = [];
3244 for (const child of value) {
3245 this[key].push(child === null
3246 ? null
3247 : new (this.context.nodeConstructors[child.type] ||
3248 this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
3249 }
3250 }
3251 else {
3252 this[key] = new (this.context.nodeConstructors[value.type] ||
3253 this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
3254 }
3255 }
3256 }
3257 render(code, options) {
3258 for (const key of this.keys) {
3259 const value = this[key];
3260 if (value === null || key === 'annotations')
3261 continue;
3262 if (Array.isArray(value)) {
3263 for (const child of value) {
3264 if (child !== null)
3265 child.render(code, options);
3266 }
3267 }
3268 else {
3269 value.render(code, options);
3270 }
3271 }
3272 }
3273 shouldBeIncluded(context) {
3274 return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
3275 }
3276 toString() {
3277 return this.context.code.slice(this.start, this.end);
3278 }
3279}
3280
3281class ClassNode extends NodeBase {
3282 createScope(parentScope) {
3283 this.scope = new ChildScope(parentScope);
3284 }
3285 hasEffectsWhenAccessedAtPath(path) {
3286 return path.length > 1;
3287 }
3288 hasEffectsWhenAssignedAtPath(path) {
3289 return path.length > 1;
3290 }
3291 hasEffectsWhenCalledAtPath(path, callOptions, context) {
3292 if (!callOptions.withNew)
3293 return true;
3294 return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
3295 (this.superClass !== null &&
3296 this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, context)));
3297 }
3298 initialise() {
3299 if (this.id !== null) {
3300 this.id.declare('class', this);
3301 }
3302 }
3303}
3304
3305class ClassDeclaration extends ClassNode {
3306 initialise() {
3307 super.initialise();
3308 if (this.id !== null) {
3309 this.id.variable.isId = true;
3310 }
3311 }
3312 parseNode(esTreeNode) {
3313 if (esTreeNode.id !== null) {
3314 this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope
3315 .parent);
3316 }
3317 super.parseNode(esTreeNode);
3318 }
3319 render(code, options) {
3320 if (options.format === 'system' && this.id && this.id.variable.exportName) {
3321 code.appendLeft(this.end, ` exports('${this.id.variable.exportName}', ${this.id.variable.getName()});`);
3322 }
3323 super.render(code, options);
3324 }
3325}
3326
3327class ArgumentsVariable extends LocalVariable {
3328 constructor(context) {
3329 super('arguments', null, UNKNOWN_EXPRESSION, context);
3330 }
3331 hasEffectsWhenAccessedAtPath(path) {
3332 return path.length > 1;
3333 }
3334 hasEffectsWhenAssignedAtPath() {
3335 return true;
3336 }
3337 hasEffectsWhenCalledAtPath() {
3338 return true;
3339 }
3340}
3341
3342class ThisVariable extends LocalVariable {
3343 constructor(context) {
3344 super('this', null, null, context);
3345 }
3346 getLiteralValueAtPath() {
3347 return UnknownValue;
3348 }
3349 hasEffectsWhenAccessedAtPath(path, context) {
3350 return (this.getInit(context).hasEffectsWhenAccessedAtPath(path, context) ||
3351 super.hasEffectsWhenAccessedAtPath(path, context));
3352 }
3353 hasEffectsWhenAssignedAtPath(path, context) {
3354 return (this.getInit(context).hasEffectsWhenAssignedAtPath(path, context) ||
3355 super.hasEffectsWhenAssignedAtPath(path, context));
3356 }
3357 hasEffectsWhenCalledAtPath(path, callOptions, context) {
3358 return (this.getInit(context).hasEffectsWhenCalledAtPath(path, callOptions, context) ||
3359 super.hasEffectsWhenCalledAtPath(path, callOptions, context));
3360 }
3361 getInit(context) {
3362 return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
3363 }
3364}
3365
3366class ParameterScope extends ChildScope {
3367 constructor(parent, context) {
3368 super(parent);
3369 this.parameters = [];
3370 this.hasRest = false;
3371 this.context = context;
3372 this.hoistedBodyVarScope = new ChildScope(this);
3373 }
3374 /**
3375 * Adds a parameter to this scope. Parameters must be added in the correct
3376 * order, e.g. from left to right.
3377 */
3378 addParameterDeclaration(identifier) {
3379 const name = identifier.name;
3380 let variable = this.hoistedBodyVarScope.variables.get(name);
3381 if (variable) {
3382 variable.addDeclaration(identifier, null);
3383 }
3384 else {
3385 variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
3386 }
3387 this.variables.set(name, variable);
3388 return variable;
3389 }
3390 addParameterVariables(parameters, hasRest) {
3391 this.parameters = parameters;
3392 for (const parameterList of parameters) {
3393 for (const parameter of parameterList) {
3394 parameter.alwaysRendered = true;
3395 }
3396 }
3397 this.hasRest = hasRest;
3398 }
3399 includeCallArguments(context, args) {
3400 let calledFromTryStatement = false;
3401 let argIncluded = false;
3402 const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
3403 for (let index = args.length - 1; index >= 0; index--) {
3404 const paramVars = this.parameters[index] || restParam;
3405 const arg = args[index];
3406 if (paramVars) {
3407 calledFromTryStatement = false;
3408 for (const variable of paramVars) {
3409 if (variable.included) {
3410 argIncluded = true;
3411 }
3412 if (variable.calledFromTryStatement) {
3413 calledFromTryStatement = true;
3414 }
3415 }
3416 }
3417 if (!argIncluded && arg.shouldBeIncluded(context)) {
3418 argIncluded = true;
3419 }
3420 if (argIncluded) {
3421 arg.include(context, calledFromTryStatement);
3422 }
3423 }
3424 }
3425}
3426
3427class ReturnValueScope extends ParameterScope {
3428 constructor() {
3429 super(...arguments);
3430 this.returnExpression = null;
3431 this.returnExpressions = [];
3432 }
3433 addReturnExpression(expression) {
3434 this.returnExpressions.push(expression);
3435 }
3436 getReturnExpression() {
3437 if (this.returnExpression === null)
3438 this.updateReturnExpression();
3439 return this.returnExpression;
3440 }
3441 updateReturnExpression() {
3442 if (this.returnExpressions.length === 1) {
3443 this.returnExpression = this.returnExpressions[0];
3444 }
3445 else {
3446 this.returnExpression = UNKNOWN_EXPRESSION;
3447 for (const expression of this.returnExpressions) {
3448 expression.deoptimizePath(UNKNOWN_PATH);
3449 }
3450 }
3451 }
3452}
3453
3454class FunctionScope extends ReturnValueScope {
3455 constructor(parent, context) {
3456 super(parent, context);
3457 this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
3458 this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
3459 }
3460 findLexicalBoundary() {
3461 return this;
3462 }
3463 includeCallArguments(context, args) {
3464 super.includeCallArguments(context, args);
3465 if (this.argumentsVariable.included) {
3466 for (const arg of args) {
3467 if (!arg.included) {
3468 arg.include(context, false);
3469 }
3470 }
3471 }
3472 }
3473}
3474
3475function isReference(node, parent) {
3476 if (node.type === 'MemberExpression') {
3477 return !node.computed && isReference(node.object, node);
3478 }
3479 if (node.type === 'Identifier') {
3480 if (!parent)
3481 return true;
3482 switch (parent.type) {
3483 // disregard `bar` in `foo.bar`
3484 case 'MemberExpression': return parent.computed || node === parent.object;
3485 // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
3486 case 'MethodDefinition': return parent.computed;
3487 // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
3488 case 'Property': return parent.computed || node === parent.value;
3489 // disregard the `bar` in `export { foo as bar }` or
3490 // the foo in `import { foo as bar }`
3491 case 'ExportSpecifier':
3492 case 'ImportSpecifier': return node === parent.local;
3493 // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
3494 case 'LabeledStatement':
3495 case 'BreakStatement':
3496 case 'ContinueStatement': return false;
3497 default: return true;
3498 }
3499 }
3500 return false;
3501}
3502
3503const ValueProperties = Symbol('Value Properties');
3504const PURE = { pure: true };
3505const IMPURE = { pure: false };
3506// We use shortened variables to reduce file size here
3507/* OBJECT */
3508const O = {
3509 // @ts-ignore
3510 __proto__: null,
3511 [ValueProperties]: IMPURE
3512};
3513/* PURE FUNCTION */
3514const PF = {
3515 // @ts-ignore
3516 __proto__: null,
3517 [ValueProperties]: PURE
3518};
3519/* CONSTRUCTOR */
3520const C = {
3521 // @ts-ignore
3522 __proto__: null,
3523 [ValueProperties]: IMPURE,
3524 prototype: O
3525};
3526/* PURE CONSTRUCTOR */
3527const PC = {
3528 // @ts-ignore
3529 __proto__: null,
3530 [ValueProperties]: PURE,
3531 prototype: O
3532};
3533const ARRAY_TYPE = {
3534 // @ts-ignore
3535 __proto__: null,
3536 [ValueProperties]: PURE,
3537 from: PF,
3538 of: PF,
3539 prototype: O
3540};
3541const INTL_MEMBER = {
3542 // @ts-ignore
3543 __proto__: null,
3544 [ValueProperties]: PURE,
3545 supportedLocalesOf: PC
3546};
3547const knownGlobals = {
3548 // Placeholders for global objects to avoid shape mutations
3549 global: O,
3550 globalThis: O,
3551 self: O,
3552 window: O,
3553 // Common globals
3554 // @ts-ignore
3555 __proto__: null,
3556 [ValueProperties]: IMPURE,
3557 Array: {
3558 // @ts-ignore
3559 __proto__: null,
3560 [ValueProperties]: IMPURE,
3561 from: PF,
3562 isArray: PF,
3563 of: PF,
3564 prototype: O
3565 },
3566 ArrayBuffer: {
3567 // @ts-ignore
3568 __proto__: null,
3569 [ValueProperties]: PURE,
3570 isView: PF,
3571 prototype: O
3572 },
3573 Atomics: O,
3574 BigInt: C,
3575 BigInt64Array: C,
3576 BigUint64Array: C,
3577 Boolean: PC,
3578 // @ts-ignore
3579 constructor: C,
3580 DataView: PC,
3581 Date: {
3582 // @ts-ignore
3583 __proto__: null,
3584 [ValueProperties]: PURE,
3585 now: PF,
3586 parse: PF,
3587 prototype: O,
3588 UTC: PF
3589 },
3590 decodeURI: PF,
3591 decodeURIComponent: PF,
3592 encodeURI: PF,
3593 encodeURIComponent: PF,
3594 Error: PC,
3595 escape: PF,
3596 eval: O,
3597 EvalError: PC,
3598 Float32Array: ARRAY_TYPE,
3599 Float64Array: ARRAY_TYPE,
3600 Function: C,
3601 // @ts-ignore
3602 hasOwnProperty: O,
3603 Infinity: O,
3604 Int16Array: ARRAY_TYPE,
3605 Int32Array: ARRAY_TYPE,
3606 Int8Array: ARRAY_TYPE,
3607 isFinite: PF,
3608 isNaN: PF,
3609 // @ts-ignore
3610 isPrototypeOf: O,
3611 JSON: O,
3612 Map: PC,
3613 Math: {
3614 // @ts-ignore
3615 __proto__: null,
3616 [ValueProperties]: IMPURE,
3617 abs: PF,
3618 acos: PF,
3619 acosh: PF,
3620 asin: PF,
3621 asinh: PF,
3622 atan: PF,
3623 atan2: PF,
3624 atanh: PF,
3625 cbrt: PF,
3626 ceil: PF,
3627 clz32: PF,
3628 cos: PF,
3629 cosh: PF,
3630 exp: PF,
3631 expm1: PF,
3632 floor: PF,
3633 fround: PF,
3634 hypot: PF,
3635 imul: PF,
3636 log: PF,
3637 log10: PF,
3638 log1p: PF,
3639 log2: PF,
3640 max: PF,
3641 min: PF,
3642 pow: PF,
3643 random: PF,
3644 round: PF,
3645 sign: PF,
3646 sin: PF,
3647 sinh: PF,
3648 sqrt: PF,
3649 tan: PF,
3650 tanh: PF,
3651 trunc: PF
3652 },
3653 NaN: O,
3654 Number: {
3655 // @ts-ignore
3656 __proto__: null,
3657 [ValueProperties]: PURE,
3658 isFinite: PF,
3659 isInteger: PF,
3660 isNaN: PF,
3661 isSafeInteger: PF,
3662 parseFloat: PF,
3663 parseInt: PF,
3664 prototype: O
3665 },
3666 Object: {
3667 // @ts-ignore
3668 __proto__: null,
3669 [ValueProperties]: PURE,
3670 create: PF,
3671 getNotifier: PF,
3672 getOwn: PF,
3673 getOwnPropertyDescriptor: PF,
3674 getOwnPropertyNames: PF,
3675 getOwnPropertySymbols: PF,
3676 getPrototypeOf: PF,
3677 is: PF,
3678 isExtensible: PF,
3679 isFrozen: PF,
3680 isSealed: PF,
3681 keys: PF,
3682 prototype: O
3683 },
3684 parseFloat: PF,
3685 parseInt: PF,
3686 Promise: {
3687 // @ts-ignore
3688 __proto__: null,
3689 [ValueProperties]: IMPURE,
3690 all: PF,
3691 prototype: O,
3692 race: PF,
3693 resolve: PF
3694 },
3695 // @ts-ignore
3696 propertyIsEnumerable: O,
3697 Proxy: O,
3698 RangeError: PC,
3699 ReferenceError: PC,
3700 Reflect: O,
3701 RegExp: PC,
3702 Set: PC,
3703 SharedArrayBuffer: C,
3704 String: {
3705 // @ts-ignore
3706 __proto__: null,
3707 [ValueProperties]: PURE,
3708 fromCharCode: PF,
3709 fromCodePoint: PF,
3710 prototype: O,
3711 raw: PF
3712 },
3713 Symbol: {
3714 // @ts-ignore
3715 __proto__: null,
3716 [ValueProperties]: PURE,
3717 for: PF,
3718 keyFor: PF,
3719 prototype: O
3720 },
3721 SyntaxError: PC,
3722 // @ts-ignore
3723 toLocaleString: O,
3724 // @ts-ignore
3725 toString: O,
3726 TypeError: PC,
3727 Uint16Array: ARRAY_TYPE,
3728 Uint32Array: ARRAY_TYPE,
3729 Uint8Array: ARRAY_TYPE,
3730 Uint8ClampedArray: ARRAY_TYPE,
3731 // Technically, this is a global, but it needs special handling
3732 // undefined: ?,
3733 unescape: PF,
3734 URIError: PC,
3735 // @ts-ignore
3736 valueOf: O,
3737 WeakMap: PC,
3738 WeakSet: PC,
3739 // Additional globals shared by Node and Browser that are not strictly part of the language
3740 clearInterval: C,
3741 clearTimeout: C,
3742 console: O,
3743 Intl: {
3744 // @ts-ignore
3745 __proto__: null,
3746 [ValueProperties]: IMPURE,
3747 Collator: INTL_MEMBER,
3748 DateTimeFormat: INTL_MEMBER,
3749 ListFormat: INTL_MEMBER,
3750 NumberFormat: INTL_MEMBER,
3751 PluralRules: INTL_MEMBER,
3752 RelativeTimeFormat: INTL_MEMBER
3753 },
3754 setInterval: C,
3755 setTimeout: C,
3756 TextDecoder: C,
3757 TextEncoder: C,
3758 URL: C,
3759 URLSearchParams: C,
3760 // Browser specific globals
3761 AbortController: C,
3762 AbortSignal: C,
3763 addEventListener: O,
3764 alert: O,
3765 AnalyserNode: C,
3766 Animation: C,
3767 AnimationEvent: C,
3768 applicationCache: O,
3769 ApplicationCache: C,
3770 ApplicationCacheErrorEvent: C,
3771 atob: O,
3772 Attr: C,
3773 Audio: C,
3774 AudioBuffer: C,
3775 AudioBufferSourceNode: C,
3776 AudioContext: C,
3777 AudioDestinationNode: C,
3778 AudioListener: C,
3779 AudioNode: C,
3780 AudioParam: C,
3781 AudioProcessingEvent: C,
3782 AudioScheduledSourceNode: C,
3783 AudioWorkletNode: C,
3784 BarProp: C,
3785 BaseAudioContext: C,
3786 BatteryManager: C,
3787 BeforeUnloadEvent: C,
3788 BiquadFilterNode: C,
3789 Blob: C,
3790 BlobEvent: C,
3791 blur: O,
3792 BroadcastChannel: C,
3793 btoa: O,
3794 ByteLengthQueuingStrategy: C,
3795 Cache: C,
3796 caches: O,
3797 CacheStorage: C,
3798 cancelAnimationFrame: O,
3799 cancelIdleCallback: O,
3800 CanvasCaptureMediaStreamTrack: C,
3801 CanvasGradient: C,
3802 CanvasPattern: C,
3803 CanvasRenderingContext2D: C,
3804 ChannelMergerNode: C,
3805 ChannelSplitterNode: C,
3806 CharacterData: C,
3807 clientInformation: O,
3808 ClipboardEvent: C,
3809 close: O,
3810 closed: O,
3811 CloseEvent: C,
3812 Comment: C,
3813 CompositionEvent: C,
3814 confirm: O,
3815 ConstantSourceNode: C,
3816 ConvolverNode: C,
3817 CountQueuingStrategy: C,
3818 createImageBitmap: O,
3819 Credential: C,
3820 CredentialsContainer: C,
3821 crypto: O,
3822 Crypto: C,
3823 CryptoKey: C,
3824 CSS: C,
3825 CSSConditionRule: C,
3826 CSSFontFaceRule: C,
3827 CSSGroupingRule: C,
3828 CSSImportRule: C,
3829 CSSKeyframeRule: C,
3830 CSSKeyframesRule: C,
3831 CSSMediaRule: C,
3832 CSSNamespaceRule: C,
3833 CSSPageRule: C,
3834 CSSRule: C,
3835 CSSRuleList: C,
3836 CSSStyleDeclaration: C,
3837 CSSStyleRule: C,
3838 CSSStyleSheet: C,
3839 CSSSupportsRule: C,
3840 CustomElementRegistry: C,
3841 customElements: O,
3842 CustomEvent: C,
3843 DataTransfer: C,
3844 DataTransferItem: C,
3845 DataTransferItemList: C,
3846 defaultstatus: O,
3847 defaultStatus: O,
3848 DelayNode: C,
3849 DeviceMotionEvent: C,
3850 DeviceOrientationEvent: C,
3851 devicePixelRatio: O,
3852 dispatchEvent: O,
3853 document: O,
3854 Document: C,
3855 DocumentFragment: C,
3856 DocumentType: C,
3857 DOMError: C,
3858 DOMException: C,
3859 DOMImplementation: C,
3860 DOMMatrix: C,
3861 DOMMatrixReadOnly: C,
3862 DOMParser: C,
3863 DOMPoint: C,
3864 DOMPointReadOnly: C,
3865 DOMQuad: C,
3866 DOMRect: C,
3867 DOMRectReadOnly: C,
3868 DOMStringList: C,
3869 DOMStringMap: C,
3870 DOMTokenList: C,
3871 DragEvent: C,
3872 DynamicsCompressorNode: C,
3873 Element: C,
3874 ErrorEvent: C,
3875 Event: C,
3876 EventSource: C,
3877 EventTarget: C,
3878 external: O,
3879 fetch: O,
3880 File: C,
3881 FileList: C,
3882 FileReader: C,
3883 find: O,
3884 focus: O,
3885 FocusEvent: C,
3886 FontFace: C,
3887 FontFaceSetLoadEvent: C,
3888 FormData: C,
3889 frames: O,
3890 GainNode: C,
3891 Gamepad: C,
3892 GamepadButton: C,
3893 GamepadEvent: C,
3894 getComputedStyle: O,
3895 getSelection: O,
3896 HashChangeEvent: C,
3897 Headers: C,
3898 history: O,
3899 History: C,
3900 HTMLAllCollection: C,
3901 HTMLAnchorElement: C,
3902 HTMLAreaElement: C,
3903 HTMLAudioElement: C,
3904 HTMLBaseElement: C,
3905 HTMLBodyElement: C,
3906 HTMLBRElement: C,
3907 HTMLButtonElement: C,
3908 HTMLCanvasElement: C,
3909 HTMLCollection: C,
3910 HTMLContentElement: C,
3911 HTMLDataElement: C,
3912 HTMLDataListElement: C,
3913 HTMLDetailsElement: C,
3914 HTMLDialogElement: C,
3915 HTMLDirectoryElement: C,
3916 HTMLDivElement: C,
3917 HTMLDListElement: C,
3918 HTMLDocument: C,
3919 HTMLElement: C,
3920 HTMLEmbedElement: C,
3921 HTMLFieldSetElement: C,
3922 HTMLFontElement: C,
3923 HTMLFormControlsCollection: C,
3924 HTMLFormElement: C,
3925 HTMLFrameElement: C,
3926 HTMLFrameSetElement: C,
3927 HTMLHeadElement: C,
3928 HTMLHeadingElement: C,
3929 HTMLHRElement: C,
3930 HTMLHtmlElement: C,
3931 HTMLIFrameElement: C,
3932 HTMLImageElement: C,
3933 HTMLInputElement: C,
3934 HTMLLabelElement: C,
3935 HTMLLegendElement: C,
3936 HTMLLIElement: C,
3937 HTMLLinkElement: C,
3938 HTMLMapElement: C,
3939 HTMLMarqueeElement: C,
3940 HTMLMediaElement: C,
3941 HTMLMenuElement: C,
3942 HTMLMetaElement: C,
3943 HTMLMeterElement: C,
3944 HTMLModElement: C,
3945 HTMLObjectElement: C,
3946 HTMLOListElement: C,
3947 HTMLOptGroupElement: C,
3948 HTMLOptionElement: C,
3949 HTMLOptionsCollection: C,
3950 HTMLOutputElement: C,
3951 HTMLParagraphElement: C,
3952 HTMLParamElement: C,
3953 HTMLPictureElement: C,
3954 HTMLPreElement: C,
3955 HTMLProgressElement: C,
3956 HTMLQuoteElement: C,
3957 HTMLScriptElement: C,
3958 HTMLSelectElement: C,
3959 HTMLShadowElement: C,
3960 HTMLSlotElement: C,
3961 HTMLSourceElement: C,
3962 HTMLSpanElement: C,
3963 HTMLStyleElement: C,
3964 HTMLTableCaptionElement: C,
3965 HTMLTableCellElement: C,
3966 HTMLTableColElement: C,
3967 HTMLTableElement: C,
3968 HTMLTableRowElement: C,
3969 HTMLTableSectionElement: C,
3970 HTMLTemplateElement: C,
3971 HTMLTextAreaElement: C,
3972 HTMLTimeElement: C,
3973 HTMLTitleElement: C,
3974 HTMLTrackElement: C,
3975 HTMLUListElement: C,
3976 HTMLUnknownElement: C,
3977 HTMLVideoElement: C,
3978 IDBCursor: C,
3979 IDBCursorWithValue: C,
3980 IDBDatabase: C,
3981 IDBFactory: C,
3982 IDBIndex: C,
3983 IDBKeyRange: C,
3984 IDBObjectStore: C,
3985 IDBOpenDBRequest: C,
3986 IDBRequest: C,
3987 IDBTransaction: C,
3988 IDBVersionChangeEvent: C,
3989 IdleDeadline: C,
3990 IIRFilterNode: C,
3991 Image: C,
3992 ImageBitmap: C,
3993 ImageBitmapRenderingContext: C,
3994 ImageCapture: C,
3995 ImageData: C,
3996 indexedDB: O,
3997 innerHeight: O,
3998 innerWidth: O,
3999 InputEvent: C,
4000 IntersectionObserver: C,
4001 IntersectionObserverEntry: C,
4002 isSecureContext: O,
4003 KeyboardEvent: C,
4004 KeyframeEffect: C,
4005 length: O,
4006 localStorage: O,
4007 location: O,
4008 Location: C,
4009 locationbar: O,
4010 matchMedia: O,
4011 MediaDeviceInfo: C,
4012 MediaDevices: C,
4013 MediaElementAudioSourceNode: C,
4014 MediaEncryptedEvent: C,
4015 MediaError: C,
4016 MediaKeyMessageEvent: C,
4017 MediaKeySession: C,
4018 MediaKeyStatusMap: C,
4019 MediaKeySystemAccess: C,
4020 MediaList: C,
4021 MediaQueryList: C,
4022 MediaQueryListEvent: C,
4023 MediaRecorder: C,
4024 MediaSettingsRange: C,
4025 MediaSource: C,
4026 MediaStream: C,
4027 MediaStreamAudioDestinationNode: C,
4028 MediaStreamAudioSourceNode: C,
4029 MediaStreamEvent: C,
4030 MediaStreamTrack: C,
4031 MediaStreamTrackEvent: C,
4032 menubar: O,
4033 MessageChannel: C,
4034 MessageEvent: C,
4035 MessagePort: C,
4036 MIDIAccess: C,
4037 MIDIConnectionEvent: C,
4038 MIDIInput: C,
4039 MIDIInputMap: C,
4040 MIDIMessageEvent: C,
4041 MIDIOutput: C,
4042 MIDIOutputMap: C,
4043 MIDIPort: C,
4044 MimeType: C,
4045 MimeTypeArray: C,
4046 MouseEvent: C,
4047 moveBy: O,
4048 moveTo: O,
4049 MutationEvent: C,
4050 MutationObserver: C,
4051 MutationRecord: C,
4052 name: O,
4053 NamedNodeMap: C,
4054 NavigationPreloadManager: C,
4055 navigator: O,
4056 Navigator: C,
4057 NetworkInformation: C,
4058 Node: C,
4059 NodeFilter: O,
4060 NodeIterator: C,
4061 NodeList: C,
4062 Notification: C,
4063 OfflineAudioCompletionEvent: C,
4064 OfflineAudioContext: C,
4065 offscreenBuffering: O,
4066 OffscreenCanvas: C,
4067 open: O,
4068 openDatabase: O,
4069 Option: C,
4070 origin: O,
4071 OscillatorNode: C,
4072 outerHeight: O,
4073 outerWidth: O,
4074 PageTransitionEvent: C,
4075 pageXOffset: O,
4076 pageYOffset: O,
4077 PannerNode: C,
4078 parent: O,
4079 Path2D: C,
4080 PaymentAddress: C,
4081 PaymentRequest: C,
4082 PaymentRequestUpdateEvent: C,
4083 PaymentResponse: C,
4084 performance: O,
4085 Performance: C,
4086 PerformanceEntry: C,
4087 PerformanceLongTaskTiming: C,
4088 PerformanceMark: C,
4089 PerformanceMeasure: C,
4090 PerformanceNavigation: C,
4091 PerformanceNavigationTiming: C,
4092 PerformanceObserver: C,
4093 PerformanceObserverEntryList: C,
4094 PerformancePaintTiming: C,
4095 PerformanceResourceTiming: C,
4096 PerformanceTiming: C,
4097 PeriodicWave: C,
4098 Permissions: C,
4099 PermissionStatus: C,
4100 personalbar: O,
4101 PhotoCapabilities: C,
4102 Plugin: C,
4103 PluginArray: C,
4104 PointerEvent: C,
4105 PopStateEvent: C,
4106 postMessage: O,
4107 Presentation: C,
4108 PresentationAvailability: C,
4109 PresentationConnection: C,
4110 PresentationConnectionAvailableEvent: C,
4111 PresentationConnectionCloseEvent: C,
4112 PresentationConnectionList: C,
4113 PresentationReceiver: C,
4114 PresentationRequest: C,
4115 print: O,
4116 ProcessingInstruction: C,
4117 ProgressEvent: C,
4118 PromiseRejectionEvent: C,
4119 prompt: O,
4120 PushManager: C,
4121 PushSubscription: C,
4122 PushSubscriptionOptions: C,
4123 queueMicrotask: O,
4124 RadioNodeList: C,
4125 Range: C,
4126 ReadableStream: C,
4127 RemotePlayback: C,
4128 removeEventListener: O,
4129 Request: C,
4130 requestAnimationFrame: O,
4131 requestIdleCallback: O,
4132 resizeBy: O,
4133 ResizeObserver: C,
4134 ResizeObserverEntry: C,
4135 resizeTo: O,
4136 Response: C,
4137 RTCCertificate: C,
4138 RTCDataChannel: C,
4139 RTCDataChannelEvent: C,
4140 RTCDtlsTransport: C,
4141 RTCIceCandidate: C,
4142 RTCIceTransport: C,
4143 RTCPeerConnection: C,
4144 RTCPeerConnectionIceEvent: C,
4145 RTCRtpReceiver: C,
4146 RTCRtpSender: C,
4147 RTCSctpTransport: C,
4148 RTCSessionDescription: C,
4149 RTCStatsReport: C,
4150 RTCTrackEvent: C,
4151 screen: O,
4152 Screen: C,
4153 screenLeft: O,
4154 ScreenOrientation: C,
4155 screenTop: O,
4156 screenX: O,
4157 screenY: O,
4158 ScriptProcessorNode: C,
4159 scroll: O,
4160 scrollbars: O,
4161 scrollBy: O,
4162 scrollTo: O,
4163 scrollX: O,
4164 scrollY: O,
4165 SecurityPolicyViolationEvent: C,
4166 Selection: C,
4167 ServiceWorker: C,
4168 ServiceWorkerContainer: C,
4169 ServiceWorkerRegistration: C,
4170 sessionStorage: O,
4171 ShadowRoot: C,
4172 SharedWorker: C,
4173 SourceBuffer: C,
4174 SourceBufferList: C,
4175 speechSynthesis: O,
4176 SpeechSynthesisEvent: C,
4177 SpeechSynthesisUtterance: C,
4178 StaticRange: C,
4179 status: O,
4180 statusbar: O,
4181 StereoPannerNode: C,
4182 stop: O,
4183 Storage: C,
4184 StorageEvent: C,
4185 StorageManager: C,
4186 styleMedia: O,
4187 StyleSheet: C,
4188 StyleSheetList: C,
4189 SubtleCrypto: C,
4190 SVGAElement: C,
4191 SVGAngle: C,
4192 SVGAnimatedAngle: C,
4193 SVGAnimatedBoolean: C,
4194 SVGAnimatedEnumeration: C,
4195 SVGAnimatedInteger: C,
4196 SVGAnimatedLength: C,
4197 SVGAnimatedLengthList: C,
4198 SVGAnimatedNumber: C,
4199 SVGAnimatedNumberList: C,
4200 SVGAnimatedPreserveAspectRatio: C,
4201 SVGAnimatedRect: C,
4202 SVGAnimatedString: C,
4203 SVGAnimatedTransformList: C,
4204 SVGAnimateElement: C,
4205 SVGAnimateMotionElement: C,
4206 SVGAnimateTransformElement: C,
4207 SVGAnimationElement: C,
4208 SVGCircleElement: C,
4209 SVGClipPathElement: C,
4210 SVGComponentTransferFunctionElement: C,
4211 SVGDefsElement: C,
4212 SVGDescElement: C,
4213 SVGDiscardElement: C,
4214 SVGElement: C,
4215 SVGEllipseElement: C,
4216 SVGFEBlendElement: C,
4217 SVGFEColorMatrixElement: C,
4218 SVGFEComponentTransferElement: C,
4219 SVGFECompositeElement: C,
4220 SVGFEConvolveMatrixElement: C,
4221 SVGFEDiffuseLightingElement: C,
4222 SVGFEDisplacementMapElement: C,
4223 SVGFEDistantLightElement: C,
4224 SVGFEDropShadowElement: C,
4225 SVGFEFloodElement: C,
4226 SVGFEFuncAElement: C,
4227 SVGFEFuncBElement: C,
4228 SVGFEFuncGElement: C,
4229 SVGFEFuncRElement: C,
4230 SVGFEGaussianBlurElement: C,
4231 SVGFEImageElement: C,
4232 SVGFEMergeElement: C,
4233 SVGFEMergeNodeElement: C,
4234 SVGFEMorphologyElement: C,
4235 SVGFEOffsetElement: C,
4236 SVGFEPointLightElement: C,
4237 SVGFESpecularLightingElement: C,
4238 SVGFESpotLightElement: C,
4239 SVGFETileElement: C,
4240 SVGFETurbulenceElement: C,
4241 SVGFilterElement: C,
4242 SVGForeignObjectElement: C,
4243 SVGGElement: C,
4244 SVGGeometryElement: C,
4245 SVGGradientElement: C,
4246 SVGGraphicsElement: C,
4247 SVGImageElement: C,
4248 SVGLength: C,
4249 SVGLengthList: C,
4250 SVGLinearGradientElement: C,
4251 SVGLineElement: C,
4252 SVGMarkerElement: C,
4253 SVGMaskElement: C,
4254 SVGMatrix: C,
4255 SVGMetadataElement: C,
4256 SVGMPathElement: C,
4257 SVGNumber: C,
4258 SVGNumberList: C,
4259 SVGPathElement: C,
4260 SVGPatternElement: C,
4261 SVGPoint: C,
4262 SVGPointList: C,
4263 SVGPolygonElement: C,
4264 SVGPolylineElement: C,
4265 SVGPreserveAspectRatio: C,
4266 SVGRadialGradientElement: C,
4267 SVGRect: C,
4268 SVGRectElement: C,
4269 SVGScriptElement: C,
4270 SVGSetElement: C,
4271 SVGStopElement: C,
4272 SVGStringList: C,
4273 SVGStyleElement: C,
4274 SVGSVGElement: C,
4275 SVGSwitchElement: C,
4276 SVGSymbolElement: C,
4277 SVGTextContentElement: C,
4278 SVGTextElement: C,
4279 SVGTextPathElement: C,
4280 SVGTextPositioningElement: C,
4281 SVGTitleElement: C,
4282 SVGTransform: C,
4283 SVGTransformList: C,
4284 SVGTSpanElement: C,
4285 SVGUnitTypes: C,
4286 SVGUseElement: C,
4287 SVGViewElement: C,
4288 TaskAttributionTiming: C,
4289 Text: C,
4290 TextEvent: C,
4291 TextMetrics: C,
4292 TextTrack: C,
4293 TextTrackCue: C,
4294 TextTrackCueList: C,
4295 TextTrackList: C,
4296 TimeRanges: C,
4297 toolbar: O,
4298 top: O,
4299 Touch: C,
4300 TouchEvent: C,
4301 TouchList: C,
4302 TrackEvent: C,
4303 TransitionEvent: C,
4304 TreeWalker: C,
4305 UIEvent: C,
4306 ValidityState: C,
4307 visualViewport: O,
4308 VisualViewport: C,
4309 VTTCue: C,
4310 WaveShaperNode: C,
4311 WebAssembly: O,
4312 WebGL2RenderingContext: C,
4313 WebGLActiveInfo: C,
4314 WebGLBuffer: C,
4315 WebGLContextEvent: C,
4316 WebGLFramebuffer: C,
4317 WebGLProgram: C,
4318 WebGLQuery: C,
4319 WebGLRenderbuffer: C,
4320 WebGLRenderingContext: C,
4321 WebGLSampler: C,
4322 WebGLShader: C,
4323 WebGLShaderPrecisionFormat: C,
4324 WebGLSync: C,
4325 WebGLTexture: C,
4326 WebGLTransformFeedback: C,
4327 WebGLUniformLocation: C,
4328 WebGLVertexArrayObject: C,
4329 WebSocket: C,
4330 WheelEvent: C,
4331 Window: C,
4332 Worker: C,
4333 WritableStream: C,
4334 XMLDocument: C,
4335 XMLHttpRequest: C,
4336 XMLHttpRequestEventTarget: C,
4337 XMLHttpRequestUpload: C,
4338 XMLSerializer: C,
4339 XPathEvaluator: C,
4340 XPathExpression: C,
4341 XPathResult: C,
4342 XSLTProcessor: C
4343};
4344for (const global of ['window', 'global', 'self', 'globalThis']) {
4345 knownGlobals[global] = knownGlobals;
4346}
4347function getGlobalAtPath(path) {
4348 let currentGlobal = knownGlobals;
4349 for (const pathSegment of path) {
4350 if (typeof pathSegment !== 'string') {
4351 return null;
4352 }
4353 currentGlobal = currentGlobal[pathSegment];
4354 if (!currentGlobal) {
4355 return null;
4356 }
4357 }
4358 return currentGlobal[ValueProperties];
4359}
4360function isPureGlobal(path) {
4361 const globalAtPath = getGlobalAtPath(path);
4362 return globalAtPath !== null && globalAtPath.pure;
4363}
4364function isGlobalMember(path) {
4365 if (path.length === 1) {
4366 return path[0] === 'undefined' || getGlobalAtPath(path) !== null;
4367 }
4368 return getGlobalAtPath(path.slice(0, -1)) !== null;
4369}
4370
4371class GlobalVariable extends Variable {
4372 hasEffectsWhenAccessedAtPath(path) {
4373 return !isGlobalMember([this.name, ...path]);
4374 }
4375 hasEffectsWhenCalledAtPath(path) {
4376 return !isPureGlobal([this.name, ...path]);
4377 }
4378}
4379
4380class Identifier$1 extends NodeBase {
4381 constructor() {
4382 super(...arguments);
4383 this.variable = null;
4384 this.bound = false;
4385 }
4386 addExportedVariables(variables) {
4387 if (this.variable !== null && this.variable.exportName) {
4388 variables.push(this.variable);
4389 }
4390 }
4391 bind() {
4392 if (this.bound)
4393 return;
4394 this.bound = true;
4395 if (this.variable === null && isReference(this, this.parent)) {
4396 this.variable = this.scope.findVariable(this.name);
4397 this.variable.addReference(this);
4398 }
4399 if (this.variable !== null &&
4400 this.variable instanceof LocalVariable &&
4401 this.variable.additionalInitializers !== null) {
4402 this.variable.consolidateInitializers();
4403 }
4404 }
4405 declare(kind, init) {
4406 let variable;
4407 switch (kind) {
4408 case 'var':
4409 variable = this.scope.addDeclaration(this, this.context, init, true);
4410 break;
4411 case 'function':
4412 variable = this.scope.addDeclaration(this, this.context, init, 'function');
4413 break;
4414 case 'let':
4415 case 'const':
4416 case 'class':
4417 variable = this.scope.addDeclaration(this, this.context, init, false);
4418 break;
4419 case 'parameter':
4420 variable = this.scope.addParameterDeclaration(this);
4421 break;
4422 /* istanbul ignore next */
4423 default:
4424 /* istanbul ignore next */
4425 throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
4426 }
4427 return [(this.variable = variable)];
4428 }
4429 deoptimizePath(path) {
4430 if (!this.bound)
4431 this.bind();
4432 if (path.length === 0 && !this.scope.contains(this.name)) {
4433 this.disallowImportReassignment();
4434 }
4435 this.variable.deoptimizePath(path);
4436 }
4437 getLiteralValueAtPath(path, recursionTracker, origin) {
4438 if (!this.bound)
4439 this.bind();
4440 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
4441 }
4442 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
4443 if (!this.bound)
4444 this.bind();
4445 return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
4446 }
4447 hasEffects() {
4448 return (this.context.unknownGlobalSideEffects &&
4449 this.variable instanceof GlobalVariable &&
4450 this.variable.hasEffectsWhenAccessedAtPath(EMPTY_PATH));
4451 }
4452 hasEffectsWhenAccessedAtPath(path, context) {
4453 return this.variable !== null && this.variable.hasEffectsWhenAccessedAtPath(path, context);
4454 }
4455 hasEffectsWhenAssignedAtPath(path, context) {
4456 return !this.variable || this.variable.hasEffectsWhenAssignedAtPath(path, context);
4457 }
4458 hasEffectsWhenCalledAtPath(path, callOptions, context) {
4459 return !this.variable || this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
4460 }
4461 include(context) {
4462 if (!this.included) {
4463 this.included = true;
4464 if (this.variable !== null) {
4465 this.context.includeVariable(context, this.variable);
4466 }
4467 }
4468 }
4469 includeCallArguments(context, args) {
4470 this.variable.includeCallArguments(context, args);
4471 }
4472 render(code, _options, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
4473 if (this.variable) {
4474 const name = this.variable.getName();
4475 if (name !== this.name) {
4476 code.overwrite(this.start, this.end, name, {
4477 contentOnly: true,
4478 storeName: true
4479 });
4480 if (isShorthandProperty) {
4481 code.prependRight(this.start, `${this.name}: `);
4482 }
4483 }
4484 // In strict mode, any variable named "eval" must be the actual "eval" function
4485 if (name === 'eval' &&
4486 renderedParentType === CallExpression &&
4487 isCalleeOfRenderedParent) {
4488 code.appendRight(this.start, '0, ');
4489 }
4490 }
4491 }
4492 disallowImportReassignment() {
4493 this.context.error({
4494 code: 'ILLEGAL_REASSIGNMENT',
4495 message: `Illegal reassignment to import '${this.name}'`
4496 }, this.start);
4497 }
4498}
4499
4500class RestElement extends NodeBase {
4501 constructor() {
4502 super(...arguments);
4503 this.declarationInit = null;
4504 }
4505 addExportedVariables(variables) {
4506 this.argument.addExportedVariables(variables);
4507 }
4508 bind() {
4509 super.bind();
4510 if (this.declarationInit !== null) {
4511 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
4512 }
4513 }
4514 declare(kind, init) {
4515 this.declarationInit = init;
4516 return this.argument.declare(kind, UNKNOWN_EXPRESSION);
4517 }
4518 deoptimizePath(path) {
4519 path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
4520 }
4521 hasEffectsWhenAssignedAtPath(path, context) {
4522 return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
4523 }
4524}
4525
4526class FunctionNode extends NodeBase {
4527 constructor() {
4528 super(...arguments);
4529 this.isPrototypeDeoptimized = false;
4530 }
4531 createScope(parentScope) {
4532 this.scope = new FunctionScope(parentScope, this.context);
4533 }
4534 deoptimizePath(path) {
4535 if (path.length === 1) {
4536 if (path[0] === 'prototype') {
4537 this.isPrototypeDeoptimized = true;
4538 }
4539 else if (path[0] === UnknownKey) {
4540 this.isPrototypeDeoptimized = true;
4541 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
4542 // which means the return expression needs to be reassigned as well
4543 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
4544 }
4545 }
4546 }
4547 getReturnExpressionWhenCalledAtPath(path) {
4548 return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
4549 }
4550 hasEffects() {
4551 return this.id !== null && this.id.hasEffects();
4552 }
4553 hasEffectsWhenAccessedAtPath(path) {
4554 if (path.length <= 1)
4555 return false;
4556 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
4557 }
4558 hasEffectsWhenAssignedAtPath(path) {
4559 if (path.length <= 1) {
4560 return false;
4561 }
4562 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
4563 }
4564 hasEffectsWhenCalledAtPath(path, callOptions, context) {
4565 if (path.length > 0)
4566 return true;
4567 for (const param of this.params) {
4568 if (param.hasEffects(context))
4569 return true;
4570 }
4571 const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
4572 context.replacedVariableInits.set(this.scope.thisVariable, callOptions.withNew ? new UnknownObjectExpression() : UNKNOWN_EXPRESSION);
4573 const { brokenFlow, ignore } = context;
4574 context.ignore = {
4575 breaks: false,
4576 continues: false,
4577 labels: new Set(),
4578 returnAwaitYield: true
4579 };
4580 if (this.body.hasEffects(context))
4581 return true;
4582 context.brokenFlow = brokenFlow;
4583 if (thisInit) {
4584 context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
4585 }
4586 else {
4587 context.replacedVariableInits.delete(this.scope.thisVariable);
4588 }
4589 context.ignore = ignore;
4590 return false;
4591 }
4592 include(context, includeChildrenRecursively) {
4593 this.included = true;
4594 if (this.id)
4595 this.id.include(context);
4596 const hasArguments = this.scope.argumentsVariable.included;
4597 for (const param of this.params) {
4598 if (!(param instanceof Identifier$1) || hasArguments) {
4599 param.include(context, includeChildrenRecursively);
4600 }
4601 }
4602 const { brokenFlow } = context;
4603 context.brokenFlow = BROKEN_FLOW_NONE;
4604 this.body.include(context, includeChildrenRecursively);
4605 context.brokenFlow = brokenFlow;
4606 }
4607 includeCallArguments(context, args) {
4608 this.scope.includeCallArguments(context, args);
4609 }
4610 initialise() {
4611 if (this.id !== null) {
4612 this.id.declare('function', this);
4613 }
4614 this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
4615 this.body.addImplicitReturnExpressionToScope();
4616 }
4617 parseNode(esTreeNode) {
4618 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
4619 super.parseNode(esTreeNode);
4620 }
4621}
4622FunctionNode.prototype.preventChildBlockScope = true;
4623
4624class FunctionDeclaration extends FunctionNode {
4625 initialise() {
4626 super.initialise();
4627 if (this.id !== null) {
4628 this.id.variable.isId = true;
4629 }
4630 }
4631 parseNode(esTreeNode) {
4632 if (esTreeNode.id !== null) {
4633 this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope
4634 .parent);
4635 }
4636 super.parseNode(esTreeNode);
4637 }
4638}
4639
4640const WHITESPACE = /\s/;
4641// The header ends at the first non-white-space after "default"
4642function getDeclarationStart(code, start = 0) {
4643 start = findFirstOccurrenceOutsideComment(code, 'default', start) + 7;
4644 while (WHITESPACE.test(code[start]))
4645 start++;
4646 return start;
4647}
4648function getIdInsertPosition(code, declarationKeyword, start = 0) {
4649 const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
4650 code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '{', declarationEnd));
4651 const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
4652 if (generatorStarPos === -1) {
4653 return declarationEnd;
4654 }
4655 return declarationEnd + generatorStarPos + 1;
4656}
4657class ExportDefaultDeclaration extends NodeBase {
4658 include(context, includeChildrenRecursively) {
4659 super.include(context, includeChildrenRecursively);
4660 if (includeChildrenRecursively) {
4661 this.context.includeVariable(context, this.variable);
4662 }
4663 }
4664 initialise() {
4665 const declaration = this.declaration;
4666 this.declarationName =
4667 (declaration.id && declaration.id.name) || this.declaration.name;
4668 this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
4669 this.context.addExport(this);
4670 }
4671 render(code, options, { start, end } = BLANK) {
4672 const declarationStart = getDeclarationStart(code.original, this.start);
4673 if (this.declaration instanceof FunctionDeclaration) {
4674 this.renderNamedDeclaration(code, declarationStart, 'function', this.declaration.id === null, options);
4675 }
4676 else if (this.declaration instanceof ClassDeclaration) {
4677 this.renderNamedDeclaration(code, declarationStart, 'class', this.declaration.id === null, options);
4678 }
4679 else if (this.variable.getOriginalVariable() !== this.variable) {
4680 // Remove altogether to prevent re-declaring the same variable
4681 if (options.format === 'system' && this.variable.exportName) {
4682 code.overwrite(start, end, `exports('${this.variable.exportName}', ${this.variable.getName()});`);
4683 }
4684 else {
4685 treeshakeNode(this, code, start, end);
4686 }
4687 return;
4688 }
4689 else if (this.variable.included) {
4690 this.renderVariableDeclaration(code, declarationStart, options);
4691 }
4692 else {
4693 code.remove(this.start, declarationStart);
4694 this.declaration.render(code, options, {
4695 isCalleeOfRenderedParent: false,
4696 renderedParentType: ExpressionStatement
4697 });
4698 if (code.original[this.end - 1] !== ';') {
4699 code.appendLeft(this.end, ';');
4700 }
4701 return;
4702 }
4703 this.declaration.render(code, options);
4704 }
4705 renderNamedDeclaration(code, declarationStart, declarationKeyword, needsId, options) {
4706 const name = this.variable.getName();
4707 // Remove `export default`
4708 code.remove(this.start, declarationStart);
4709 if (needsId) {
4710 code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, declarationStart), ` ${name}`);
4711 }
4712 if (options.format === 'system' &&
4713 this.declaration instanceof ClassDeclaration &&
4714 this.variable.exportName) {
4715 code.appendLeft(this.end, ` exports('${this.variable.exportName}', ${name});`);
4716 }
4717 }
4718 renderVariableDeclaration(code, declarationStart, options) {
4719 const systemBinding = options.format === 'system' && this.variable.exportName
4720 ? `exports('${this.variable.exportName}', `
4721 : '';
4722 code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = ${systemBinding}`);
4723 const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
4724 if (systemBinding) {
4725 code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
4726 }
4727 else if (!hasTrailingSemicolon) {
4728 code.appendLeft(this.end, ';');
4729 }
4730 }
4731}
4732ExportDefaultDeclaration.prototype.needsBoundaries = true;
4733
4734class ExportDefaultVariable extends LocalVariable {
4735 constructor(name, exportDefaultDeclaration, context) {
4736 super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
4737 this.hasId = false;
4738 // Not initialised during construction
4739 this.originalId = null;
4740 this.originalVariable = null;
4741 const declaration = exportDefaultDeclaration.declaration;
4742 if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
4743 declaration.id) {
4744 this.hasId = true;
4745 this.originalId = declaration.id;
4746 }
4747 else if (declaration instanceof Identifier$1) {
4748 this.originalId = declaration;
4749 }
4750 }
4751 addReference(identifier) {
4752 if (!this.hasId) {
4753 this.name = identifier.name;
4754 }
4755 }
4756 getAssignedVariableName() {
4757 return (this.originalId && this.originalId.name) || null;
4758 }
4759 getBaseVariableName() {
4760 const original = this.getOriginalVariable();
4761 if (original === this) {
4762 return super.getBaseVariableName();
4763 }
4764 else {
4765 return original.getBaseVariableName();
4766 }
4767 }
4768 getName() {
4769 const original = this.getOriginalVariable();
4770 if (original === this) {
4771 return super.getName();
4772 }
4773 else {
4774 return original.getName();
4775 }
4776 }
4777 getOriginalVariable() {
4778 if (this.originalVariable === null) {
4779 if (!this.originalId || (!this.hasId && this.originalId.variable.isReassigned)) {
4780 this.originalVariable = this;
4781 }
4782 else {
4783 const assignedOriginal = this.originalId.variable;
4784 this.originalVariable =
4785 assignedOriginal instanceof ExportDefaultVariable
4786 ? assignedOriginal.getOriginalVariable()
4787 : assignedOriginal;
4788 }
4789 }
4790 return this.originalVariable;
4791 }
4792 setRenderNames(baseName, name) {
4793 const original = this.getOriginalVariable();
4794 if (original === this) {
4795 super.setRenderNames(baseName, name);
4796 }
4797 else {
4798 original.setRenderNames(baseName, name);
4799 }
4800 }
4801 setSafeName(name) {
4802 const original = this.getOriginalVariable();
4803 if (original === this) {
4804 super.setSafeName(name);
4805 }
4806 else {
4807 original.setSafeName(name);
4808 }
4809 }
4810}
4811
4812const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
4813const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
4814const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
4815
4816class ExportShimVariable extends Variable {
4817 constructor(module) {
4818 super(MISSING_EXPORT_SHIM_VARIABLE);
4819 this.module = module;
4820 }
4821}
4822
4823class NamespaceVariable extends Variable {
4824 constructor(context) {
4825 super(context.getModuleName());
4826 this.memberVariables = Object.create(null);
4827 this.containsExternalNamespace = false;
4828 this.referencedEarly = false;
4829 this.references = [];
4830 this.context = context;
4831 this.module = context.module;
4832 }
4833 addReference(identifier) {
4834 this.references.push(identifier);
4835 this.name = identifier.name;
4836 }
4837 // This is only called if "UNKNOWN_PATH" is reassigned as in all other situations, either the
4838 // build fails due to an illegal namespace reassignment or MemberExpression already forwards
4839 // the reassignment to the right variable. This means we lost track of this variable and thus
4840 // need to reassign all exports.
4841 deoptimizePath() {
4842 for (const key in this.memberVariables) {
4843 this.memberVariables[key].deoptimizePath(UNKNOWN_PATH);
4844 }
4845 }
4846 include(context) {
4847 if (!this.included) {
4848 if (this.containsExternalNamespace) {
4849 this.context.error({
4850 code: 'NAMESPACE_CANNOT_CONTAIN_EXTERNAL',
4851 id: this.module.id,
4852 message: `Cannot create an explicit namespace object for module "${this.context.getModuleName()}" because it contains a reexported external namespace`
4853 }, undefined);
4854 }
4855 this.included = true;
4856 for (const identifier of this.references) {
4857 if (identifier.context.getModuleExecIndex() <= this.context.getModuleExecIndex()) {
4858 this.referencedEarly = true;
4859 break;
4860 }
4861 }
4862 if (this.context.preserveModules) {
4863 for (const memberName of Object.keys(this.memberVariables))
4864 this.memberVariables[memberName].include(context);
4865 }
4866 else {
4867 for (const memberName of Object.keys(this.memberVariables))
4868 this.context.includeVariable(context, this.memberVariables[memberName]);
4869 }
4870 }
4871 }
4872 initialise() {
4873 for (const name of this.context.getExports().concat(this.context.getReexports())) {
4874 if (name[0] === '*' && name.length > 1)
4875 this.containsExternalNamespace = true;
4876 this.memberVariables[name] = this.context.traceExport(name);
4877 }
4878 }
4879 renderBlock(options) {
4880 const _ = options.compact ? '' : ' ';
4881 const n = options.compact ? '' : '\n';
4882 const t = options.indent;
4883 const members = Object.keys(this.memberVariables).map(name => {
4884 const original = this.memberVariables[name];
4885 if (this.referencedEarly || original.isReassigned) {
4886 return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${options.compact ? '' : ';'}${_}}`;
4887 }
4888 const safeName = RESERVED_NAMES[name] ? `'${name}'` : name;
4889 return `${t}${safeName}: ${original.getName()}`;
4890 });
4891 members.unshift(`${t}__proto__:${_}null`);
4892 if (options.namespaceToStringTag) {
4893 members.unshift(`${t}[Symbol.toStringTag]:${_}'Module'`);
4894 }
4895 const name = this.getName();
4896 const callee = options.freeze ? `/*#__PURE__*/Object.freeze` : '';
4897 const membersStr = members.join(`,${n}`);
4898 let output = `${options.varOrConst} ${name}${_}=${_}${callee}({${n}${membersStr}${n}});`;
4899 if (options.format === 'system' && this.exportName) {
4900 output += `${n}exports('${this.exportName}',${_}${name});`;
4901 }
4902 return output;
4903 }
4904 renderFirst() {
4905 return this.referencedEarly;
4906 }
4907}
4908NamespaceVariable.prototype.isNamespace = true;
4909
4910const esModuleExport = `Object.defineProperty(exports, '__esModule', { value: true });`;
4911const compactEsModuleExport = `Object.defineProperty(exports,'__esModule',{value:true});`;
4912
4913function getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, mechanism = 'return ') {
4914 const _ = compact ? '' : ' ';
4915 const n = compact ? '' : '\n';
4916 if (!namedExportsMode) {
4917 let local;
4918 if (exports.length > 0) {
4919 local = exports[0].local;
4920 }
4921 else {
4922 for (const dep of dependencies) {
4923 if (dep.reexports) {
4924 const expt = dep.reexports[0];
4925 local =
4926 dep.namedExportsMode && expt.imported !== '*' && expt.imported !== 'default'
4927 ? `${dep.name}.${expt.imported}`
4928 : dep.name;
4929 }
4930 }
4931 }
4932 return `${mechanism}${local};`;
4933 }
4934 let exportBlock = '';
4935 // star exports must always output first for precedence
4936 dependencies.forEach(({ name, reexports }) => {
4937 if (reexports && namedExportsMode) {
4938 reexports.forEach(specifier => {
4939 if (specifier.reexported === '*') {
4940 if (exportBlock)
4941 exportBlock += n;
4942 if (specifier.needsLiveBinding) {
4943 exportBlock +=
4944 `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
4945 `${t}if${_}(k${_}!==${_}'default')${_}Object.defineProperty(exports,${_}k,${_}{${n}` +
4946 `${t}${t}enumerable:${_}true,${n}` +
4947 `${t}${t}get:${_}function${_}()${_}{${n}` +
4948 `${t}${t}${t}return ${name}[k];${n}` +
4949 `${t}${t}}${n}${t}});${n}});`;
4950 }
4951 else {
4952 exportBlock +=
4953 `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
4954 `${t}if${_}(k${_}!==${_}'default')${_}exports[k]${_}=${_}${name}[k];${n}});`;
4955 }
4956 }
4957 });
4958 }
4959 });
4960 for (const { name, imports, reexports, isChunk, namedExportsMode: depNamedExportsMode, exportsNames } of dependencies) {
4961 if (reexports && namedExportsMode) {
4962 for (const specifier of reexports) {
4963 if (specifier.imported === 'default' && !isChunk) {
4964 if (exportBlock)
4965 exportBlock += n;
4966 if (exportsNames &&
4967 (reexports.some(specifier => specifier.imported === 'default'
4968 ? specifier.reexported === 'default'
4969 : specifier.imported !== '*') ||
4970 (imports && imports.some(specifier => specifier.imported !== 'default')))) {
4971 exportBlock += `exports.${specifier.reexported}${_}=${_}${name}${interop !== false ? '__default' : '.default'};`;
4972 }
4973 else {
4974 exportBlock += `exports.${specifier.reexported}${_}=${_}${name};`;
4975 }
4976 }
4977 else if (specifier.imported !== '*') {
4978 if (exportBlock)
4979 exportBlock += n;
4980 const importName = specifier.imported === 'default' && !depNamedExportsMode
4981 ? name
4982 : `${name}.${specifier.imported}`;
4983 exportBlock += specifier.needsLiveBinding
4984 ? `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
4985 `${t}enumerable:${_}true,${n}` +
4986 `${t}get:${_}function${_}()${_}{${n}` +
4987 `${t}${t}return ${importName};${n}${t}}${n}});`
4988 : `exports.${specifier.reexported}${_}=${_}${importName};`;
4989 }
4990 else if (specifier.reexported !== '*') {
4991 if (exportBlock)
4992 exportBlock += n;
4993 exportBlock += `exports.${specifier.reexported}${_}=${_}${name};`;
4994 }
4995 }
4996 }
4997 }
4998 for (const expt of exports) {
4999 const lhs = `exports.${expt.exported}`;
5000 const rhs = expt.local;
5001 if (lhs !== rhs) {
5002 if (exportBlock)
5003 exportBlock += n;
5004 exportBlock += `${lhs}${_}=${_}${rhs};`;
5005 }
5006 }
5007 return exportBlock;
5008}
5009
5010function getInteropBlock(dependencies, options, varOrConst) {
5011 const _ = options.compact ? '' : ' ';
5012 return dependencies
5013 .map(({ name, exportsNames, exportsDefault, namedExportsMode }) => {
5014 if (!namedExportsMode || !exportsDefault || options.interop === false)
5015 return null;
5016 if (exportsNames) {
5017 return (`${varOrConst} ${name}__default${_}=${_}'default'${_}in ${name}${_}?` +
5018 `${_}${name}['default']${_}:${_}${name};`);
5019 }
5020 return (`${name}${_}=${_}${name}${_}&&${_}${name}.hasOwnProperty('default')${_}?` +
5021 `${_}${name}['default']${_}:${_}${name};`);
5022 })
5023 .filter(Boolean)
5024 .join(options.compact ? '' : '\n');
5025}
5026
5027function copyPropertyLiveBinding(_, n, t, i) {
5028 return (`${i}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
5029 `${i}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
5030 `${i}${t}enumerable:${_}true,${n}` +
5031 `${i}${t}get:${_}function${_}()${_}{${n}` +
5032 `${i}${t}${t}return e[k];${n}` +
5033 `${i}${t}}${n}` +
5034 `${i}});${n}`);
5035}
5036function copyPropertyStatic(_, n, _t, i) {
5037 return `${i}n[k]${_}=e${_}[k];${n}`;
5038}
5039function getInteropNamespace(_, n, t, liveBindings) {
5040 return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
5041 `${t}if${_}(e${_}&&${_}e.__esModule)${_}{${_}return e;${_}}${_}else${_}{${n}` +
5042 `${t}${t}var n${_}=${_}{};${n}` +
5043 `${t}${t}if${_}(e)${_}{${n}` +
5044 `${t}${t}${t}Object.keys(e).forEach(function${_}(k)${_}{${n}` +
5045 (liveBindings ? copyPropertyLiveBinding : copyPropertyStatic)(_, n, t, t + t + t + t) +
5046 `${t}${t}${t}});${n}` +
5047 `${t}${t}}${n}` +
5048 `${t}${t}n['default']${_}=${_}e;${n}` +
5049 `${t}${t}return n;${n}` +
5050 `${t}}${n}` +
5051 `}${n}${n}`);
5052}
5053
5054const builtins$1 = {
5055 assert: true,
5056 buffer: true,
5057 console: true,
5058 constants: true,
5059 domain: true,
5060 events: true,
5061 http: true,
5062 https: true,
5063 os: true,
5064 path: true,
5065 process: true,
5066 punycode: true,
5067 querystring: true,
5068 stream: true,
5069 string_decoder: true,
5070 timers: true,
5071 tty: true,
5072 url: true,
5073 util: true,
5074 vm: true,
5075 zlib: true
5076};
5077// 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
5078function warnOnBuiltins(warn, dependencies) {
5079 const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins$1);
5080 if (!externalBuiltins.length)
5081 return;
5082 const detail = externalBuiltins.length === 1
5083 ? `module ('${externalBuiltins[0]}')`
5084 : `modules (${externalBuiltins
5085 .slice(0, -1)
5086 .map(name => `'${name}'`)
5087 .join(', ')} and '${externalBuiltins.slice(-1)}')`;
5088 warn({
5089 code: 'MISSING_NODE_BUILTINS',
5090 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`,
5091 modules: externalBuiltins
5092 });
5093}
5094
5095// AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
5096// The assumption is that this makes sense for all relative ids:
5097// https://requirejs.org/docs/api.html#jsfiles
5098function removeExtensionFromRelativeAmdId(id) {
5099 if (id[0] === '.' && id.endsWith('.js')) {
5100 return id.slice(0, -3);
5101 }
5102 return id;
5103}
5104function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryModuleFacade, namedExportsMode, outro, varOrConst, warn }, options) {
5105 warnOnBuiltins(warn, dependencies);
5106 const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
5107 const args = dependencies.map(m => m.name);
5108 const n = options.compact ? '' : '\n';
5109 const _ = options.compact ? '' : ' ';
5110 if (namedExportsMode && hasExports) {
5111 args.unshift(`exports`);
5112 deps.unshift(`'exports'`);
5113 }
5114 if (accessedGlobals.has('require')) {
5115 args.unshift('require');
5116 deps.unshift(`'require'`);
5117 }
5118 if (accessedGlobals.has('module')) {
5119 args.unshift('module');
5120 deps.unshift(`'module'`);
5121 }
5122 const amdOptions = options.amd || {};
5123 const params = (amdOptions.id ? `'${amdOptions.id}',${_}` : ``) +
5124 (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
5125 const useStrict = options.strict !== false ? `${_}'use strict';` : ``;
5126 const define = amdOptions.define || 'define';
5127 const wrapperStart = `${define}(${params}function${_}(${args.join(`,${_}`)})${_}{${useStrict}${n}${n}`;
5128 // var foo__default = 'default' in foo ? foo['default'] : foo;
5129 const interopBlock = getInteropBlock(dependencies, options, varOrConst);
5130 if (interopBlock) {
5131 magicString.prepend(interopBlock + n + n);
5132 }
5133 if (accessedGlobals.has(INTEROP_NAMESPACE_VARIABLE)) {
5134 magicString.prepend(getInteropNamespace(_, n, t, options.externalLiveBindings !== false));
5135 }
5136 if (intro)
5137 magicString.prepend(intro);
5138 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
5139 if (exportBlock)
5140 magicString.append(n + n + exportBlock);
5141 if (namedExportsMode && hasExports && isEntryModuleFacade && options.esModule)
5142 magicString.append(`${n}${n}${options.compact ? compactEsModuleExport : esModuleExport}`);
5143 if (outro)
5144 magicString.append(outro);
5145 return magicString
5146 .indent(t)
5147 .append(n + n + '});')
5148 .prepend(wrapperStart);
5149}
5150
5151function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryModuleFacade, namedExportsMode, outro, varOrConst }, options) {
5152 const n = options.compact ? '' : '\n';
5153 const _ = options.compact ? '' : ' ';
5154 intro =
5155 (options.strict === false ? intro : `'use strict';${n}${n}${intro}`) +
5156 (namedExportsMode && hasExports && isEntryModuleFacade && options.esModule
5157 ? `${options.compact ? compactEsModuleExport : esModuleExport}${n}${n}`
5158 : '');
5159 let needsInterop = false;
5160 const interop = options.interop !== false;
5161 let importBlock;
5162 let definingVariable = false;
5163 importBlock = '';
5164 for (const { id, namedExportsMode, isChunk, name, reexports, imports, exportsNames, exportsDefault } of dependencies) {
5165 if (!reexports && !imports) {
5166 if (importBlock) {
5167 importBlock += !options.compact || definingVariable ? `;${n}` : ',';
5168 }
5169 definingVariable = false;
5170 importBlock += `require('${id}')`;
5171 }
5172 else {
5173 importBlock +=
5174 options.compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${varOrConst} `;
5175 definingVariable = true;
5176 if (!interop || isChunk || !exportsDefault || !namedExportsMode) {
5177 importBlock += `${name}${_}=${_}require('${id}')`;
5178 }
5179 else {
5180 needsInterop = true;
5181 if (exportsNames)
5182 importBlock += `${name}${_}=${_}require('${id}')${options.compact ? ',' : `;\n${varOrConst} `}${name}__default${_}=${_}${INTEROP_DEFAULT_VARIABLE}(${name})`;
5183 else
5184 importBlock += `${name}${_}=${_}${INTEROP_DEFAULT_VARIABLE}(require('${id}'))`;
5185 }
5186 }
5187 }
5188 if (importBlock)
5189 importBlock += ';';
5190 if (needsInterop) {
5191 const ex = options.compact ? 'e' : 'ex';
5192 intro +=
5193 `function ${INTEROP_DEFAULT_VARIABLE}${_}(${ex})${_}{${_}return${_}` +
5194 `(${ex}${_}&&${_}(typeof ${ex}${_}===${_}'object')${_}&&${_}'default'${_}in ${ex})${_}` +
5195 `?${_}${ex}['default']${_}:${_}${ex}${options.compact ? '' : '; '}}${n}${n}`;
5196 }
5197 if (accessedGlobals.has(INTEROP_NAMESPACE_VARIABLE)) {
5198 intro += getInteropNamespace(_, n, t, options.externalLiveBindings !== false);
5199 }
5200 if (importBlock)
5201 intro += importBlock + n + n;
5202 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t, `module.exports${_}=${_}`);
5203 magicString.prepend(intro);
5204 if (exportBlock)
5205 magicString.append(n + n + exportBlock);
5206 if (outro)
5207 magicString.append(outro);
5208 return magicString;
5209}
5210
5211function esm(magicString, { intro, outro, dependencies, exports }, options) {
5212 const _ = options.compact ? '' : ' ';
5213 const n = options.compact ? '' : '\n';
5214 const importBlock = dependencies
5215 .map(({ id, reexports, imports, name }) => {
5216 if (!reexports && !imports) {
5217 return `import${_}'${id}';`;
5218 }
5219 let output = '';
5220 if (imports) {
5221 const defaultImport = imports.find(specifier => specifier.imported === 'default');
5222 const starImport = imports.find(specifier => specifier.imported === '*');
5223 if (starImport) {
5224 output += `import${_}*${_}as ${starImport.local} from${_}'${id}';`;
5225 if (imports.length > 1)
5226 output += n;
5227 }
5228 if (defaultImport && imports.length === 1) {
5229 output += `import ${defaultImport.local} from${_}'${id}';`;
5230 }
5231 else if (!starImport || imports.length > 1) {
5232 output += `import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${imports
5233 .filter(specifier => specifier !== defaultImport && specifier !== starImport)
5234 .map(specifier => {
5235 if (specifier.imported === specifier.local) {
5236 return specifier.imported;
5237 }
5238 else {
5239 return `${specifier.imported} as ${specifier.local}`;
5240 }
5241 })
5242 .join(`,${_}`)}${_}}${_}from${_}'${id}';`;
5243 }
5244 }
5245 if (reexports) {
5246 if (imports)
5247 output += n;
5248 const starExport = reexports.find(specifier => specifier.reexported === '*');
5249 const namespaceReexport = reexports.find(specifier => specifier.imported === '*' && specifier.reexported !== '*');
5250 if (starExport) {
5251 output += `export${_}*${_}from${_}'${id}';`;
5252 if (reexports.length === 1) {
5253 return output;
5254 }
5255 output += n;
5256 }
5257 if (namespaceReexport) {
5258 if (!imports ||
5259 !imports.some(specifier => specifier.imported === '*' && specifier.local === name))
5260 output += `import${_}*${_}as ${name} from${_}'${id}';${n}`;
5261 output += `export${_}{${_}${name === namespaceReexport.reexported
5262 ? name
5263 : `${name} as ${namespaceReexport.reexported}`} };`;
5264 if (reexports.length === (starExport ? 2 : 1)) {
5265 return output;
5266 }
5267 output += n;
5268 }
5269 output += `export${_}{${_}${reexports
5270 .filter(specifier => specifier !== starExport && specifier !== namespaceReexport)
5271 .map(specifier => {
5272 if (specifier.imported === specifier.reexported) {
5273 return specifier.imported;
5274 }
5275 else {
5276 return `${specifier.imported} as ${specifier.reexported}`;
5277 }
5278 })
5279 .join(`,${_}`)}${_}}${_}from${_}'${id}';`;
5280 }
5281 return output;
5282 })
5283 .join(n);
5284 if (importBlock)
5285 intro += importBlock + n + n;
5286 if (intro)
5287 magicString.prepend(intro);
5288 const exportBlock = [];
5289 const exportDeclaration = [];
5290 exports.forEach(specifier => {
5291 if (specifier.exported === 'default') {
5292 exportBlock.push(`export default ${specifier.local};`);
5293 }
5294 else {
5295 exportDeclaration.push(specifier.exported === specifier.local
5296 ? specifier.local
5297 : `${specifier.local} as ${specifier.exported}`);
5298 }
5299 });
5300 if (exportDeclaration.length) {
5301 exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
5302 }
5303 if (exportBlock.length)
5304 magicString.append(n + n + exportBlock.join(n).trim());
5305 if (outro)
5306 magicString.append(outro);
5307 return magicString.trim();
5308}
5309
5310function spaces(i) {
5311 let result = '';
5312 while (i--)
5313 result += ' ';
5314 return result;
5315}
5316function tabsToSpaces(str) {
5317 return str.replace(/^\t+/, match => match.split('\t').join(' '));
5318}
5319function getCodeFrame(source, line, column) {
5320 let lines = source.split('\n');
5321 const frameStart = Math.max(0, line - 3);
5322 let frameEnd = Math.min(line + 2, lines.length);
5323 lines = lines.slice(frameStart, frameEnd);
5324 while (!/\S/.test(lines[lines.length - 1])) {
5325 lines.pop();
5326 frameEnd -= 1;
5327 }
5328 const digits = String(frameEnd).length;
5329 return lines
5330 .map((str, i) => {
5331 const isErrorLine = frameStart + i + 1 === line;
5332 let lineNum = String(i + frameStart + 1);
5333 while (lineNum.length < digits)
5334 lineNum = ` ${lineNum}`;
5335 if (isErrorLine) {
5336 const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
5337 return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
5338 }
5339 return `${lineNum}: ${tabsToSpaces(str)}`;
5340 })
5341 .join('\n');
5342}
5343
5344function sanitizeFileName(name) {
5345 return name.replace(/[\0?*]/g, '_');
5346}
5347
5348function getAliasName(id) {
5349 const base = basename(id);
5350 return base.substr(0, base.length - extname(id).length);
5351}
5352function relativeId(id) {
5353 if (typeof process === 'undefined' || !isAbsolute(id))
5354 return id;
5355 return relative$1(process.cwd(), id);
5356}
5357function isPlainPathFragment(name) {
5358 // not starting with "/", "./", "../"
5359 return (name[0] !== '/' &&
5360 !(name[0] === '.' && (name[1] === '/' || name[1] === '.')) &&
5361 sanitizeFileName(name) === name);
5362}
5363
5364function error(base, props) {
5365 if (!(base instanceof Error))
5366 base = Object.assign(new Error(base.message), base);
5367 if (props)
5368 Object.assign(base, props);
5369 throw base;
5370}
5371function augmentCodeLocation(object, pos, source, id) {
5372 if (typeof pos === 'object') {
5373 const { line, column } = pos;
5374 object.loc = { file: id, line, column };
5375 }
5376 else {
5377 object.pos = pos;
5378 const { line, column } = locate(source, pos, { offsetLine: 1 });
5379 object.loc = { file: id, line, column };
5380 }
5381 if (object.frame === undefined) {
5382 const { line, column } = object.loc;
5383 object.frame = getCodeFrame(source, line, column);
5384 }
5385}
5386var Errors;
5387(function (Errors) {
5388 Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
5389 Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
5390 Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
5391 Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
5392 Errors["BAD_LOADER"] = "BAD_LOADER";
5393 Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
5394 Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
5395 Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
5396 Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
5397 Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
5398 Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
5399 Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
5400 Errors["INVALID_OPTION"] = "INVALID_OPTION";
5401 Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
5402 Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
5403 Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
5404 Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
5405 Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
5406 Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
5407 Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
5408})(Errors || (Errors = {}));
5409function errAssetNotFinalisedForFileName(name) {
5410 return {
5411 code: Errors.ASSET_NOT_FINALISED,
5412 message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
5413 };
5414}
5415function errCannotEmitFromOptionsHook() {
5416 return {
5417 code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
5418 message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
5419 };
5420}
5421function errChunkNotGeneratedForFileName(name) {
5422 return {
5423 code: Errors.CHUNK_NOT_GENERATED,
5424 message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
5425 };
5426}
5427function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
5428 return {
5429 code: Errors.ASSET_NOT_FOUND,
5430 message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
5431 };
5432}
5433function errAssetSourceAlreadySet(name) {
5434 return {
5435 code: Errors.ASSET_SOURCE_ALREADY_SET,
5436 message: `Unable to set the source for asset "${name}", source already set.`
5437 };
5438}
5439function errNoAssetSourceSet(assetName) {
5440 return {
5441 code: Errors.ASSET_SOURCE_MISSING,
5442 message: `Plugin error creating asset "${assetName}" - no asset source set.`
5443 };
5444}
5445function errBadLoader(id) {
5446 return {
5447 code: Errors.BAD_LOADER,
5448 message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
5449 };
5450}
5451function errDeprecation(deprecation) {
5452 return Object.assign({ code: Errors.DEPRECATED_FEATURE }, (typeof deprecation === 'string' ? { message: deprecation } : deprecation));
5453}
5454function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
5455 return {
5456 code: Errors.FILE_NOT_FOUND,
5457 message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
5458 };
5459}
5460function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
5461 return {
5462 code: Errors.INVALID_CHUNK,
5463 message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
5464 };
5465}
5466function errInternalIdCannotBeExternal(source, importer) {
5467 return {
5468 code: Errors.INVALID_EXTERNAL_ID,
5469 message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
5470 };
5471}
5472function errInvalidOption(option, explanation) {
5473 return {
5474 code: Errors.INVALID_OPTION,
5475 message: `Invalid value for option "${option}" - ${explanation}.`
5476 };
5477}
5478function errInvalidRollupPhaseForAddWatchFile() {
5479 return {
5480 code: Errors.INVALID_ROLLUP_PHASE,
5481 message: `Cannot call addWatchFile after the build has finished.`
5482 };
5483}
5484function errInvalidRollupPhaseForChunkEmission() {
5485 return {
5486 code: Errors.INVALID_ROLLUP_PHASE,
5487 message: `Cannot emit chunks after module loading has finished.`
5488 };
5489}
5490function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
5491 return {
5492 code: Errors.NAMESPACE_CONFLICT,
5493 message: `Conflicting namespaces: ${relativeId(reexportingModule.id)} re-exports '${name}' from both ${relativeId(reexportingModule.exportsAll[name])} and ${relativeId(additionalExportAllModule.exportsAll[name])} (will be ignored)`,
5494 name,
5495 reexporter: reexportingModule.id,
5496 sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
5497 };
5498}
5499function errEntryCannotBeExternal(unresolvedId) {
5500 return {
5501 code: Errors.UNRESOLVED_ENTRY,
5502 message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
5503 };
5504}
5505function errUnresolvedEntry(unresolvedId) {
5506 return {
5507 code: Errors.UNRESOLVED_ENTRY,
5508 message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
5509 };
5510}
5511function errUnresolvedImport(source, importer) {
5512 return {
5513 code: Errors.UNRESOLVED_IMPORT,
5514 message: `Could not resolve '${source}' from ${relativeId(importer)}`
5515 };
5516}
5517function errUnresolvedImportTreatedAsExternal(source, importer) {
5518 return {
5519 code: Errors.UNRESOLVED_IMPORT,
5520 importer: relativeId(importer),
5521 message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
5522 source,
5523 url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
5524 };
5525}
5526function errFailedValidation(message) {
5527 return {
5528 code: Errors.VALIDATION_ERROR,
5529 message
5530 };
5531}
5532
5533// Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
5534// if the property name isn't trivial
5535const shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
5536function property(prop) {
5537 return shouldUseDot.test(prop) ? `.${prop}` : `['${prop}']`;
5538}
5539function keypath(keypath) {
5540 return keypath
5541 .split('.')
5542 .map(property)
5543 .join('');
5544}
5545
5546function setupNamespace(name, root, globals, compact) {
5547 const parts = name.split('.');
5548 if (globals) {
5549 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
5550 }
5551 const _ = compact ? '' : ' ';
5552 parts.pop();
5553 let acc = root;
5554 return (parts
5555 .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}${compact ? '' : ';'}`))
5556 .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
5557}
5558function assignToDeepVariable(deepName, root, globals, compact, assignment) {
5559 const _ = compact ? '' : ' ';
5560 const parts = deepName.split('.');
5561 if (globals) {
5562 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
5563 }
5564 const last = parts.pop();
5565 let acc = root;
5566 let deepAssignment = parts
5567 .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`))
5568 .concat(`${acc}${property(last)}`)
5569 .join(`,${_}`)
5570 .concat(`${_}=${_}${assignment}`);
5571 if (parts.length > 0) {
5572 deepAssignment = `(${deepAssignment})`;
5573 }
5574 return deepAssignment;
5575}
5576
5577function trimEmptyImports(dependencies) {
5578 let i = dependencies.length;
5579 while (i--) {
5580 const dependency = dependencies[i];
5581 if (dependency.exportsDefault || dependency.exportsNames) {
5582 return dependencies.slice(0, i + 1);
5583 }
5584 }
5585 return [];
5586}
5587
5588const thisProp = (name) => `this${keypath(name)}`;
5589function iife(magicString, { dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, options) {
5590 const _ = options.compact ? '' : ' ';
5591 const n = options.compact ? '' : '\n';
5592 const { extend, name } = options;
5593 const isNamespaced = name && name.indexOf('.') !== -1;
5594 const useVariableAssignment = !extend && !isNamespaced;
5595 if (name && useVariableAssignment && !isLegal(name)) {
5596 error({
5597 code: 'ILLEGAL_IDENTIFIER_AS_NAME',
5598 message: `Given name (${name}) is not legal JS identifier. If you need this you can try --extend option`
5599 });
5600 }
5601 warnOnBuiltins(warn, dependencies);
5602 const external = trimEmptyImports(dependencies);
5603 const deps = external.map(dep => dep.globalName || 'null');
5604 const args = external.map(m => m.name);
5605 if (hasExports && !name) {
5606 error({
5607 code: 'INVALID_OPTION',
5608 message: `You must supply "output.name" for IIFE bundles.`
5609 });
5610 }
5611 if (namedExportsMode && hasExports) {
5612 if (extend) {
5613 deps.unshift(`${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{}`);
5614 args.unshift('exports');
5615 }
5616 else {
5617 deps.unshift('{}');
5618 args.unshift('exports');
5619 }
5620 }
5621 const useStrict = options.strict !== false ? `${t}'use strict';${n}${n}` : ``;
5622 let wrapperIntro = `(function${_}(${args.join(`,${_}`)})${_}{${n}${useStrict}`;
5623 if (hasExports && (!extend || !namedExportsMode)) {
5624 wrapperIntro =
5625 (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name)) +
5626 `${_}=${_}${wrapperIntro}`;
5627 }
5628 if (isNamespaced && hasExports) {
5629 wrapperIntro =
5630 setupNamespace(name, 'this', options.globals, options.compact) + wrapperIntro;
5631 }
5632 let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`;
5633 if (!extend && namedExportsMode && hasExports) {
5634 wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
5635 }
5636 // var foo__default = 'default' in foo ? foo['default'] : foo;
5637 const interopBlock = getInteropBlock(dependencies, options, varOrConst);
5638 if (interopBlock)
5639 magicString.prepend(interopBlock + n + n);
5640 if (intro)
5641 magicString.prepend(intro);
5642 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
5643 if (exportBlock)
5644 magicString.append(n + n + exportBlock);
5645 if (outro)
5646 magicString.append(outro);
5647 return magicString
5648 .indent(t)
5649 .prepend(wrapperIntro)
5650 .append(wrapperOutro);
5651}
5652
5653function getStarExcludes({ dependencies, exports }) {
5654 const starExcludes = new Set(exports.map(expt => expt.exported));
5655 if (!starExcludes.has('default'))
5656 starExcludes.add('default');
5657 // also include reexport names
5658 dependencies.forEach(({ reexports }) => {
5659 if (reexports)
5660 reexports.forEach(reexport => {
5661 if (reexport.imported !== '*' && !starExcludes.has(reexport.reexported))
5662 starExcludes.add(reexport.reexported);
5663 });
5664 });
5665 return starExcludes;
5666}
5667const getStarExcludesBlock = (starExcludes, varOrConst, _, t, n) => starExcludes
5668 ? `${n}${t}${varOrConst} _starExcludes${_}=${_}{${_}${Array.from(starExcludes).join(`:${_}1,${_}`)}${starExcludes.size ? `:${_}1` : ''}${_}};`
5669 : '';
5670const getImportBindingsBlock = (importBindings, _, t, n) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
5671function getExportsBlock(exports, _, t, n) {
5672 if (exports.length === 0) {
5673 return '';
5674 }
5675 if (exports.length === 1) {
5676 return `${t}${t}${t}exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
5677 }
5678 return (`${t}${t}${t}exports({${n}` +
5679 exports.map(({ name, value }) => `${t}${t}${t}${t}${name}:${_}${value}`).join(`,${n}`) +
5680 `${n}${t}${t}${t}});${n}${n}`);
5681}
5682const getHoistedExportsBlock = (exports, _, t, n) => getExportsBlock(exports
5683 .filter(expt => expt.hoisted || expt.uninitialized)
5684 .map(expt => ({ name: expt.exported, value: expt.uninitialized ? 'void 0' : expt.local })), _, t, n);
5685const getMissingExportsBlock = (exports, _, t, n) => getExportsBlock(exports
5686 .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
5687 .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), _, t, n);
5688function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, outro, usesTopLevelAwait, varOrConst }, options) {
5689 const n = options.compact ? '' : '\n';
5690 const _ = options.compact ? '' : ' ';
5691 const dependencyIds = dependencies.map(m => `'${m.id}'`);
5692 const importBindings = [];
5693 let starExcludes;
5694 const setters = [];
5695 dependencies.forEach(({ imports, reexports }) => {
5696 const setter = [];
5697 if (imports) {
5698 imports.forEach(specifier => {
5699 importBindings.push(specifier.local);
5700 if (specifier.imported === '*') {
5701 setter.push(`${specifier.local}${_}=${_}module;`);
5702 }
5703 else {
5704 setter.push(`${specifier.local}${_}=${_}module.${specifier.imported};`);
5705 }
5706 });
5707 }
5708 if (reexports) {
5709 let createdSetter = false;
5710 // bulk-reexport form
5711 if (reexports.length > 1 ||
5712 (reexports.length === 1 &&
5713 (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
5714 // star reexports
5715 reexports.forEach(specifier => {
5716 if (specifier.reexported !== '*')
5717 return;
5718 // need own exports list for deduping in star export case
5719 if (!starExcludes) {
5720 starExcludes = getStarExcludes({ dependencies, exports });
5721 }
5722 if (!createdSetter) {
5723 setter.push(`${varOrConst} _setter${_}=${_}{};`);
5724 createdSetter = true;
5725 }
5726 setter.push(`for${_}(var _$p${_}in${_}module)${_}{`);
5727 setter.push(`${t}if${_}(!_starExcludes[_$p])${_}_setter[_$p]${_}=${_}module[_$p];`);
5728 setter.push('}');
5729 });
5730 // star import reexport
5731 reexports.forEach(specifier => {
5732 if (specifier.imported !== '*' || specifier.reexported === '*')
5733 return;
5734 setter.push(`exports('${specifier.reexported}',${_}module);`);
5735 });
5736 // reexports
5737 reexports.forEach(specifier => {
5738 if (specifier.reexported === '*' || specifier.imported === '*')
5739 return;
5740 if (!createdSetter) {
5741 setter.push(`${varOrConst} _setter${_}=${_}{};`);
5742 createdSetter = true;
5743 }
5744 setter.push(`_setter.${specifier.reexported}${_}=${_}module.${specifier.imported};`);
5745 });
5746 if (createdSetter) {
5747 setter.push('exports(_setter);');
5748 }
5749 }
5750 else {
5751 // single reexport
5752 reexports.forEach(specifier => {
5753 setter.push(`exports('${specifier.reexported}',${_}module.${specifier.imported});`);
5754 });
5755 }
5756 }
5757 setters.push(setter.join(`${n}${t}${t}${t}`));
5758 });
5759 const registeredName = options.name ? `'${options.name}',${_}` : '';
5760 const wrapperParams = accessedGlobals.has('module')
5761 ? `exports,${_}module`
5762 : hasExports
5763 ? 'exports'
5764 : '';
5765 let wrapperStart = `System.register(${registeredName}[` +
5766 dependencyIds.join(`,${_}`) +
5767 `],${_}function${_}(${wrapperParams})${_}{${n}${t}${options.strict ? "'use strict';" : ''}` +
5768 getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
5769 getImportBindingsBlock(importBindings, _, t, n) +
5770 `${n}${t}return${_}{${setters.length
5771 ? `${n}${t}${t}setters:${_}[${setters
5772 .map(s => s
5773 ? `function${_}(module)${_}{${n}${t}${t}${t}${s}${n}${t}${t}}`
5774 : `function${_}()${_}{}`)
5775 .join(`,${_}`)}],`
5776 : ''}${n}`;
5777 wrapperStart +=
5778 `${t}${t}execute:${_}${usesTopLevelAwait ? `async${_}` : ''}function${_}()${_}{${n}${n}` +
5779 getHoistedExportsBlock(exports, _, t, n);
5780 const wrapperEnd = `${n}${n}` +
5781 getMissingExportsBlock(exports, _, t, n) +
5782 `${t}${t}}${n}${t}}${options.compact ? '' : ';'}${n}});`;
5783 if (intro)
5784 magicString.prepend(intro);
5785 if (outro)
5786 magicString.append(outro);
5787 return magicString
5788 .indent(`${t}${t}${t}`)
5789 .append(wrapperEnd)
5790 .prepend(wrapperStart);
5791}
5792
5793function globalProp(name, globalVar) {
5794 if (!name)
5795 return 'null';
5796 return `${globalVar}${keypath(name)}`;
5797}
5798function safeAccess(name, globalVar, _) {
5799 const parts = name.split('.');
5800 let acc = globalVar;
5801 return parts.map(part => ((acc += property(part)), acc)).join(`${_}&&${_}`);
5802}
5803function umd(magicString, { dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, options) {
5804 const _ = options.compact ? '' : ' ';
5805 const n = options.compact ? '' : '\n';
5806 const factoryVar = options.compact ? 'f' : 'factory';
5807 const globalVar = options.compact ? 'g' : 'global';
5808 if (hasExports && !options.name) {
5809 error({
5810 code: 'INVALID_OPTION',
5811 message: 'You must supply "output.name" for UMD bundles.'
5812 });
5813 }
5814 warnOnBuiltins(warn, dependencies);
5815 const amdDeps = dependencies.map(m => `'${m.id}'`);
5816 const cjsDeps = dependencies.map(m => `require('${m.id}')`);
5817 const trimmedImports = trimEmptyImports(dependencies);
5818 const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar));
5819 const factoryArgs = trimmedImports.map(m => m.name);
5820 if (namedExportsMode && (hasExports || options.noConflict === true)) {
5821 amdDeps.unshift(`'exports'`);
5822 cjsDeps.unshift(`exports`);
5823 globalDeps.unshift(assignToDeepVariable(options.name, globalVar, options.globals, options.compact, `${options.extend ? `${globalProp(options.name, globalVar)}${_}||${_}` : ''}{}`));
5824 factoryArgs.unshift('exports');
5825 }
5826 const amdOptions = options.amd || {};
5827 const amdParams = (amdOptions.id ? `'${amdOptions.id}',${_}` : ``) +
5828 (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
5829 const define = amdOptions.define || 'define';
5830 const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
5831 const useStrict = options.strict !== false ? `${_}'use strict';${n}` : ``;
5832 let iifeExport;
5833 if (options.noConflict === true) {
5834 const noConflictExportsVar = options.compact ? 'e' : 'exports';
5835 let factory;
5836 if (!namedExportsMode && hasExports) {
5837 factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(options.name, globalVar, options.globals, options.compact, `${factoryVar}(${globalDeps.join(`,${_}`)})`)};`;
5838 }
5839 else if (namedExportsMode) {
5840 const module = globalDeps.shift();
5841 factory =
5842 `var ${noConflictExportsVar}${_}=${_}${module};${n}` +
5843 `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
5844 }
5845 iifeExport =
5846 `(function${_}()${_}{${n}` +
5847 `${t}${t}var current${_}=${_}${safeAccess(options.name, globalVar, _)};${n}` +
5848 `${t}${t}${factory}${n}` +
5849 `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` +
5850 `${globalProp(options.name, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${options.compact ? '' : '; '}};${n}` +
5851 `${t}}())`;
5852 }
5853 else {
5854 iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
5855 if (!namedExportsMode && hasExports) {
5856 iifeExport = assignToDeepVariable(options.name, globalVar, options.globals, options.compact, iifeExport);
5857 }
5858 }
5859 const iifeNeedsGlobal = hasExports || (options.noConflict === true && namedExportsMode) || globalDeps.length > 0;
5860 const globalParam = iifeNeedsGlobal ? `${globalVar},${_}` : '';
5861 const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
5862 const iifeStart = iifeNeedsGlobal ? `(${globalVar}${_}=${_}${globalVar}${_}||${_}self,${_}` : '';
5863 const iifeEnd = iifeNeedsGlobal ? ')' : '';
5864 const cjsIntro = iifeNeedsGlobal
5865 ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
5866 `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
5867 : '';
5868 // factory function should be wrapped by parentheses to avoid lazy parsing
5869 const wrapperIntro = `(function${_}(${globalParam}${factoryVar})${_}{${n}` +
5870 cjsIntro +
5871 `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
5872 `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
5873 `}(${globalArg}(function${_}(${factoryArgs.join(', ')})${_}{${useStrict}${n}`;
5874 const wrapperOutro = n + n + '})));';
5875 // var foo__default = 'default' in foo ? foo['default'] : foo;
5876 const interopBlock = getInteropBlock(dependencies, options, varOrConst);
5877 if (interopBlock)
5878 magicString.prepend(interopBlock + n + n);
5879 if (intro)
5880 magicString.prepend(intro);
5881 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
5882 if (exportBlock)
5883 magicString.append(n + n + exportBlock);
5884 if (namedExportsMode && hasExports && options.esModule)
5885 magicString.append(n + n + (options.compact ? compactEsModuleExport : esModuleExport));
5886 if (outro)
5887 magicString.append(outro);
5888 return magicString
5889 .trim()
5890 .indent(t)
5891 .append(wrapperOutro)
5892 .prepend(wrapperIntro);
5893}
5894
5895var finalisers = { system, amd, cjs, es: esm, iife, umd };
5896
5897const extractors = {
5898 ArrayPattern(names, param) {
5899 for (const element of param.elements) {
5900 if (element)
5901 extractors[element.type](names, element);
5902 }
5903 },
5904 AssignmentPattern(names, param) {
5905 extractors[param.left.type](names, param.left);
5906 },
5907 Identifier(names, param) {
5908 names.push(param.name);
5909 },
5910 MemberExpression() { },
5911 ObjectPattern(names, param) {
5912 for (const prop of param.properties) {
5913 if (prop.type === 'RestElement') {
5914 extractors.RestElement(names, prop);
5915 }
5916 else {
5917 extractors[prop.value.type](names, prop.value);
5918 }
5919 }
5920 },
5921 RestElement(names, param) {
5922 extractors[param.argument.type](names, param.argument);
5923 }
5924};
5925const extractAssignedNames = function extractAssignedNames(param) {
5926 const names = [];
5927 extractors[param.type](names, param);
5928 return names;
5929};
5930
5931class ArrayExpression extends NodeBase {
5932 bind() {
5933 super.bind();
5934 for (const element of this.elements) {
5935 if (element !== null)
5936 element.deoptimizePath(UNKNOWN_PATH);
5937 }
5938 }
5939 getReturnExpressionWhenCalledAtPath(path) {
5940 if (path.length !== 1)
5941 return UNKNOWN_EXPRESSION;
5942 return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
5943 }
5944 hasEffectsWhenAccessedAtPath(path) {
5945 return path.length > 1;
5946 }
5947 hasEffectsWhenCalledAtPath(path, callOptions, context) {
5948 if (path.length === 1) {
5949 return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
5950 }
5951 return true;
5952 }
5953}
5954
5955class ArrayPattern extends NodeBase {
5956 addExportedVariables(variables) {
5957 for (const element of this.elements) {
5958 if (element !== null) {
5959 element.addExportedVariables(variables);
5960 }
5961 }
5962 }
5963 declare(kind) {
5964 const variables = [];
5965 for (const element of this.elements) {
5966 if (element !== null) {
5967 variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
5968 }
5969 }
5970 return variables;
5971 }
5972 deoptimizePath(path) {
5973 if (path.length === 0) {
5974 for (const element of this.elements) {
5975 if (element !== null) {
5976 element.deoptimizePath(path);
5977 }
5978 }
5979 }
5980 }
5981 hasEffectsWhenAssignedAtPath(path, context) {
5982 if (path.length > 0)
5983 return true;
5984 for (const element of this.elements) {
5985 if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
5986 return true;
5987 }
5988 return false;
5989 }
5990}
5991
5992class BlockScope extends ChildScope {
5993 addDeclaration(identifier, context, init = null, isHoisted) {
5994 if (isHoisted) {
5995 return this.parent.addDeclaration(identifier, context, isHoisted === 'function' ? init : UNKNOWN_EXPRESSION, isHoisted);
5996 }
5997 else {
5998 return super.addDeclaration(identifier, context, init, false);
5999 }
6000 }
6001}
6002
6003class BlockStatement$1 extends NodeBase {
6004 addImplicitReturnExpressionToScope() {
6005 const lastStatement = this.body[this.body.length - 1];
6006 if (!lastStatement || lastStatement.type !== ReturnStatement) {
6007 this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
6008 }
6009 }
6010 createScope(parentScope) {
6011 this.scope = this.parent.preventChildBlockScope
6012 ? parentScope
6013 : new BlockScope(parentScope);
6014 }
6015 hasEffects(context) {
6016 for (const node of this.body) {
6017 if (node.hasEffects(context))
6018 return true;
6019 if (context.brokenFlow)
6020 break;
6021 }
6022 return false;
6023 }
6024 include(context, includeChildrenRecursively) {
6025 this.included = true;
6026 for (const node of this.body) {
6027 if (includeChildrenRecursively || node.shouldBeIncluded(context))
6028 node.include(context, includeChildrenRecursively);
6029 }
6030 }
6031 render(code, options) {
6032 if (this.body.length) {
6033 renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
6034 }
6035 else {
6036 super.render(code, options);
6037 }
6038 }
6039}
6040
6041class ArrowFunctionExpression extends NodeBase {
6042 createScope(parentScope) {
6043 this.scope = new ReturnValueScope(parentScope, this.context);
6044 }
6045 deoptimizePath(path) {
6046 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
6047 // which means the return expression needs to be reassigned
6048 if (path.length === 1 && path[0] === UnknownKey) {
6049 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
6050 }
6051 }
6052 getReturnExpressionWhenCalledAtPath(path) {
6053 return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
6054 }
6055 hasEffects() {
6056 return false;
6057 }
6058 hasEffectsWhenAccessedAtPath(path) {
6059 return path.length > 1;
6060 }
6061 hasEffectsWhenAssignedAtPath(path) {
6062 return path.length > 1;
6063 }
6064 hasEffectsWhenCalledAtPath(path, _callOptions, context) {
6065 if (path.length > 0)
6066 return true;
6067 for (const param of this.params) {
6068 if (param.hasEffects(context))
6069 return true;
6070 }
6071 const { ignore, brokenFlow } = context;
6072 context.ignore = {
6073 breaks: false,
6074 continues: false,
6075 labels: new Set(),
6076 returnAwaitYield: true
6077 };
6078 if (this.body.hasEffects(context))
6079 return true;
6080 context.ignore = ignore;
6081 context.brokenFlow = brokenFlow;
6082 return false;
6083 }
6084 include(context, includeChildrenRecursively) {
6085 this.included = true;
6086 for (const param of this.params) {
6087 if (!(param instanceof Identifier$1)) {
6088 param.include(context, includeChildrenRecursively);
6089 }
6090 }
6091 const { brokenFlow } = context;
6092 context.brokenFlow = BROKEN_FLOW_NONE;
6093 this.body.include(context, includeChildrenRecursively);
6094 context.brokenFlow = brokenFlow;
6095 }
6096 includeCallArguments(context, args) {
6097 this.scope.includeCallArguments(context, args);
6098 }
6099 initialise() {
6100 this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
6101 if (this.body instanceof BlockStatement$1) {
6102 this.body.addImplicitReturnExpressionToScope();
6103 }
6104 else {
6105 this.scope.addReturnExpression(this.body);
6106 }
6107 }
6108 parseNode(esTreeNode) {
6109 if (esTreeNode.body.type === BlockStatement) {
6110 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
6111 }
6112 super.parseNode(esTreeNode);
6113 }
6114}
6115ArrowFunctionExpression.prototype.preventChildBlockScope = true;
6116
6117function getSystemExportStatement(exportedVariables) {
6118 if (exportedVariables.length === 1) {
6119 return `exports('${exportedVariables[0].safeExportName ||
6120 exportedVariables[0].exportName}', ${exportedVariables[0].getName()});`;
6121 }
6122 else {
6123 return `exports({${exportedVariables
6124 .map(variable => `${variable.safeExportName || variable.exportName}: ${variable.getName()}`)
6125 .join(', ')}});`;
6126 }
6127}
6128
6129class AssignmentExpression extends NodeBase {
6130 bind() {
6131 super.bind();
6132 this.left.deoptimizePath(EMPTY_PATH);
6133 // We cannot propagate mutations of the new binding to the old binding with certainty
6134 this.right.deoptimizePath(UNKNOWN_PATH);
6135 }
6136 hasEffects(context) {
6137 return (this.right.hasEffects(context) ||
6138 this.left.hasEffects(context) ||
6139 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
6140 }
6141 hasEffectsWhenAccessedAtPath(path, context) {
6142 return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, context);
6143 }
6144 render(code, options) {
6145 this.left.render(code, options);
6146 this.right.render(code, options);
6147 if (options.format === 'system') {
6148 if (this.left.variable && this.left.variable.exportName) {
6149 code.prependLeft(code.original.indexOf('=', this.left.end) + 1, ` exports('${this.left.variable.exportName}',`);
6150 code.appendLeft(this.right.end, `)`);
6151 }
6152 else if ('addExportedVariables' in this.left) {
6153 const systemPatternExports = [];
6154 this.left.addExportedVariables(systemPatternExports);
6155 if (systemPatternExports.length > 0) {
6156 code.prependRight(this.start, `function (v) {${getSystemExportStatement(systemPatternExports)} return v;} (`);
6157 code.appendLeft(this.end, ')');
6158 }
6159 }
6160 }
6161 }
6162}
6163
6164class AssignmentPattern extends NodeBase {
6165 addExportedVariables(variables) {
6166 this.left.addExportedVariables(variables);
6167 }
6168 bind() {
6169 super.bind();
6170 this.left.deoptimizePath(EMPTY_PATH);
6171 this.right.deoptimizePath(UNKNOWN_PATH);
6172 }
6173 declare(kind, init) {
6174 return this.left.declare(kind, init);
6175 }
6176 deoptimizePath(path) {
6177 path.length === 0 && this.left.deoptimizePath(path);
6178 }
6179 hasEffectsWhenAssignedAtPath(path, context) {
6180 return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
6181 }
6182 render(code, options, { isShorthandProperty } = BLANK) {
6183 this.left.render(code, options, { isShorthandProperty });
6184 this.right.render(code, options);
6185 }
6186}
6187
6188class AwaitExpression extends NodeBase {
6189 hasEffects(context) {
6190 return !context.ignore.returnAwaitYield || this.argument.hasEffects(context);
6191 }
6192 include(context, includeChildrenRecursively) {
6193 if (!this.included) {
6194 this.included = true;
6195 checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
6196 let parent = this.parent;
6197 do {
6198 if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
6199 break checkTopLevelAwait;
6200 } while ((parent = parent.parent));
6201 this.context.usesTopLevelAwait = true;
6202 }
6203 }
6204 this.argument.include(context, includeChildrenRecursively);
6205 }
6206}
6207
6208class ExpressionStatement$1 extends NodeBase {
6209 initialise() {
6210 if (this.directive &&
6211 this.directive !== 'use strict' &&
6212 this.parent.type === Program) {
6213 this.context.warn(
6214 // This is necessary, because either way (deleting or not) can lead to errors.
6215 {
6216 code: 'MODULE_LEVEL_DIRECTIVE',
6217 message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
6218 }, this.start);
6219 }
6220 }
6221 render(code, options) {
6222 super.render(code, options);
6223 if (this.included)
6224 this.insertSemicolon(code);
6225 }
6226 shouldBeIncluded(context) {
6227 if (this.directive && this.directive !== 'use strict')
6228 return this.parent.type !== Program;
6229 return super.shouldBeIncluded(context);
6230 }
6231}
6232
6233const binaryOperators = {
6234 '!=': (left, right) => left != right,
6235 '!==': (left, right) => left !== right,
6236 '%': (left, right) => left % right,
6237 '&': (left, right) => left & right,
6238 '*': (left, right) => left * right,
6239 // At the moment, "**" will be transpiled to Math.pow
6240 '**': (left, right) => Math.pow(left, right),
6241 '+': (left, right) => left + right,
6242 '-': (left, right) => left - right,
6243 '/': (left, right) => left / right,
6244 '<': (left, right) => left < right,
6245 '<<': (left, right) => left << right,
6246 '<=': (left, right) => left <= right,
6247 '==': (left, right) => left == right,
6248 '===': (left, right) => left === right,
6249 '>': (left, right) => left > right,
6250 '>=': (left, right) => left >= right,
6251 '>>': (left, right) => left >> right,
6252 '>>>': (left, right) => left >>> right,
6253 '^': (left, right) => left ^ right,
6254 in: () => UnknownValue,
6255 instanceof: () => UnknownValue,
6256 '|': (left, right) => left | right
6257};
6258class BinaryExpression extends NodeBase {
6259 deoptimizeCache() { }
6260 getLiteralValueAtPath(path, recursionTracker, origin) {
6261 if (path.length > 0)
6262 return UnknownValue;
6263 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
6264 if (leftValue === UnknownValue)
6265 return UnknownValue;
6266 const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
6267 if (rightValue === UnknownValue)
6268 return UnknownValue;
6269 const operatorFn = binaryOperators[this.operator];
6270 if (!operatorFn)
6271 return UnknownValue;
6272 return operatorFn(leftValue, rightValue);
6273 }
6274 hasEffects(context) {
6275 // support some implicit type coercion runtime errors
6276 if (this.operator === '+' &&
6277 this.parent instanceof ExpressionStatement$1 &&
6278 this.left.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this) === '')
6279 return true;
6280 return super.hasEffects(context);
6281 }
6282 hasEffectsWhenAccessedAtPath(path) {
6283 return path.length > 1;
6284 }
6285}
6286
6287class BreakStatement extends NodeBase {
6288 hasEffects(context) {
6289 if (this.label) {
6290 if (!context.ignore.labels.has(this.label.name))
6291 return true;
6292 context.includedLabels.add(this.label.name);
6293 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
6294 }
6295 else {
6296 if (!context.ignore.breaks)
6297 return true;
6298 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
6299 }
6300 return false;
6301 }
6302 include(context) {
6303 this.included = true;
6304 if (this.label) {
6305 this.label.include(context);
6306 context.includedLabels.add(this.label.name);
6307 }
6308 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
6309 }
6310}
6311
6312class CallExpression$1 extends NodeBase {
6313 constructor() {
6314 super(...arguments);
6315 // We collect deoptimization information if returnExpression !== UNKNOWN_EXPRESSION
6316 this.expressionsToBeDeoptimized = [];
6317 this.returnExpression = null;
6318 }
6319 bind() {
6320 super.bind();
6321 if (this.callee instanceof Identifier$1) {
6322 const variable = this.scope.findVariable(this.callee.name);
6323 if (variable.isNamespace) {
6324 this.context.error({
6325 code: 'CANNOT_CALL_NAMESPACE',
6326 message: `Cannot call a namespace ('${this.callee.name}')`
6327 }, this.start);
6328 }
6329 if (this.callee.name === 'eval') {
6330 this.context.warn({
6331 code: 'EVAL',
6332 message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
6333 url: 'https://rollupjs.org/guide/en/#avoiding-eval'
6334 }, this.start);
6335 }
6336 }
6337 if (this.returnExpression === null) {
6338 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
6339 }
6340 for (const argument of this.arguments) {
6341 // This will make sure all properties of parameters behave as "unknown"
6342 argument.deoptimizePath(UNKNOWN_PATH);
6343 }
6344 }
6345 deoptimizeCache() {
6346 if (this.returnExpression !== UNKNOWN_EXPRESSION) {
6347 this.returnExpression = UNKNOWN_EXPRESSION;
6348 for (const expression of this.expressionsToBeDeoptimized) {
6349 expression.deoptimizeCache();
6350 }
6351 }
6352 }
6353 deoptimizePath(path) {
6354 if (path.length === 0)
6355 return;
6356 const trackedEntities = this.context.deoptimizationTracker.getEntities(path);
6357 if (trackedEntities.has(this))
6358 return;
6359 trackedEntities.add(this);
6360 if (this.returnExpression === null) {
6361 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
6362 }
6363 this.returnExpression.deoptimizePath(path);
6364 }
6365 getLiteralValueAtPath(path, recursionTracker, origin) {
6366 if (this.returnExpression === null) {
6367 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this);
6368 }
6369 if (this.returnExpression === UNKNOWN_EXPRESSION) {
6370 return UnknownValue;
6371 }
6372 const trackedEntities = recursionTracker.getEntities(path);
6373 if (trackedEntities.has(this.returnExpression)) {
6374 return UnknownValue;
6375 }
6376 this.expressionsToBeDeoptimized.push(origin);
6377 trackedEntities.add(this.returnExpression);
6378 const value = this.returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
6379 trackedEntities.delete(this.returnExpression);
6380 return value;
6381 }
6382 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
6383 if (this.returnExpression === null) {
6384 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this);
6385 }
6386 if (this.returnExpression === UNKNOWN_EXPRESSION) {
6387 return UNKNOWN_EXPRESSION;
6388 }
6389 const trackedEntities = recursionTracker.getEntities(path);
6390 if (trackedEntities.has(this.returnExpression)) {
6391 return UNKNOWN_EXPRESSION;
6392 }
6393 this.expressionsToBeDeoptimized.push(origin);
6394 trackedEntities.add(this.returnExpression);
6395 const value = this.returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
6396 trackedEntities.delete(this.returnExpression);
6397 return value;
6398 }
6399 hasEffects(context) {
6400 for (const argument of this.arguments) {
6401 if (argument.hasEffects(context))
6402 return true;
6403 }
6404 if (this.context.annotations && this.annotatedPure)
6405 return false;
6406 return (this.callee.hasEffects(context) ||
6407 this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
6408 }
6409 hasEffectsWhenAccessedAtPath(path, context) {
6410 if (path.length === 0)
6411 return false;
6412 const trackedExpressions = context.accessed.getEntities(path);
6413 if (trackedExpressions.has(this))
6414 return false;
6415 trackedExpressions.add(this);
6416 return this.returnExpression.hasEffectsWhenAccessedAtPath(path, context);
6417 }
6418 hasEffectsWhenAssignedAtPath(path, context) {
6419 if (path.length === 0)
6420 return true;
6421 const trackedExpressions = context.assigned.getEntities(path);
6422 if (trackedExpressions.has(this))
6423 return false;
6424 trackedExpressions.add(this);
6425 return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
6426 }
6427 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6428 const trackedExpressions = (callOptions.withNew
6429 ? context.instantiated
6430 : context.called).getEntities(path);
6431 if (trackedExpressions.has(this))
6432 return false;
6433 trackedExpressions.add(this);
6434 return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
6435 }
6436 include(context, includeChildrenRecursively) {
6437 if (includeChildrenRecursively) {
6438 super.include(context, includeChildrenRecursively);
6439 if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
6440 this.callee instanceof Identifier$1 &&
6441 this.callee.variable) {
6442 this.callee.variable.markCalledFromTryStatement();
6443 }
6444 }
6445 else {
6446 this.included = true;
6447 this.callee.include(context, false);
6448 }
6449 this.callee.includeCallArguments(context, this.arguments);
6450 if (!this.returnExpression.included) {
6451 this.returnExpression.include(context, false);
6452 }
6453 }
6454 initialise() {
6455 this.callOptions = {
6456 args: this.arguments,
6457 withNew: false
6458 };
6459 }
6460 render(code, options, { renderedParentType } = BLANK) {
6461 this.callee.render(code, options);
6462 if (this.arguments.length > 0) {
6463 if (this.arguments[this.arguments.length - 1].included) {
6464 for (const arg of this.arguments) {
6465 arg.render(code, options);
6466 }
6467 }
6468 else {
6469 let lastIncludedIndex = this.arguments.length - 2;
6470 while (lastIncludedIndex >= 0 && !this.arguments[lastIncludedIndex].included) {
6471 lastIncludedIndex--;
6472 }
6473 if (lastIncludedIndex >= 0) {
6474 for (let index = 0; index <= lastIncludedIndex; index++) {
6475 this.arguments[index].render(code, options);
6476 }
6477 code.remove(findFirstOccurrenceOutsideComment(code.original, ',', this.arguments[lastIncludedIndex].end), this.end - 1);
6478 }
6479 else {
6480 code.remove(findFirstOccurrenceOutsideComment(code.original, '(', this.callee.end) + 1, this.end - 1);
6481 }
6482 }
6483 }
6484 if (renderedParentType === ExpressionStatement &&
6485 this.callee.type === FunctionExpression) {
6486 code.appendRight(this.start, '(');
6487 code.prependLeft(this.end, ')');
6488 }
6489 }
6490}
6491
6492class CatchScope extends ParameterScope {
6493 addDeclaration(identifier, context, init, isHoisted) {
6494 if (isHoisted) {
6495 return this.parent.addDeclaration(identifier, context, init, isHoisted);
6496 }
6497 else {
6498 return super.addDeclaration(identifier, context, init, false);
6499 }
6500 }
6501}
6502
6503class CatchClause extends NodeBase {
6504 createScope(parentScope) {
6505 this.scope = new CatchScope(parentScope, this.context);
6506 }
6507 initialise() {
6508 if (this.param) {
6509 this.param.declare('parameter', UNKNOWN_EXPRESSION);
6510 }
6511 }
6512 parseNode(esTreeNode) {
6513 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope);
6514 super.parseNode(esTreeNode);
6515 }
6516}
6517CatchClause.prototype.preventChildBlockScope = true;
6518
6519class ClassBody extends NodeBase {
6520 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6521 if (path.length > 0)
6522 return true;
6523 return (this.classConstructor !== null &&
6524 this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
6525 }
6526 initialise() {
6527 for (const method of this.body) {
6528 if (method.kind === 'constructor') {
6529 this.classConstructor = method;
6530 return;
6531 }
6532 }
6533 this.classConstructor = null;
6534 }
6535}
6536
6537class ClassExpression extends ClassNode {
6538}
6539
6540class MultiExpression {
6541 constructor(expressions) {
6542 this.included = false;
6543 this.expressions = expressions;
6544 }
6545 deoptimizePath(path) {
6546 for (const expression of this.expressions) {
6547 expression.deoptimizePath(path);
6548 }
6549 }
6550 getLiteralValueAtPath() {
6551 return UnknownValue;
6552 }
6553 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
6554 return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)));
6555 }
6556 hasEffectsWhenAccessedAtPath(path, context) {
6557 for (const expression of this.expressions) {
6558 if (expression.hasEffectsWhenAccessedAtPath(path, context))
6559 return true;
6560 }
6561 return false;
6562 }
6563 hasEffectsWhenAssignedAtPath(path, context) {
6564 for (const expression of this.expressions) {
6565 if (expression.hasEffectsWhenAssignedAtPath(path, context))
6566 return true;
6567 }
6568 return false;
6569 }
6570 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6571 for (const expression of this.expressions) {
6572 if (expression.hasEffectsWhenCalledAtPath(path, callOptions, context))
6573 return true;
6574 }
6575 return false;
6576 }
6577 include() { }
6578 includeCallArguments() { }
6579}
6580
6581class ConditionalExpression extends NodeBase {
6582 constructor() {
6583 super(...arguments);
6584 // We collect deoptimization information if usedBranch !== null
6585 this.expressionsToBeDeoptimized = [];
6586 this.isBranchResolutionAnalysed = false;
6587 this.unusedBranch = null;
6588 this.usedBranch = null;
6589 }
6590 bind() {
6591 super.bind();
6592 if (!this.isBranchResolutionAnalysed)
6593 this.analyseBranchResolution();
6594 }
6595 deoptimizeCache() {
6596 if (this.usedBranch !== null) {
6597 // We did not track if there were reassignments to the previous branch.
6598 // Also, the return value might need to be reassigned.
6599 this.usedBranch = null;
6600 this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
6601 for (const expression of this.expressionsToBeDeoptimized) {
6602 expression.deoptimizeCache();
6603 }
6604 }
6605 }
6606 deoptimizePath(path) {
6607 if (path.length > 0) {
6608 if (!this.isBranchResolutionAnalysed)
6609 this.analyseBranchResolution();
6610 if (this.usedBranch === null) {
6611 this.consequent.deoptimizePath(path);
6612 this.alternate.deoptimizePath(path);
6613 }
6614 else {
6615 this.usedBranch.deoptimizePath(path);
6616 }
6617 }
6618 }
6619 getLiteralValueAtPath(path, recursionTracker, origin) {
6620 if (!this.isBranchResolutionAnalysed)
6621 this.analyseBranchResolution();
6622 if (this.usedBranch === null)
6623 return UnknownValue;
6624 this.expressionsToBeDeoptimized.push(origin);
6625 return this.usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
6626 }
6627 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
6628 if (!this.isBranchResolutionAnalysed)
6629 this.analyseBranchResolution();
6630 if (this.usedBranch === null)
6631 return new MultiExpression([
6632 this.consequent.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
6633 this.alternate.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
6634 ]);
6635 this.expressionsToBeDeoptimized.push(origin);
6636 return this.usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
6637 }
6638 hasEffects(context) {
6639 if (this.test.hasEffects(context))
6640 return true;
6641 if (this.usedBranch === null) {
6642 return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
6643 }
6644 return this.usedBranch.hasEffects(context);
6645 }
6646 hasEffectsWhenAccessedAtPath(path, context) {
6647 if (path.length === 0)
6648 return false;
6649 if (this.usedBranch === null) {
6650 return (this.consequent.hasEffectsWhenAccessedAtPath(path, context) ||
6651 this.alternate.hasEffectsWhenAccessedAtPath(path, context));
6652 }
6653 return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
6654 }
6655 hasEffectsWhenAssignedAtPath(path, context) {
6656 if (path.length === 0)
6657 return true;
6658 if (this.usedBranch === null) {
6659 return (this.consequent.hasEffectsWhenAssignedAtPath(path, context) ||
6660 this.alternate.hasEffectsWhenAssignedAtPath(path, context));
6661 }
6662 return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
6663 }
6664 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6665 if (this.usedBranch === null) {
6666 return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
6667 this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, context));
6668 }
6669 return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
6670 }
6671 include(context, includeChildrenRecursively) {
6672 this.included = true;
6673 if (includeChildrenRecursively ||
6674 this.usedBranch === null ||
6675 this.test.shouldBeIncluded(context)) {
6676 this.test.include(context, includeChildrenRecursively);
6677 this.consequent.include(context, includeChildrenRecursively);
6678 this.alternate.include(context, includeChildrenRecursively);
6679 }
6680 else {
6681 this.usedBranch.include(context, includeChildrenRecursively);
6682 }
6683 }
6684 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
6685 if (!this.test.included) {
6686 const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
6687 const inclusionStart = (this.consequent.included
6688 ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
6689 : colonPos) + 1;
6690 if (preventASI) {
6691 removeLineBreaks(code, inclusionStart, this.usedBranch.start);
6692 }
6693 code.remove(this.start, inclusionStart);
6694 if (this.consequent.included) {
6695 code.remove(colonPos, this.end);
6696 }
6697 removeAnnotations(this, code);
6698 this.usedBranch.render(code, options, {
6699 isCalleeOfRenderedParent: renderedParentType
6700 ? isCalleeOfRenderedParent
6701 : this.parent.callee === this,
6702 renderedParentType: renderedParentType || this.parent.type
6703 });
6704 }
6705 else {
6706 super.render(code, options);
6707 }
6708 }
6709 analyseBranchResolution() {
6710 this.isBranchResolutionAnalysed = true;
6711 const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
6712 if (testValue !== UnknownValue) {
6713 if (testValue) {
6714 this.usedBranch = this.consequent;
6715 this.unusedBranch = this.alternate;
6716 }
6717 else {
6718 this.usedBranch = this.alternate;
6719 this.unusedBranch = this.consequent;
6720 }
6721 }
6722 }
6723}
6724
6725class ContinueStatement extends NodeBase {
6726 hasEffects(context) {
6727 if (this.label) {
6728 if (!context.ignore.labels.has(this.label.name))
6729 return true;
6730 context.includedLabels.add(this.label.name);
6731 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
6732 }
6733 else {
6734 if (!context.ignore.continues)
6735 return true;
6736 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
6737 }
6738 return false;
6739 }
6740 include(context) {
6741 this.included = true;
6742 if (this.label) {
6743 this.label.include(context);
6744 context.includedLabels.add(this.label.name);
6745 }
6746 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
6747 }
6748}
6749
6750class DoWhileStatement extends NodeBase {
6751 hasEffects(context) {
6752 if (this.test.hasEffects(context))
6753 return true;
6754 const { brokenFlow, ignore: { breaks, continues } } = context;
6755 context.ignore.breaks = true;
6756 context.ignore.continues = true;
6757 if (this.body.hasEffects(context))
6758 return true;
6759 context.ignore.breaks = breaks;
6760 context.ignore.continues = continues;
6761 context.brokenFlow = brokenFlow;
6762 return false;
6763 }
6764 include(context, includeChildrenRecursively) {
6765 this.included = true;
6766 this.test.include(context, includeChildrenRecursively);
6767 const { brokenFlow } = context;
6768 this.body.include(context, includeChildrenRecursively);
6769 context.brokenFlow = brokenFlow;
6770 }
6771}
6772
6773class EmptyStatement extends NodeBase {
6774 hasEffects() {
6775 return false;
6776 }
6777}
6778
6779class ExportAllDeclaration$1 extends NodeBase {
6780 hasEffects() {
6781 return false;
6782 }
6783 initialise() {
6784 this.context.addExport(this);
6785 }
6786 render(code, _options, { start, end } = BLANK) {
6787 code.remove(start, end);
6788 }
6789}
6790ExportAllDeclaration$1.prototype.needsBoundaries = true;
6791
6792class ExportNamedDeclaration extends NodeBase {
6793 bind() {
6794 // Do not bind specifiers
6795 if (this.declaration !== null)
6796 this.declaration.bind();
6797 }
6798 hasEffects(context) {
6799 return this.declaration !== null && this.declaration.hasEffects(context);
6800 }
6801 initialise() {
6802 this.context.addExport(this);
6803 }
6804 render(code, options, { start, end } = BLANK) {
6805 if (this.declaration === null) {
6806 code.remove(start, end);
6807 }
6808 else {
6809 code.remove(this.start, this.declaration.start);
6810 this.declaration.render(code, options, { start, end });
6811 }
6812 }
6813}
6814ExportNamedDeclaration.prototype.needsBoundaries = true;
6815
6816class ForInStatement extends NodeBase {
6817 bind() {
6818 this.left.bind();
6819 this.left.deoptimizePath(EMPTY_PATH);
6820 this.right.bind();
6821 this.body.bind();
6822 }
6823 createScope(parentScope) {
6824 this.scope = new BlockScope(parentScope);
6825 }
6826 hasEffects(context) {
6827 if ((this.left &&
6828 (this.left.hasEffects(context) ||
6829 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))) ||
6830 (this.right && this.right.hasEffects(context)))
6831 return true;
6832 const { brokenFlow, ignore: { breaks, continues } } = context;
6833 context.ignore.breaks = true;
6834 context.ignore.continues = true;
6835 if (this.body.hasEffects(context))
6836 return true;
6837 context.ignore.breaks = breaks;
6838 context.ignore.continues = continues;
6839 context.brokenFlow = brokenFlow;
6840 return false;
6841 }
6842 include(context, includeChildrenRecursively) {
6843 this.included = true;
6844 this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context);
6845 this.left.deoptimizePath(EMPTY_PATH);
6846 this.right.include(context, includeChildrenRecursively);
6847 const { brokenFlow } = context;
6848 this.body.include(context, includeChildrenRecursively);
6849 context.brokenFlow = brokenFlow;
6850 }
6851 render(code, options) {
6852 this.left.render(code, options, NO_SEMICOLON);
6853 this.right.render(code, options, NO_SEMICOLON);
6854 // handle no space between "in" and the right side
6855 if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
6856 code.prependLeft(this.right.start, ' ');
6857 }
6858 this.body.render(code, options);
6859 }
6860}
6861
6862class ForOfStatement extends NodeBase {
6863 bind() {
6864 this.left.bind();
6865 this.left.deoptimizePath(EMPTY_PATH);
6866 this.right.bind();
6867 this.body.bind();
6868 }
6869 createScope(parentScope) {
6870 this.scope = new BlockScope(parentScope);
6871 }
6872 hasEffects() {
6873 // Placeholder until proper Symbol.Iterator support
6874 return true;
6875 }
6876 include(context, includeChildrenRecursively) {
6877 this.included = true;
6878 this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context);
6879 this.left.deoptimizePath(EMPTY_PATH);
6880 this.right.include(context, includeChildrenRecursively);
6881 const { brokenFlow } = context;
6882 this.body.include(context, includeChildrenRecursively);
6883 context.brokenFlow = brokenFlow;
6884 }
6885 render(code, options) {
6886 this.left.render(code, options, NO_SEMICOLON);
6887 this.right.render(code, options, NO_SEMICOLON);
6888 // handle no space between "of" and the right side
6889 if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
6890 code.prependLeft(this.right.start, ' ');
6891 }
6892 this.body.render(code, options);
6893 }
6894}
6895
6896class ForStatement extends NodeBase {
6897 createScope(parentScope) {
6898 this.scope = new BlockScope(parentScope);
6899 }
6900 hasEffects(context) {
6901 if ((this.init && this.init.hasEffects(context)) ||
6902 (this.test && this.test.hasEffects(context)) ||
6903 (this.update && this.update.hasEffects(context)))
6904 return true;
6905 const { brokenFlow, ignore: { breaks, continues } } = context;
6906 context.ignore.breaks = true;
6907 context.ignore.continues = true;
6908 if (this.body.hasEffects(context))
6909 return true;
6910 context.ignore.breaks = breaks;
6911 context.ignore.continues = continues;
6912 context.brokenFlow = brokenFlow;
6913 return false;
6914 }
6915 include(context, includeChildrenRecursively) {
6916 this.included = true;
6917 if (this.init)
6918 this.init.include(context, includeChildrenRecursively);
6919 if (this.test)
6920 this.test.include(context, includeChildrenRecursively);
6921 const { brokenFlow } = context;
6922 if (this.update)
6923 this.update.include(context, includeChildrenRecursively);
6924 this.body.include(context, includeChildrenRecursively);
6925 context.brokenFlow = brokenFlow;
6926 }
6927 render(code, options) {
6928 if (this.init)
6929 this.init.render(code, options, NO_SEMICOLON);
6930 if (this.test)
6931 this.test.render(code, options, NO_SEMICOLON);
6932 if (this.update)
6933 this.update.render(code, options, NO_SEMICOLON);
6934 this.body.render(code, options);
6935 }
6936}
6937
6938class FunctionExpression$1 extends FunctionNode {
6939}
6940
6941class IfStatement extends NodeBase {
6942 bind() {
6943 super.bind();
6944 this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
6945 }
6946 deoptimizeCache() {
6947 this.testValue = UnknownValue;
6948 }
6949 hasEffects(context) {
6950 if (this.test.hasEffects(context))
6951 return true;
6952 if (this.testValue === UnknownValue) {
6953 const { brokenFlow } = context;
6954 if (this.consequent.hasEffects(context))
6955 return true;
6956 const consequentBrokenFlow = context.brokenFlow;
6957 context.brokenFlow = brokenFlow;
6958 if (this.alternate === null)
6959 return false;
6960 if (this.alternate.hasEffects(context))
6961 return true;
6962 context.brokenFlow =
6963 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
6964 return false;
6965 }
6966 return this.testValue
6967 ? this.consequent.hasEffects(context)
6968 : this.alternate !== null && this.alternate.hasEffects(context);
6969 }
6970 include(context, includeChildrenRecursively) {
6971 this.included = true;
6972 if (includeChildrenRecursively) {
6973 this.includeRecursively(includeChildrenRecursively, context);
6974 }
6975 else if (this.testValue === UnknownValue) {
6976 this.includeUnknownTest(context);
6977 }
6978 else {
6979 this.includeKnownTest(context);
6980 }
6981 }
6982 render(code, options) {
6983 // Note that unknown test values are always included
6984 if (!this.test.included &&
6985 (this.testValue
6986 ? this.alternate === null || !this.alternate.included
6987 : !this.consequent.included)) {
6988 const singleRetainedBranch = (this.testValue
6989 ? this.consequent
6990 : this.alternate);
6991 code.remove(this.start, singleRetainedBranch.start);
6992 code.remove(singleRetainedBranch.end, this.end);
6993 removeAnnotations(this, code);
6994 singleRetainedBranch.render(code, options);
6995 }
6996 else {
6997 if (this.test.included) {
6998 this.test.render(code, options);
6999 }
7000 else {
7001 code.overwrite(this.test.start, this.test.end, this.testValue ? 'true' : 'false');
7002 }
7003 if (this.consequent.included) {
7004 this.consequent.render(code, options);
7005 }
7006 else {
7007 code.overwrite(this.consequent.start, this.consequent.end, ';');
7008 }
7009 if (this.alternate !== null) {
7010 if (this.alternate.included) {
7011 this.alternate.render(code, options);
7012 }
7013 else {
7014 code.remove(this.consequent.end, this.alternate.end);
7015 }
7016 }
7017 }
7018 }
7019 includeKnownTest(context) {
7020 if (this.test.shouldBeIncluded(context)) {
7021 this.test.include(context, false);
7022 }
7023 if (this.testValue && this.consequent.shouldBeIncluded(context)) {
7024 this.consequent.include(context, false);
7025 }
7026 if (this.alternate !== null && !this.testValue && this.alternate.shouldBeIncluded(context)) {
7027 this.alternate.include(context, false);
7028 }
7029 }
7030 includeRecursively(includeChildrenRecursively, context) {
7031 this.test.include(context, includeChildrenRecursively);
7032 this.consequent.include(context, includeChildrenRecursively);
7033 if (this.alternate !== null) {
7034 this.alternate.include(context, includeChildrenRecursively);
7035 }
7036 }
7037 includeUnknownTest(context) {
7038 this.test.include(context, false);
7039 const { brokenFlow } = context;
7040 let consequentBrokenFlow = BROKEN_FLOW_NONE;
7041 if (this.consequent.shouldBeIncluded(context)) {
7042 this.consequent.include(context, false);
7043 consequentBrokenFlow = context.brokenFlow;
7044 context.brokenFlow = brokenFlow;
7045 }
7046 if (this.alternate !== null && this.alternate.shouldBeIncluded(context)) {
7047 this.alternate.include(context, false);
7048 context.brokenFlow =
7049 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
7050 }
7051 }
7052}
7053
7054class ImportDeclaration extends NodeBase {
7055 bind() { }
7056 hasEffects() {
7057 return false;
7058 }
7059 initialise() {
7060 this.context.addImport(this);
7061 }
7062 render(code, _options, { start, end } = BLANK) {
7063 code.remove(start, end);
7064 }
7065}
7066ImportDeclaration.prototype.needsBoundaries = true;
7067
7068class Import extends NodeBase {
7069 constructor() {
7070 super(...arguments);
7071 this.exportMode = 'auto';
7072 }
7073 hasEffects() {
7074 return true;
7075 }
7076 include(context, includeChildrenRecursively) {
7077 if (!this.included) {
7078 this.included = true;
7079 this.context.includeDynamicImport(this);
7080 }
7081 this.source.include(context, includeChildrenRecursively);
7082 }
7083 initialise() {
7084 this.context.addDynamicImport(this);
7085 }
7086 render(code, options) {
7087 if (this.inlineNamespace) {
7088 const _ = options.compact ? '' : ' ';
7089 const s = options.compact ? '' : ';';
7090 code.overwrite(this.start, this.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`);
7091 return;
7092 }
7093 const importMechanism = this.getDynamicImportMechanism(options);
7094 if (importMechanism) {
7095 code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, importMechanism.left);
7096 code.overwrite(this.end - 1, this.end, importMechanism.right);
7097 }
7098 this.source.render(code, options);
7099 }
7100 renderFinalResolution(code, resolution, format) {
7101 if (this.included) {
7102 if (format === 'amd' && resolution.startsWith("'.") && resolution.endsWith(".js'")) {
7103 resolution = resolution.slice(0, -4) + "'";
7104 }
7105 code.overwrite(this.source.start, this.source.end, resolution);
7106 }
7107 }
7108 setResolution(exportMode, inlineNamespace) {
7109 this.exportMode = exportMode;
7110 if (inlineNamespace) {
7111 this.inlineNamespace = inlineNamespace;
7112 }
7113 else {
7114 this.scope.addAccessedGlobalsByFormat({
7115 amd: ['require'],
7116 cjs: ['require'],
7117 system: ['module']
7118 });
7119 if (exportMode === 'auto') {
7120 this.scope.addAccessedGlobalsByFormat({
7121 amd: [INTEROP_NAMESPACE_VARIABLE],
7122 cjs: [INTEROP_NAMESPACE_VARIABLE]
7123 });
7124 }
7125 }
7126 }
7127 getDynamicImportMechanism(options) {
7128 switch (options.format) {
7129 case 'cjs': {
7130 const _ = options.compact ? '' : ' ';
7131 const resolve = options.compact ? 'c' : 'resolve';
7132 switch (this.exportMode) {
7133 case 'default':
7134 return {
7135 left: `new Promise(function${_}(${resolve})${_}{${_}${resolve}({${_}'default':${_}require(`,
7136 right: `)${_}});${_}})`
7137 };
7138 case 'auto':
7139 return {
7140 left: `new Promise(function${_}(${resolve})${_}{${_}${resolve}(${INTEROP_NAMESPACE_VARIABLE}(require(`,
7141 right: `)));${_}})`
7142 };
7143 default:
7144 return {
7145 left: `new Promise(function${_}(${resolve})${_}{${_}${resolve}(require(`,
7146 right: `));${_}})`
7147 };
7148 }
7149 }
7150 case 'amd': {
7151 const _ = options.compact ? '' : ' ';
7152 const resolve = options.compact ? 'c' : 'resolve';
7153 const reject = options.compact ? 'e' : 'reject';
7154 const resolveNamespace = this.exportMode === 'default'
7155 ? `function${_}(m)${_}{${_}${resolve}({${_}'default':${_}m${_}});${_}}`
7156 : this.exportMode === 'auto'
7157 ? `function${_}(m)${_}{${_}${resolve}(${INTEROP_NAMESPACE_VARIABLE}(m));${_}}`
7158 : resolve;
7159 return {
7160 left: `new Promise(function${_}(${resolve},${_}${reject})${_}{${_}require([`,
7161 right: `],${_}${resolveNamespace},${_}${reject})${_}})`
7162 };
7163 }
7164 case 'system':
7165 return {
7166 left: 'module.import(',
7167 right: ')'
7168 };
7169 case 'es':
7170 if (options.dynamicImportFunction) {
7171 return {
7172 left: `${options.dynamicImportFunction}(`,
7173 right: ')'
7174 };
7175 }
7176 }
7177 return null;
7178 }
7179}
7180
7181class LabeledStatement extends NodeBase {
7182 hasEffects(context) {
7183 const brokenFlow = context.brokenFlow;
7184 context.ignore.labels.add(this.label.name);
7185 if (this.body.hasEffects(context))
7186 return true;
7187 context.ignore.labels.delete(this.label.name);
7188 if (context.includedLabels.has(this.label.name)) {
7189 context.includedLabels.delete(this.label.name);
7190 context.brokenFlow = brokenFlow;
7191 }
7192 return false;
7193 }
7194 include(context, includeChildrenRecursively) {
7195 this.included = true;
7196 const brokenFlow = context.brokenFlow;
7197 this.body.include(context, includeChildrenRecursively);
7198 if (context.includedLabels.has(this.label.name)) {
7199 this.label.include(context);
7200 context.includedLabels.delete(this.label.name);
7201 context.brokenFlow = brokenFlow;
7202 }
7203 }
7204 render(code, options) {
7205 if (this.label.included) {
7206 this.label.render(code, options);
7207 }
7208 else {
7209 code.remove(this.start, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1);
7210 }
7211 this.body.render(code, options);
7212 }
7213}
7214
7215class Literal extends NodeBase {
7216 getLiteralValueAtPath(path) {
7217 if (path.length > 0 ||
7218 // unknown literals can also be null but do not start with an "n"
7219 (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
7220 typeof this.value === 'bigint' ||
7221 // to support shims for regular expressions
7222 this.context.code.charCodeAt(this.start) === 47) {
7223 return UnknownValue;
7224 }
7225 return this.value;
7226 }
7227 getReturnExpressionWhenCalledAtPath(path) {
7228 if (path.length !== 1)
7229 return UNKNOWN_EXPRESSION;
7230 return getMemberReturnExpressionWhenCalled(this.members, path[0]);
7231 }
7232 hasEffectsWhenAccessedAtPath(path) {
7233 if (this.value === null) {
7234 return path.length > 0;
7235 }
7236 return path.length > 1;
7237 }
7238 hasEffectsWhenAssignedAtPath(path) {
7239 return path.length > 0;
7240 }
7241 hasEffectsWhenCalledAtPath(path, callOptions, context) {
7242 if (path.length === 1) {
7243 return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, context);
7244 }
7245 return true;
7246 }
7247 initialise() {
7248 this.members = getLiteralMembersForValue(this.value);
7249 }
7250 render(code) {
7251 if (typeof this.value === 'string') {
7252 code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
7253 }
7254 }
7255}
7256
7257class LogicalExpression extends NodeBase {
7258 constructor() {
7259 super(...arguments);
7260 // We collect deoptimization information if usedBranch !== null
7261 this.expressionsToBeDeoptimized = [];
7262 this.isBranchResolutionAnalysed = false;
7263 this.unusedBranch = null;
7264 this.usedBranch = null;
7265 }
7266 bind() {
7267 super.bind();
7268 if (!this.isBranchResolutionAnalysed)
7269 this.analyseBranchResolution();
7270 }
7271 deoptimizeCache() {
7272 if (this.usedBranch !== null) {
7273 // We did not track if there were reassignments to any of the branches.
7274 // Also, the return values might need reassignment.
7275 this.usedBranch = null;
7276 this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
7277 for (const expression of this.expressionsToBeDeoptimized) {
7278 expression.deoptimizeCache();
7279 }
7280 }
7281 }
7282 deoptimizePath(path) {
7283 if (path.length > 0) {
7284 if (!this.isBranchResolutionAnalysed)
7285 this.analyseBranchResolution();
7286 if (this.usedBranch === null) {
7287 this.left.deoptimizePath(path);
7288 this.right.deoptimizePath(path);
7289 }
7290 else {
7291 this.usedBranch.deoptimizePath(path);
7292 }
7293 }
7294 }
7295 getLiteralValueAtPath(path, recursionTracker, origin) {
7296 if (!this.isBranchResolutionAnalysed)
7297 this.analyseBranchResolution();
7298 if (this.usedBranch === null)
7299 return UnknownValue;
7300 this.expressionsToBeDeoptimized.push(origin);
7301 return this.usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
7302 }
7303 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
7304 if (!this.isBranchResolutionAnalysed)
7305 this.analyseBranchResolution();
7306 if (this.usedBranch === null)
7307 return new MultiExpression([
7308 this.left.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
7309 this.right.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
7310 ]);
7311 this.expressionsToBeDeoptimized.push(origin);
7312 return this.usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
7313 }
7314 hasEffects(context) {
7315 if (this.usedBranch === null) {
7316 return this.left.hasEffects(context) || this.right.hasEffects(context);
7317 }
7318 return this.usedBranch.hasEffects(context);
7319 }
7320 hasEffectsWhenAccessedAtPath(path, context) {
7321 if (path.length === 0)
7322 return false;
7323 if (this.usedBranch === null) {
7324 return (this.left.hasEffectsWhenAccessedAtPath(path, context) ||
7325 this.right.hasEffectsWhenAccessedAtPath(path, context));
7326 }
7327 return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
7328 }
7329 hasEffectsWhenAssignedAtPath(path, context) {
7330 if (path.length === 0)
7331 return true;
7332 if (this.usedBranch === null) {
7333 return (this.left.hasEffectsWhenAssignedAtPath(path, context) ||
7334 this.right.hasEffectsWhenAssignedAtPath(path, context));
7335 }
7336 return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
7337 }
7338 hasEffectsWhenCalledAtPath(path, callOptions, context) {
7339 if (this.usedBranch === null) {
7340 return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
7341 this.right.hasEffectsWhenCalledAtPath(path, callOptions, context));
7342 }
7343 return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
7344 }
7345 include(context, includeChildrenRecursively) {
7346 this.included = true;
7347 if (includeChildrenRecursively ||
7348 this.usedBranch === null ||
7349 this.unusedBranch.shouldBeIncluded(context)) {
7350 this.left.include(context, includeChildrenRecursively);
7351 this.right.include(context, includeChildrenRecursively);
7352 }
7353 else {
7354 this.usedBranch.include(context, includeChildrenRecursively);
7355 }
7356 }
7357 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
7358 if (!this.left.included || !this.right.included) {
7359 const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
7360 if (this.right.included) {
7361 code.remove(this.start, operatorPos + 2);
7362 if (preventASI) {
7363 removeLineBreaks(code, operatorPos + 2, this.right.start);
7364 }
7365 }
7366 else {
7367 code.remove(operatorPos, this.end);
7368 }
7369 removeAnnotations(this, code);
7370 this.usedBranch.render(code, options, {
7371 isCalleeOfRenderedParent: renderedParentType
7372 ? isCalleeOfRenderedParent
7373 : this.parent.callee === this,
7374 renderedParentType: renderedParentType || this.parent.type
7375 });
7376 }
7377 else {
7378 super.render(code, options);
7379 }
7380 }
7381 analyseBranchResolution() {
7382 this.isBranchResolutionAnalysed = true;
7383 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
7384 if (leftValue !== UnknownValue) {
7385 if (this.operator === '||' ? leftValue : !leftValue) {
7386 this.usedBranch = this.left;
7387 this.unusedBranch = this.right;
7388 }
7389 else {
7390 this.usedBranch = this.right;
7391 this.unusedBranch = this.left;
7392 }
7393 }
7394 }
7395}
7396
7397function getResolvablePropertyKey(memberExpression) {
7398 return memberExpression.computed
7399 ? getResolvableComputedPropertyKey(memberExpression.property)
7400 : memberExpression.property.name;
7401}
7402function getResolvableComputedPropertyKey(propertyKey) {
7403 if (propertyKey instanceof Literal) {
7404 return String(propertyKey.value);
7405 }
7406 return null;
7407}
7408function getPathIfNotComputed(memberExpression) {
7409 const nextPathKey = memberExpression.propertyKey;
7410 const object = memberExpression.object;
7411 if (typeof nextPathKey === 'string') {
7412 if (object instanceof Identifier$1) {
7413 return [
7414 { key: object.name, pos: object.start },
7415 { key: nextPathKey, pos: memberExpression.property.start }
7416 ];
7417 }
7418 if (object instanceof MemberExpression) {
7419 const parentPath = getPathIfNotComputed(object);
7420 return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
7421 }
7422 }
7423 return null;
7424}
7425function getStringFromPath(path) {
7426 let pathString = path[0].key;
7427 for (let index = 1; index < path.length; index++) {
7428 pathString += '.' + path[index].key;
7429 }
7430 return pathString;
7431}
7432class MemberExpression extends NodeBase {
7433 constructor() {
7434 super(...arguments);
7435 this.variable = null;
7436 this.bound = false;
7437 this.expressionsToBeDeoptimized = [];
7438 this.replacement = null;
7439 }
7440 addExportedVariables() { }
7441 bind() {
7442 if (this.bound)
7443 return;
7444 this.bound = true;
7445 const path = getPathIfNotComputed(this);
7446 const baseVariable = path && this.scope.findVariable(path[0].key);
7447 if (baseVariable && baseVariable.isNamespace) {
7448 const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
7449 if (!resolvedVariable) {
7450 super.bind();
7451 }
7452 else if (typeof resolvedVariable === 'string') {
7453 this.replacement = resolvedVariable;
7454 }
7455 else {
7456 if (resolvedVariable instanceof ExternalVariable && resolvedVariable.module) {
7457 resolvedVariable.module.suggestName(path[0].key);
7458 }
7459 this.variable = resolvedVariable;
7460 this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
7461 }
7462 }
7463 else {
7464 super.bind();
7465 if (this.propertyKey === null)
7466 this.analysePropertyKey();
7467 }
7468 }
7469 deoptimizeCache() {
7470 for (const expression of this.expressionsToBeDeoptimized) {
7471 expression.deoptimizeCache();
7472 }
7473 }
7474 deoptimizePath(path) {
7475 if (!this.bound)
7476 this.bind();
7477 if (path.length === 0)
7478 this.disallowNamespaceReassignment();
7479 if (this.variable) {
7480 this.variable.deoptimizePath(path);
7481 }
7482 else {
7483 if (this.propertyKey === null)
7484 this.analysePropertyKey();
7485 this.object.deoptimizePath([this.propertyKey, ...path]);
7486 }
7487 }
7488 getLiteralValueAtPath(path, recursionTracker, origin) {
7489 if (!this.bound)
7490 this.bind();
7491 if (this.variable !== null) {
7492 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
7493 }
7494 if (this.propertyKey === null)
7495 this.analysePropertyKey();
7496 this.expressionsToBeDeoptimized.push(origin);
7497 return this.object.getLiteralValueAtPath([this.propertyKey, ...path], recursionTracker, origin);
7498 }
7499 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
7500 if (!this.bound)
7501 this.bind();
7502 if (this.variable !== null) {
7503 return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
7504 }
7505 if (this.propertyKey === null)
7506 this.analysePropertyKey();
7507 this.expressionsToBeDeoptimized.push(origin);
7508 return this.object.getReturnExpressionWhenCalledAtPath([this.propertyKey, ...path], recursionTracker, origin);
7509 }
7510 hasEffects(context) {
7511 return (this.property.hasEffects(context) ||
7512 this.object.hasEffects(context) ||
7513 (this.context.propertyReadSideEffects &&
7514 this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], context)));
7515 }
7516 hasEffectsWhenAccessedAtPath(path, context) {
7517 if (path.length === 0)
7518 return false;
7519 if (this.variable !== null) {
7520 return this.variable.hasEffectsWhenAccessedAtPath(path, context);
7521 }
7522 return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey, ...path], context);
7523 }
7524 hasEffectsWhenAssignedAtPath(path, context) {
7525 if (this.variable !== null) {
7526 return this.variable.hasEffectsWhenAssignedAtPath(path, context);
7527 }
7528 return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey, ...path], context);
7529 }
7530 hasEffectsWhenCalledAtPath(path, callOptions, context) {
7531 if (this.variable !== null) {
7532 return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
7533 }
7534 return this.object.hasEffectsWhenCalledAtPath([this.propertyKey, ...path], callOptions, context);
7535 }
7536 include(context, includeChildrenRecursively) {
7537 if (!this.included) {
7538 this.included = true;
7539 if (this.variable !== null) {
7540 this.context.includeVariable(context, this.variable);
7541 }
7542 }
7543 this.object.include(context, includeChildrenRecursively);
7544 this.property.include(context, includeChildrenRecursively);
7545 }
7546 includeCallArguments(context, args) {
7547 if (this.variable) {
7548 this.variable.includeCallArguments(context, args);
7549 }
7550 else {
7551 super.includeCallArguments(context, args);
7552 }
7553 }
7554 initialise() {
7555 this.propertyKey = getResolvablePropertyKey(this);
7556 }
7557 render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) {
7558 const isCalleeOfDifferentParent = renderedParentType === CallExpression && isCalleeOfRenderedParent;
7559 if (this.variable || this.replacement) {
7560 let replacement = this.variable ? this.variable.getName() : this.replacement;
7561 if (isCalleeOfDifferentParent)
7562 replacement = '0, ' + replacement;
7563 code.overwrite(this.start, this.end, replacement, {
7564 contentOnly: true,
7565 storeName: true
7566 });
7567 }
7568 else {
7569 if (isCalleeOfDifferentParent) {
7570 code.appendRight(this.start, '0, ');
7571 }
7572 super.render(code, options);
7573 }
7574 }
7575 analysePropertyKey() {
7576 this.propertyKey = UnknownKey;
7577 const value = this.property.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
7578 this.propertyKey = value === UnknownValue ? UnknownKey : String(value);
7579 }
7580 disallowNamespaceReassignment() {
7581 if (this.object instanceof Identifier$1 &&
7582 this.scope.findVariable(this.object.name).isNamespace) {
7583 this.context.error({
7584 code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
7585 message: `Illegal reassignment to import '${this.object.name}'`
7586 }, this.start);
7587 }
7588 }
7589 resolveNamespaceVariables(baseVariable, path) {
7590 if (path.length === 0)
7591 return baseVariable;
7592 if (!baseVariable.isNamespace)
7593 return null;
7594 const exportName = path[0].key;
7595 const variable = baseVariable instanceof ExternalVariable
7596 ? baseVariable.module.getVariableForExportName(exportName)
7597 : baseVariable.context.traceExport(exportName);
7598 if (!variable) {
7599 const fileName = baseVariable instanceof ExternalVariable
7600 ? baseVariable.module.id
7601 : baseVariable.context.fileName;
7602 this.context.warn({
7603 code: 'MISSING_EXPORT',
7604 exporter: relativeId(fileName),
7605 importer: relativeId(this.context.fileName),
7606 message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
7607 missing: exportName,
7608 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
7609 }, path[0].pos);
7610 return 'undefined';
7611 }
7612 return this.resolveNamespaceVariables(variable, path.slice(1));
7613 }
7614}
7615
7616const readFile = (file) => new Promise((fulfil, reject) => readFile$1(file, 'utf-8', (err, contents) => (err ? reject(err) : fulfil(contents))));
7617function mkdirpath(path) {
7618 const dir = dirname(path);
7619 try {
7620 readdirSync(dir);
7621 }
7622 catch (err) {
7623 mkdirpath(dir);
7624 try {
7625 mkdirSync(dir);
7626 }
7627 catch (err2) {
7628 if (err2.code !== 'EEXIST') {
7629 throw err2;
7630 }
7631 }
7632 }
7633}
7634function writeFile(dest, data) {
7635 return new Promise((fulfil, reject) => {
7636 mkdirpath(dest);
7637 writeFile$1(dest, data, err => {
7638 if (err) {
7639 reject(err);
7640 }
7641 else {
7642 fulfil();
7643 }
7644 });
7645 });
7646}
7647
7648function getRollupDefaultPlugin(preserveSymlinks) {
7649 return {
7650 name: 'Rollup Core',
7651 resolveId: createResolveId(preserveSymlinks),
7652 load(id) {
7653 return readFile(id);
7654 },
7655 resolveFileUrl({ relativePath, format }) {
7656 return relativeUrlMechanisms[format](relativePath);
7657 },
7658 resolveImportMeta(prop, { chunkId, format }) {
7659 const mechanism = importMetaMechanisms[format] && importMetaMechanisms[format](prop, chunkId);
7660 if (mechanism) {
7661 return mechanism;
7662 }
7663 }
7664 };
7665}
7666function findFile(file, preserveSymlinks) {
7667 try {
7668 const stats = lstatSync(file);
7669 if (!preserveSymlinks && stats.isSymbolicLink())
7670 return findFile(realpathSync(file), preserveSymlinks);
7671 if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
7672 // check case
7673 const name = basename(file);
7674 const files = readdirSync(dirname(file));
7675 if (files.indexOf(name) !== -1)
7676 return file;
7677 }
7678 }
7679 catch (err) {
7680 // suppress
7681 }
7682}
7683function addJsExtensionIfNecessary(file, preserveSymlinks) {
7684 let found = findFile(file, preserveSymlinks);
7685 if (found)
7686 return found;
7687 found = findFile(file + '.mjs', preserveSymlinks);
7688 if (found)
7689 return found;
7690 found = findFile(file + '.js', preserveSymlinks);
7691 return found;
7692}
7693function createResolveId(preserveSymlinks) {
7694 return function (source, importer) {
7695 if (typeof process === 'undefined') {
7696 error({
7697 code: 'MISSING_PROCESS',
7698 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`,
7699 url: 'https://rollupjs.org/guide/en/#a-simple-example'
7700 });
7701 }
7702 // external modules (non-entry modules that start with neither '.' or '/')
7703 // are skipped at this stage.
7704 if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
7705 return null;
7706 // `resolve` processes paths from right to left, prepending them until an
7707 // absolute path is created. Absolute importees therefore shortcircuit the
7708 // resolve call and require no special handing on our part.
7709 // See https://nodejs.org/api/path.html#path_path_resolve_paths
7710 return addJsExtensionIfNecessary(resolve(importer ? dirname(importer) : resolve(), source), preserveSymlinks);
7711 };
7712}
7713const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
7714const getUrlFromDocument = (chunkId) => `(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
7715const getGenericImportMetaMechanism = (getUrl) => (prop, chunkId) => {
7716 const urlMechanism = getUrl(chunkId);
7717 return prop === null ? `({ url: ${urlMechanism} })` : prop === 'url' ? urlMechanism : 'undefined';
7718};
7719const importMetaMechanisms = {
7720 amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
7721 cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
7722 iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
7723 system: prop => (prop === null ? `module.meta` : `module.meta.${prop}`),
7724 umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`)
7725};
7726const getRelativeUrlFromDocument = (relativePath) => getResolveUrl(`'${relativePath}', document.currentScript && document.currentScript.src || document.baseURI`);
7727const relativeUrlMechanisms = {
7728 amd: relativePath => {
7729 if (relativePath[0] !== '.')
7730 relativePath = './' + relativePath;
7731 return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
7732 },
7733 cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
7734 es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
7735 iife: relativePath => getRelativeUrlFromDocument(relativePath),
7736 system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
7737 umd: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`
7738};
7739const accessedMetaUrlGlobals = {
7740 amd: ['document', 'module', 'URL'],
7741 cjs: ['document', 'require', 'URL'],
7742 iife: ['document', 'URL'],
7743 system: ['module'],
7744 umd: ['document', 'require', 'URL']
7745};
7746const accessedFileUrlGlobals = {
7747 amd: ['document', 'require', 'URL'],
7748 cjs: ['document', 'require', 'URL'],
7749 iife: ['document', 'URL'],
7750 system: ['module', 'URL'],
7751 umd: ['document', 'require', 'URL']
7752};
7753
7754const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
7755const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
7756const FILE_PREFIX = 'ROLLUP_FILE_URL_';
7757class MetaProperty extends NodeBase {
7758 hasEffects() {
7759 return false;
7760 }
7761 hasEffectsWhenAccessedAtPath(path) {
7762 return path.length > 1;
7763 }
7764 include() {
7765 if (!this.included) {
7766 this.included = true;
7767 const parent = this.parent;
7768 const metaProperty = (this.metaProperty =
7769 parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
7770 ? parent.propertyKey
7771 : null);
7772 if (metaProperty) {
7773 if (metaProperty.startsWith(FILE_PREFIX) ||
7774 metaProperty.startsWith(ASSET_PREFIX) ||
7775 metaProperty.startsWith(CHUNK_PREFIX)) {
7776 this.scope.addAccessedGlobalsByFormat(accessedFileUrlGlobals);
7777 }
7778 else {
7779 this.scope.addAccessedGlobalsByFormat(accessedMetaUrlGlobals);
7780 }
7781 }
7782 }
7783 }
7784 initialise() {
7785 if (this.meta.name === 'import') {
7786 this.context.addImportMeta(this);
7787 }
7788 }
7789 renderFinalMechanism(code, chunkId, format, pluginDriver) {
7790 if (!this.included)
7791 return;
7792 const parent = this.parent;
7793 const metaProperty = this.metaProperty;
7794 if (metaProperty &&
7795 (metaProperty.startsWith(FILE_PREFIX) ||
7796 metaProperty.startsWith(ASSET_PREFIX) ||
7797 metaProperty.startsWith(CHUNK_PREFIX))) {
7798 let referenceId = null;
7799 let assetReferenceId = null;
7800 let chunkReferenceId = null;
7801 let fileName;
7802 if (metaProperty.startsWith(FILE_PREFIX)) {
7803 referenceId = metaProperty.substr(FILE_PREFIX.length);
7804 fileName = this.context.getFileName(referenceId);
7805 }
7806 else if (metaProperty.startsWith(ASSET_PREFIX)) {
7807 this.context.warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, false);
7808 assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
7809 fileName = this.context.getFileName(assetReferenceId);
7810 }
7811 else {
7812 this.context.warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, false);
7813 chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
7814 fileName = this.context.getFileName(chunkReferenceId);
7815 }
7816 const relativePath = normalize(relative$1(dirname(chunkId), fileName));
7817 let replacement;
7818 if (assetReferenceId !== null) {
7819 replacement = pluginDriver.hookFirstSync('resolveAssetUrl', [
7820 {
7821 assetFileName: fileName,
7822 chunkId,
7823 format,
7824 moduleId: this.context.module.id,
7825 relativeAssetPath: relativePath
7826 }
7827 ]);
7828 }
7829 if (!replacement) {
7830 replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
7831 {
7832 assetReferenceId,
7833 chunkId,
7834 chunkReferenceId,
7835 fileName,
7836 format,
7837 moduleId: this.context.module.id,
7838 referenceId: referenceId || assetReferenceId || chunkReferenceId,
7839 relativePath
7840 }
7841 ]);
7842 }
7843 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
7844 return;
7845 }
7846 const replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
7847 metaProperty,
7848 {
7849 chunkId,
7850 format,
7851 moduleId: this.context.module.id
7852 }
7853 ]);
7854 if (typeof replacement === 'string') {
7855 if (parent instanceof MemberExpression) {
7856 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
7857 }
7858 else {
7859 code.overwrite(this.start, this.end, replacement, { contentOnly: true });
7860 }
7861 }
7862 }
7863}
7864
7865class MethodDefinition extends NodeBase {
7866 hasEffects(context) {
7867 return this.key.hasEffects(context);
7868 }
7869 hasEffectsWhenCalledAtPath(path, callOptions, context) {
7870 return (path.length > 0 || this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
7871 }
7872}
7873
7874class NewExpression extends NodeBase {
7875 bind() {
7876 super.bind();
7877 for (const argument of this.arguments) {
7878 // This will make sure all properties of parameters behave as "unknown"
7879 argument.deoptimizePath(UNKNOWN_PATH);
7880 }
7881 }
7882 hasEffects(context) {
7883 for (const argument of this.arguments) {
7884 if (argument.hasEffects(context))
7885 return true;
7886 }
7887 if (this.context.annotations && this.annotatedPure)
7888 return false;
7889 return (this.callee.hasEffects(context) ||
7890 this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
7891 }
7892 hasEffectsWhenAccessedAtPath(path) {
7893 return path.length > 1;
7894 }
7895 initialise() {
7896 this.callOptions = {
7897 args: this.arguments,
7898 withNew: true
7899 };
7900 }
7901}
7902
7903class SpreadElement extends NodeBase {
7904 bind() {
7905 super.bind();
7906 // Only properties of properties of the argument could become subject to reassignment
7907 // This will also reassign the return values of iterators
7908 this.argument.deoptimizePath([UnknownKey, UnknownKey]);
7909 }
7910}
7911
7912class ObjectExpression extends NodeBase {
7913 constructor() {
7914 super(...arguments);
7915 this.deoptimizedPaths = new Set();
7916 // We collect deoptimization information if we can resolve a computed property access
7917 this.expressionsToBeDeoptimized = new Map();
7918 this.hasUnknownDeoptimizedProperty = false;
7919 this.propertyMap = null;
7920 this.unmatchablePropertiesRead = [];
7921 this.unmatchablePropertiesWrite = [];
7922 }
7923 bind() {
7924 super.bind();
7925 if (this.propertyMap === null)
7926 this.buildPropertyMap();
7927 }
7928 // We could also track this per-property but this would quickly become much more complex
7929 deoptimizeCache() {
7930 if (!this.hasUnknownDeoptimizedProperty)
7931 this.deoptimizeAllProperties();
7932 }
7933 deoptimizePath(path) {
7934 if (this.hasUnknownDeoptimizedProperty)
7935 return;
7936 if (this.propertyMap === null)
7937 this.buildPropertyMap();
7938 if (path.length === 0) {
7939 this.deoptimizeAllProperties();
7940 return;
7941 }
7942 const key = path[0];
7943 if (path.length === 1) {
7944 if (typeof key !== 'string') {
7945 this.deoptimizeAllProperties();
7946 return;
7947 }
7948 if (!this.deoptimizedPaths.has(key)) {
7949 this.deoptimizedPaths.add(key);
7950 // we only deoptimizeCache exact matches as in all other cases,
7951 // we do not return a literal value or return expression
7952 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
7953 if (expressionsToBeDeoptimized) {
7954 for (const expression of expressionsToBeDeoptimized) {
7955 expression.deoptimizeCache();
7956 }
7957 }
7958 }
7959 }
7960 const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
7961 for (const property of typeof key === 'string'
7962 ? this.propertyMap[key]
7963 ? this.propertyMap[key].propertiesRead
7964 : []
7965 : this.properties) {
7966 property.deoptimizePath(subPath);
7967 }
7968 }
7969 getLiteralValueAtPath(path, recursionTracker, origin) {
7970 if (this.propertyMap === null)
7971 this.buildPropertyMap();
7972 const key = path[0];
7973 if (path.length === 0 ||
7974 this.hasUnknownDeoptimizedProperty ||
7975 typeof key !== 'string' ||
7976 this.deoptimizedPaths.has(key))
7977 return UnknownValue;
7978 if (path.length === 1 &&
7979 !this.propertyMap[key] &&
7980 !objectMembers[key] &&
7981 this.unmatchablePropertiesRead.length === 0) {
7982 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
7983 if (expressionsToBeDeoptimized) {
7984 expressionsToBeDeoptimized.push(origin);
7985 }
7986 else {
7987 this.expressionsToBeDeoptimized.set(key, [origin]);
7988 }
7989 return undefined;
7990 }
7991 if (!this.propertyMap[key] ||
7992 this.propertyMap[key].exactMatchRead === null ||
7993 this.propertyMap[key].propertiesRead.length > 1) {
7994 return UnknownValue;
7995 }
7996 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
7997 if (expressionsToBeDeoptimized) {
7998 expressionsToBeDeoptimized.push(origin);
7999 }
8000 else {
8001 this.expressionsToBeDeoptimized.set(key, [origin]);
8002 }
8003 return this.propertyMap[key]
8004 .exactMatchRead.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
8005 }
8006 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
8007 if (this.propertyMap === null)
8008 this.buildPropertyMap();
8009 const key = path[0];
8010 if (path.length === 0 ||
8011 this.hasUnknownDeoptimizedProperty ||
8012 typeof key !== 'string' ||
8013 this.deoptimizedPaths.has(key))
8014 return UNKNOWN_EXPRESSION;
8015 if (path.length === 1 &&
8016 objectMembers[key] &&
8017 this.unmatchablePropertiesRead.length === 0 &&
8018 (!this.propertyMap[key] ||
8019 this.propertyMap[key].exactMatchRead === null))
8020 return getMemberReturnExpressionWhenCalled(objectMembers, key);
8021 if (!this.propertyMap[key] ||
8022 this.propertyMap[key].exactMatchRead === null ||
8023 this.propertyMap[key].propertiesRead.length > 1)
8024 return UNKNOWN_EXPRESSION;
8025 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
8026 if (expressionsToBeDeoptimized) {
8027 expressionsToBeDeoptimized.push(origin);
8028 }
8029 else {
8030 this.expressionsToBeDeoptimized.set(key, [origin]);
8031 }
8032 return this.propertyMap[key]
8033 .exactMatchRead.getReturnExpressionWhenCalledAtPath(path.slice(1), recursionTracker, origin);
8034 }
8035 hasEffectsWhenAccessedAtPath(path, context) {
8036 if (path.length === 0)
8037 return false;
8038 const key = path[0];
8039 if (path.length > 1 &&
8040 (this.hasUnknownDeoptimizedProperty ||
8041 typeof key !== 'string' ||
8042 this.deoptimizedPaths.has(key) ||
8043 !this.propertyMap[key] ||
8044 this.propertyMap[key].exactMatchRead === null))
8045 return true;
8046 const subPath = path.slice(1);
8047 for (const property of typeof key !== 'string'
8048 ? this.properties
8049 : this.propertyMap[key]
8050 ? this.propertyMap[key].propertiesRead
8051 : []) {
8052 if (property.hasEffectsWhenAccessedAtPath(subPath, context))
8053 return true;
8054 }
8055 return false;
8056 }
8057 hasEffectsWhenAssignedAtPath(path, context) {
8058 if (path.length === 0)
8059 return false;
8060 const key = path[0];
8061 if (path.length > 1 &&
8062 (this.hasUnknownDeoptimizedProperty ||
8063 typeof key !== 'string' ||
8064 this.deoptimizedPaths.has(key) ||
8065 !this.propertyMap[key] ||
8066 this.propertyMap[key].exactMatchRead === null))
8067 return true;
8068 const subPath = path.slice(1);
8069 for (const property of typeof key !== 'string'
8070 ? this.properties
8071 : path.length > 1
8072 ? this.propertyMap[key].propertiesRead
8073 : this.propertyMap[key]
8074 ? this.propertyMap[key].propertiesSet
8075 : []) {
8076 if (property.hasEffectsWhenAssignedAtPath(subPath, context))
8077 return true;
8078 }
8079 return false;
8080 }
8081 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8082 const key = path[0];
8083 if (path.length === 0 ||
8084 this.hasUnknownDeoptimizedProperty ||
8085 typeof key !== 'string' ||
8086 this.deoptimizedPaths.has(key) ||
8087 (this.propertyMap[key]
8088 ? !this.propertyMap[key].exactMatchRead
8089 : path.length > 1 || !objectMembers[key]))
8090 return true;
8091 const subPath = path.slice(1);
8092 for (const property of this.propertyMap[key]
8093 ? this.propertyMap[key].propertiesRead
8094 : []) {
8095 if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, context))
8096 return true;
8097 }
8098 if (path.length === 1 && objectMembers[key])
8099 return hasMemberEffectWhenCalled(objectMembers, key, this.included, callOptions, context);
8100 return false;
8101 }
8102 render(code, options, { renderedParentType } = BLANK) {
8103 super.render(code, options);
8104 if (renderedParentType === ExpressionStatement) {
8105 code.appendRight(this.start, '(');
8106 code.prependLeft(this.end, ')');
8107 }
8108 }
8109 buildPropertyMap() {
8110 this.propertyMap = Object.create(null);
8111 for (let index = this.properties.length - 1; index >= 0; index--) {
8112 const property = this.properties[index];
8113 if (property instanceof SpreadElement) {
8114 this.unmatchablePropertiesRead.push(property);
8115 continue;
8116 }
8117 const isWrite = property.kind !== 'get';
8118 const isRead = property.kind !== 'set';
8119 let key;
8120 if (property.computed) {
8121 const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
8122 if (keyValue === UnknownValue) {
8123 if (isRead) {
8124 this.unmatchablePropertiesRead.push(property);
8125 }
8126 else {
8127 this.unmatchablePropertiesWrite.push(property);
8128 }
8129 continue;
8130 }
8131 key = String(keyValue);
8132 }
8133 else if (property.key instanceof Identifier$1) {
8134 key = property.key.name;
8135 }
8136 else {
8137 key = String(property.key.value);
8138 }
8139 const propertyMapProperty = this.propertyMap[key];
8140 if (!propertyMapProperty) {
8141 this.propertyMap[key] = {
8142 exactMatchRead: isRead ? property : null,
8143 exactMatchWrite: isWrite ? property : null,
8144 propertiesRead: isRead ? [property, ...this.unmatchablePropertiesRead] : [],
8145 propertiesSet: isWrite && !isRead ? [property, ...this.unmatchablePropertiesWrite] : []
8146 };
8147 continue;
8148 }
8149 if (isRead && propertyMapProperty.exactMatchRead === null) {
8150 propertyMapProperty.exactMatchRead = property;
8151 propertyMapProperty.propertiesRead.push(property, ...this.unmatchablePropertiesRead);
8152 }
8153 if (isWrite && !isRead && propertyMapProperty.exactMatchWrite === null) {
8154 propertyMapProperty.exactMatchWrite = property;
8155 propertyMapProperty.propertiesSet.push(property, ...this.unmatchablePropertiesWrite);
8156 }
8157 }
8158 }
8159 deoptimizeAllProperties() {
8160 this.hasUnknownDeoptimizedProperty = true;
8161 for (const property of this.properties) {
8162 property.deoptimizePath(UNKNOWN_PATH);
8163 }
8164 for (const expressionsToBeDeoptimized of this.expressionsToBeDeoptimized.values()) {
8165 for (const expression of expressionsToBeDeoptimized) {
8166 expression.deoptimizeCache();
8167 }
8168 }
8169 }
8170}
8171
8172class ObjectPattern extends NodeBase {
8173 addExportedVariables(variables) {
8174 for (const property of this.properties) {
8175 if (property.type === Property) {
8176 property.value.addExportedVariables(variables);
8177 }
8178 else {
8179 property.argument.addExportedVariables(variables);
8180 }
8181 }
8182 }
8183 declare(kind, init) {
8184 const variables = [];
8185 for (const property of this.properties) {
8186 variables.push(...property.declare(kind, init));
8187 }
8188 return variables;
8189 }
8190 deoptimizePath(path) {
8191 if (path.length === 0) {
8192 for (const property of this.properties) {
8193 property.deoptimizePath(path);
8194 }
8195 }
8196 }
8197 hasEffectsWhenAssignedAtPath(path, context) {
8198 if (path.length > 0)
8199 return true;
8200 for (const property of this.properties) {
8201 if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
8202 return true;
8203 }
8204 return false;
8205 }
8206}
8207
8208class Program$1 extends NodeBase {
8209 hasEffects(context) {
8210 for (const node of this.body) {
8211 if (node.hasEffects(context))
8212 return true;
8213 }
8214 return false;
8215 }
8216 include(context, includeChildrenRecursively) {
8217 this.included = true;
8218 for (const node of this.body) {
8219 if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
8220 node.include(context, includeChildrenRecursively);
8221 }
8222 }
8223 }
8224 render(code, options) {
8225 if (this.body.length) {
8226 renderStatementList(this.body, code, this.start, this.end, options);
8227 }
8228 else {
8229 super.render(code, options);
8230 }
8231 }
8232}
8233
8234class Property$1 extends NodeBase {
8235 constructor() {
8236 super(...arguments);
8237 this.declarationInit = null;
8238 this.returnExpression = null;
8239 }
8240 bind() {
8241 super.bind();
8242 if (this.kind === 'get' && this.returnExpression === null)
8243 this.updateReturnExpression();
8244 if (this.declarationInit !== null) {
8245 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
8246 }
8247 }
8248 declare(kind, init) {
8249 this.declarationInit = init;
8250 return this.value.declare(kind, UNKNOWN_EXPRESSION);
8251 }
8252 deoptimizeCache() {
8253 // As getter properties directly receive their values from function expressions that always
8254 // have a fixed return value, there is no known situation where a getter is deoptimized.
8255 throw new Error('Unexpected deoptimization');
8256 }
8257 deoptimizePath(path) {
8258 if (this.kind === 'get') {
8259 if (path.length > 0) {
8260 if (this.returnExpression === null)
8261 this.updateReturnExpression();
8262 this.returnExpression.deoptimizePath(path);
8263 }
8264 }
8265 else if (this.kind !== 'set') {
8266 this.value.deoptimizePath(path);
8267 }
8268 }
8269 getLiteralValueAtPath(path, recursionTracker, origin) {
8270 if (this.kind === 'get') {
8271 if (this.returnExpression === null)
8272 this.updateReturnExpression();
8273 return this.returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
8274 }
8275 return this.value.getLiteralValueAtPath(path, recursionTracker, origin);
8276 }
8277 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
8278 if (this.kind === 'get') {
8279 if (this.returnExpression === null)
8280 this.updateReturnExpression();
8281 return this.returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
8282 }
8283 return this.value.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
8284 }
8285 hasEffects(context) {
8286 return this.key.hasEffects(context) || this.value.hasEffects(context);
8287 }
8288 hasEffectsWhenAccessedAtPath(path, context) {
8289 if (this.kind === 'get') {
8290 const trackedExpressions = context.accessed.getEntities(path);
8291 if (trackedExpressions.has(this))
8292 return false;
8293 trackedExpressions.add(this);
8294 return (this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context) ||
8295 (path.length > 0 &&
8296 this.returnExpression.hasEffectsWhenAccessedAtPath(path, context)));
8297 }
8298 return this.value.hasEffectsWhenAccessedAtPath(path, context);
8299 }
8300 hasEffectsWhenAssignedAtPath(path, context) {
8301 if (this.kind === 'get') {
8302 const trackedExpressions = context.assigned.getEntities(path);
8303 if (trackedExpressions.has(this))
8304 return false;
8305 trackedExpressions.add(this);
8306 return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
8307 }
8308 if (this.kind === 'set') {
8309 const trackedExpressions = context.assigned.getEntities(path);
8310 if (trackedExpressions.has(this))
8311 return false;
8312 trackedExpressions.add(this);
8313 return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context);
8314 }
8315 return this.value.hasEffectsWhenAssignedAtPath(path, context);
8316 }
8317 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8318 if (this.kind === 'get') {
8319 const trackedExpressions = (callOptions.withNew
8320 ? context.instantiated
8321 : context.called).getEntities(path);
8322 if (trackedExpressions.has(this))
8323 return false;
8324 trackedExpressions.add(this);
8325 return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
8326 }
8327 return this.value.hasEffectsWhenCalledAtPath(path, callOptions, context);
8328 }
8329 initialise() {
8330 this.accessorCallOptions = {
8331 args: NO_ARGS,
8332 withNew: false
8333 };
8334 }
8335 render(code, options) {
8336 if (!this.shorthand) {
8337 this.key.render(code, options);
8338 }
8339 this.value.render(code, options, { isShorthandProperty: this.shorthand });
8340 }
8341 updateReturnExpression() {
8342 this.returnExpression = UNKNOWN_EXPRESSION;
8343 this.returnExpression = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
8344 }
8345}
8346
8347class ReturnStatement$1 extends NodeBase {
8348 hasEffects(context) {
8349 if (!context.ignore.returnAwaitYield ||
8350 (this.argument !== null && this.argument.hasEffects(context)))
8351 return true;
8352 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8353 return false;
8354 }
8355 include(context, includeChildrenRecursively) {
8356 this.included = true;
8357 if (this.argument) {
8358 this.argument.include(context, includeChildrenRecursively);
8359 }
8360 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8361 }
8362 initialise() {
8363 this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
8364 }
8365 render(code, options) {
8366 if (this.argument) {
8367 this.argument.render(code, options, { preventASI: true });
8368 if (this.argument.start === this.start + 6 /* 'return'.length */) {
8369 code.prependLeft(this.start + 6, ' ');
8370 }
8371 }
8372 }
8373}
8374
8375class SequenceExpression extends NodeBase {
8376 deoptimizePath(path) {
8377 if (path.length > 0)
8378 this.expressions[this.expressions.length - 1].deoptimizePath(path);
8379 }
8380 getLiteralValueAtPath(path, recursionTracker, origin) {
8381 return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
8382 }
8383 hasEffects(context) {
8384 for (const expression of this.expressions) {
8385 if (expression.hasEffects(context))
8386 return true;
8387 }
8388 return false;
8389 }
8390 hasEffectsWhenAccessedAtPath(path, context) {
8391 return (path.length > 0 &&
8392 this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, context));
8393 }
8394 hasEffectsWhenAssignedAtPath(path, context) {
8395 return (path.length === 0 ||
8396 this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, context));
8397 }
8398 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8399 return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, context);
8400 }
8401 include(context, includeChildrenRecursively) {
8402 this.included = true;
8403 for (let i = 0; i < this.expressions.length - 1; i++) {
8404 const node = this.expressions[i];
8405 if (includeChildrenRecursively || node.shouldBeIncluded(context))
8406 node.include(context, includeChildrenRecursively);
8407 }
8408 this.expressions[this.expressions.length - 1].include(context, includeChildrenRecursively);
8409 }
8410 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
8411 let includedNodes = 0;
8412 for (const { node, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
8413 if (!node.included) {
8414 treeshakeNode(node, code, start, end);
8415 continue;
8416 }
8417 includedNodes++;
8418 if (includedNodes === 1 && preventASI) {
8419 removeLineBreaks(code, start, node.start);
8420 }
8421 if (node === this.expressions[this.expressions.length - 1] && includedNodes === 1) {
8422 node.render(code, options, {
8423 isCalleeOfRenderedParent: renderedParentType
8424 ? isCalleeOfRenderedParent
8425 : this.parent.callee === this,
8426 renderedParentType: renderedParentType || this.parent.type
8427 });
8428 }
8429 else {
8430 node.render(code, options);
8431 }
8432 }
8433 }
8434}
8435
8436class SwitchCase extends NodeBase {
8437 hasEffects(context) {
8438 if (this.test && this.test.hasEffects(context))
8439 return true;
8440 for (const node of this.consequent) {
8441 if (context.brokenFlow)
8442 break;
8443 if (node.hasEffects(context))
8444 return true;
8445 }
8446 return false;
8447 }
8448 include(context, includeChildrenRecursively) {
8449 this.included = true;
8450 if (this.test)
8451 this.test.include(context, includeChildrenRecursively);
8452 for (const node of this.consequent) {
8453 if (includeChildrenRecursively || node.shouldBeIncluded(context))
8454 node.include(context, includeChildrenRecursively);
8455 }
8456 }
8457 render(code, options, nodeRenderOptions) {
8458 if (this.consequent.length) {
8459 this.test && this.test.render(code, options);
8460 const testEnd = this.test
8461 ? this.test.end
8462 : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
8463 const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
8464 renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
8465 }
8466 else {
8467 super.render(code, options);
8468 }
8469 }
8470}
8471SwitchCase.prototype.needsBoundaries = true;
8472
8473class SwitchStatement extends NodeBase {
8474 createScope(parentScope) {
8475 this.scope = new BlockScope(parentScope);
8476 }
8477 hasEffects(context) {
8478 if (this.discriminant.hasEffects(context))
8479 return true;
8480 const { brokenFlow, ignore: { breaks } } = context;
8481 let minBrokenFlow = Infinity;
8482 context.ignore.breaks = true;
8483 for (const switchCase of this.cases) {
8484 if (switchCase.hasEffects(context))
8485 return true;
8486 minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
8487 context.brokenFlow = brokenFlow;
8488 }
8489 if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
8490 context.brokenFlow = minBrokenFlow;
8491 }
8492 context.ignore.breaks = breaks;
8493 return false;
8494 }
8495 include(context, includeChildrenRecursively) {
8496 this.included = true;
8497 this.discriminant.include(context, includeChildrenRecursively);
8498 const { brokenFlow } = context;
8499 let minBrokenFlow = Infinity;
8500 let isCaseIncluded = includeChildrenRecursively ||
8501 (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
8502 for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
8503 const switchCase = this.cases[caseIndex];
8504 if (switchCase.included) {
8505 isCaseIncluded = true;
8506 }
8507 if (!isCaseIncluded) {
8508 const hasEffectsContext = createHasEffectsContext();
8509 hasEffectsContext.ignore.breaks = true;
8510 isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
8511 }
8512 if (isCaseIncluded) {
8513 switchCase.include(context, includeChildrenRecursively);
8514 minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
8515 context.brokenFlow = brokenFlow;
8516 }
8517 }
8518 if (isCaseIncluded &&
8519 this.defaultCase !== null &&
8520 !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
8521 context.brokenFlow = minBrokenFlow;
8522 }
8523 }
8524 initialise() {
8525 for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
8526 if (this.cases[caseIndex].test === null) {
8527 this.defaultCase = caseIndex;
8528 return;
8529 }
8530 }
8531 this.defaultCase = null;
8532 }
8533 render(code, options) {
8534 this.discriminant.render(code, options);
8535 if (this.cases.length > 0) {
8536 renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
8537 }
8538 }
8539}
8540
8541class TaggedTemplateExpression extends NodeBase {
8542 bind() {
8543 super.bind();
8544 if (this.tag.type === Identifier) {
8545 const variable = this.scope.findVariable(this.tag.name);
8546 if (variable.isNamespace) {
8547 this.context.error({
8548 code: 'CANNOT_CALL_NAMESPACE',
8549 message: `Cannot call a namespace ('${this.tag.name}')`
8550 }, this.start);
8551 }
8552 if (this.tag.name === 'eval') {
8553 this.context.warn({
8554 code: 'EVAL',
8555 message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
8556 url: 'https://rollupjs.org/guide/en/#avoiding-eval'
8557 }, this.start);
8558 }
8559 }
8560 }
8561 hasEffects(context) {
8562 return (super.hasEffects(context) ||
8563 this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
8564 }
8565 initialise() {
8566 this.callOptions = {
8567 args: NO_ARGS,
8568 withNew: false
8569 };
8570 }
8571}
8572
8573class TemplateElement extends NodeBase {
8574 hasEffects() {
8575 return false;
8576 }
8577}
8578
8579class TemplateLiteral extends NodeBase {
8580 getLiteralValueAtPath(path) {
8581 if (path.length > 0 || this.quasis.length !== 1) {
8582 return UnknownValue;
8583 }
8584 return this.quasis[0].value.cooked;
8585 }
8586 render(code, options) {
8587 code.indentExclusionRanges.push([this.start, this.end]);
8588 super.render(code, options);
8589 }
8590}
8591
8592class ModuleScope extends ChildScope {
8593 constructor(parent, context) {
8594 super(parent);
8595 this.context = context;
8596 this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
8597 }
8598 addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
8599 const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
8600 this.variables.set('default', variable);
8601 return variable;
8602 }
8603 addNamespaceMemberAccess(_name, variable) {
8604 if (variable instanceof GlobalVariable) {
8605 this.accessedOutsideVariables.set(variable.name, variable);
8606 }
8607 }
8608 deconflict(format) {
8609 // all module level variables are already deconflicted when deconflicting the chunk
8610 for (const scope of this.children)
8611 scope.deconflict(format);
8612 }
8613 findLexicalBoundary() {
8614 return this;
8615 }
8616 findVariable(name) {
8617 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
8618 if (knownVariable) {
8619 return knownVariable;
8620 }
8621 const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
8622 if (variable instanceof GlobalVariable) {
8623 this.accessedOutsideVariables.set(name, variable);
8624 }
8625 return variable;
8626 }
8627}
8628
8629class ThisExpression extends NodeBase {
8630 bind() {
8631 super.bind();
8632 this.variable = this.scope.findVariable('this');
8633 }
8634 hasEffectsWhenAccessedAtPath(path, context) {
8635 return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, context);
8636 }
8637 hasEffectsWhenAssignedAtPath(path, context) {
8638 return this.variable.hasEffectsWhenAssignedAtPath(path, context);
8639 }
8640 initialise() {
8641 this.alias =
8642 this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
8643 if (this.alias === 'undefined') {
8644 this.context.warn({
8645 code: 'THIS_IS_UNDEFINED',
8646 message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
8647 url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
8648 }, this.start);
8649 }
8650 }
8651 render(code) {
8652 if (this.alias !== null) {
8653 code.overwrite(this.start, this.end, this.alias, {
8654 contentOnly: false,
8655 storeName: true
8656 });
8657 }
8658 }
8659}
8660
8661class ThrowStatement extends NodeBase {
8662 hasEffects() {
8663 return true;
8664 }
8665 include(context, includeChildrenRecursively) {
8666 this.included = true;
8667 this.argument.include(context, includeChildrenRecursively);
8668 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8669 }
8670 render(code, options) {
8671 this.argument.render(code, options, { preventASI: true });
8672 if (this.argument.start === this.start + 5 /* 'throw'.length */) {
8673 code.prependLeft(this.start + 5, ' ');
8674 }
8675 }
8676}
8677
8678class TryStatement extends NodeBase {
8679 constructor() {
8680 super(...arguments);
8681 this.directlyIncluded = false;
8682 }
8683 hasEffects(context) {
8684 return ((this.context.tryCatchDeoptimization
8685 ? this.block.body.length > 0
8686 : this.block.hasEffects(context)) ||
8687 (this.finalizer !== null && this.finalizer.hasEffects(context)));
8688 }
8689 include(context, includeChildrenRecursively) {
8690 const { brokenFlow } = context;
8691 if (!this.directlyIncluded || !this.context.tryCatchDeoptimization) {
8692 this.included = true;
8693 this.directlyIncluded = true;
8694 this.block.include(context, this.context.tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
8695 context.brokenFlow = brokenFlow;
8696 }
8697 if (this.handler !== null) {
8698 this.handler.include(context, includeChildrenRecursively);
8699 context.brokenFlow = brokenFlow;
8700 }
8701 if (this.finalizer !== null) {
8702 this.finalizer.include(context, includeChildrenRecursively);
8703 }
8704 }
8705}
8706
8707const unaryOperators = {
8708 '!': value => !value,
8709 '+': value => +value,
8710 '-': value => -value,
8711 delete: () => UnknownValue,
8712 typeof: value => typeof value,
8713 void: () => undefined,
8714 '~': value => ~value
8715};
8716class UnaryExpression extends NodeBase {
8717 bind() {
8718 super.bind();
8719 if (this.operator === 'delete') {
8720 this.argument.deoptimizePath(EMPTY_PATH);
8721 }
8722 }
8723 getLiteralValueAtPath(path, recursionTracker, origin) {
8724 if (path.length > 0)
8725 return UnknownValue;
8726 const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
8727 if (argumentValue === UnknownValue)
8728 return UnknownValue;
8729 return unaryOperators[this.operator](argumentValue);
8730 }
8731 hasEffects(context) {
8732 if (this.operator === 'typeof' && this.argument instanceof Identifier$1)
8733 return false;
8734 return (this.argument.hasEffects(context) ||
8735 (this.operator === 'delete' &&
8736 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)));
8737 }
8738 hasEffectsWhenAccessedAtPath(path) {
8739 if (this.operator === 'void') {
8740 return path.length > 0;
8741 }
8742 return path.length > 1;
8743 }
8744}
8745
8746class UnknownNode extends NodeBase {
8747 hasEffects() {
8748 return true;
8749 }
8750 include(context) {
8751 super.include(context, true);
8752 }
8753}
8754
8755class UpdateExpression extends NodeBase {
8756 bind() {
8757 super.bind();
8758 this.argument.deoptimizePath(EMPTY_PATH);
8759 if (this.argument instanceof Identifier$1) {
8760 const variable = this.scope.findVariable(this.argument.name);
8761 variable.isReassigned = true;
8762 }
8763 }
8764 hasEffects(context) {
8765 return (this.argument.hasEffects(context) ||
8766 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
8767 }
8768 hasEffectsWhenAccessedAtPath(path) {
8769 return path.length > 1;
8770 }
8771 render(code, options) {
8772 this.argument.render(code, options);
8773 const variable = this.argument.variable;
8774 if (options.format === 'system' && variable && variable.exportName) {
8775 const name = variable.getName();
8776 if (this.prefix) {
8777 code.overwrite(this.start, this.end, `exports('${variable.exportName}', ${this.operator}${name})`);
8778 }
8779 else {
8780 let op;
8781 switch (this.operator) {
8782 case '++':
8783 op = `${name} + 1`;
8784 break;
8785 case '--':
8786 op = `${name} - 1`;
8787 break;
8788 }
8789 code.overwrite(this.start, this.end, `(exports('${variable.exportName}', ${op}), ${name}${this.operator})`);
8790 }
8791 }
8792 }
8793}
8794
8795function isReassignedExportsMember(variable) {
8796 return variable.renderBaseName !== null && variable.exportName !== null && variable.isReassigned;
8797}
8798function areAllDeclarationsIncludedAndNotExported(declarations) {
8799 for (const declarator of declarations) {
8800 if (!declarator.included)
8801 return false;
8802 if (declarator.id.type === Identifier) {
8803 if (declarator.id.variable.exportName)
8804 return false;
8805 }
8806 else {
8807 const exportedVariables = [];
8808 declarator.id.addExportedVariables(exportedVariables);
8809 if (exportedVariables.length > 0)
8810 return false;
8811 }
8812 }
8813 return true;
8814}
8815class VariableDeclaration$1 extends NodeBase {
8816 deoptimizePath() {
8817 for (const declarator of this.declarations) {
8818 declarator.deoptimizePath(EMPTY_PATH);
8819 }
8820 }
8821 hasEffectsWhenAssignedAtPath() {
8822 return false;
8823 }
8824 include(context, includeChildrenRecursively) {
8825 this.included = true;
8826 for (const declarator of this.declarations) {
8827 if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
8828 declarator.include(context, includeChildrenRecursively);
8829 }
8830 }
8831 includeWithAllDeclaredVariables(includeChildrenRecursively, context) {
8832 this.included = true;
8833 for (const declarator of this.declarations) {
8834 declarator.include(context, includeChildrenRecursively);
8835 }
8836 }
8837 initialise() {
8838 for (const declarator of this.declarations) {
8839 declarator.declareDeclarator(this.kind);
8840 }
8841 }
8842 render(code, options, nodeRenderOptions = BLANK) {
8843 if (areAllDeclarationsIncludedAndNotExported(this.declarations)) {
8844 for (const declarator of this.declarations) {
8845 declarator.render(code, options);
8846 }
8847 if (!nodeRenderOptions.isNoStatement &&
8848 code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
8849 code.appendLeft(this.end, ';');
8850 }
8851 }
8852 else {
8853 this.renderReplacedDeclarations(code, options, nodeRenderOptions);
8854 }
8855 }
8856 renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, addSemicolon, systemPatternExports) {
8857 if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
8858 code.remove(this.end - 1, this.end);
8859 }
8860 if (addSemicolon) {
8861 separatorString += ';';
8862 }
8863 if (lastSeparatorPos !== null) {
8864 if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
8865 (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
8866 code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
8867 actualContentEnd--;
8868 if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
8869 actualContentEnd--;
8870 }
8871 }
8872 if (actualContentEnd === lastSeparatorPos + 1) {
8873 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
8874 }
8875 else {
8876 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
8877 code.remove(actualContentEnd, renderedContentEnd);
8878 }
8879 }
8880 else {
8881 code.appendLeft(renderedContentEnd, separatorString);
8882 }
8883 if (systemPatternExports.length > 0) {
8884 code.appendLeft(renderedContentEnd, ' ' + getSystemExportStatement(systemPatternExports));
8885 }
8886 }
8887 renderReplacedDeclarations(code, options, { start = this.start, end = this.end, isNoStatement }) {
8888 const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
8889 let actualContentEnd, renderedContentEnd;
8890 if (/\n\s*$/.test(code.slice(this.start, separatedNodes[0].start))) {
8891 renderedContentEnd = this.start + this.kind.length;
8892 }
8893 else {
8894 renderedContentEnd = separatedNodes[0].start;
8895 }
8896 let lastSeparatorPos = renderedContentEnd - 1;
8897 code.remove(this.start, lastSeparatorPos);
8898 let isInDeclaration = false;
8899 let hasRenderedContent = false;
8900 let separatorString = '', leadingString, nextSeparatorString;
8901 const systemPatternExports = [];
8902 for (const { node, start, separator, contentEnd, end } of separatedNodes) {
8903 if (!node.included ||
8904 (node.id instanceof Identifier$1 &&
8905 isReassignedExportsMember(node.id.variable) &&
8906 node.init === null)) {
8907 code.remove(start, end);
8908 continue;
8909 }
8910 leadingString = '';
8911 nextSeparatorString = '';
8912 if (node.id instanceof Identifier$1 &&
8913 isReassignedExportsMember(node.id.variable)) {
8914 if (hasRenderedContent) {
8915 separatorString += ';';
8916 }
8917 isInDeclaration = false;
8918 }
8919 else {
8920 if (options.format === 'system' && node.init !== null) {
8921 if (node.id.type !== Identifier) {
8922 node.id.addExportedVariables(systemPatternExports);
8923 }
8924 else if (node.id.variable.exportName) {
8925 code.prependLeft(code.original.indexOf('=', node.id.end) + 1, ` exports('${node.id.variable.safeExportName ||
8926 node.id.variable.exportName}',`);
8927 nextSeparatorString += ')';
8928 }
8929 }
8930 if (isInDeclaration) {
8931 separatorString += ',';
8932 }
8933 else {
8934 if (hasRenderedContent) {
8935 separatorString += ';';
8936 }
8937 leadingString += `${this.kind} `;
8938 isInDeclaration = true;
8939 }
8940 }
8941 if (renderedContentEnd === lastSeparatorPos + 1) {
8942 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
8943 }
8944 else {
8945 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
8946 code.appendLeft(renderedContentEnd, leadingString);
8947 }
8948 node.render(code, options);
8949 actualContentEnd = contentEnd;
8950 renderedContentEnd = end;
8951 hasRenderedContent = true;
8952 lastSeparatorPos = separator;
8953 separatorString = nextSeparatorString;
8954 }
8955 if (hasRenderedContent) {
8956 this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, !isNoStatement, systemPatternExports);
8957 }
8958 else {
8959 code.remove(start, end);
8960 }
8961 }
8962}
8963
8964class VariableDeclarator extends NodeBase {
8965 declareDeclarator(kind) {
8966 this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
8967 }
8968 deoptimizePath(path) {
8969 this.id.deoptimizePath(path);
8970 }
8971 render(code, options) {
8972 // This can happen for hoisted variables in dead branches
8973 if (this.init !== null && !this.init.included) {
8974 code.remove(this.id.end, this.end);
8975 this.id.render(code, options);
8976 }
8977 else {
8978 super.render(code, options);
8979 }
8980 }
8981}
8982
8983class WhileStatement extends NodeBase {
8984 hasEffects(context) {
8985 if (this.test.hasEffects(context))
8986 return true;
8987 const { brokenFlow, ignore: { breaks, continues } } = context;
8988 context.ignore.breaks = true;
8989 context.ignore.continues = true;
8990 if (this.body.hasEffects(context))
8991 return true;
8992 context.ignore.breaks = breaks;
8993 context.ignore.continues = continues;
8994 context.brokenFlow = brokenFlow;
8995 return false;
8996 }
8997 include(context, includeChildrenRecursively) {
8998 this.included = true;
8999 this.test.include(context, includeChildrenRecursively);
9000 const { brokenFlow } = context;
9001 this.body.include(context, includeChildrenRecursively);
9002 context.brokenFlow = brokenFlow;
9003 }
9004}
9005
9006class YieldExpression extends NodeBase {
9007 bind() {
9008 super.bind();
9009 if (this.argument !== null) {
9010 this.argument.deoptimizePath(UNKNOWN_PATH);
9011 }
9012 }
9013 hasEffects(context) {
9014 return (!context.ignore.returnAwaitYield ||
9015 (this.argument !== null && this.argument.hasEffects(context)));
9016 }
9017 render(code, options) {
9018 if (this.argument) {
9019 this.argument.render(code, options);
9020 if (this.argument.start === this.start + 5 /* 'yield'.length */) {
9021 code.prependLeft(this.start + 5, ' ');
9022 }
9023 }
9024 }
9025}
9026
9027const nodeConstructors = {
9028 ArrayExpression,
9029 ArrayPattern,
9030 ArrowFunctionExpression,
9031 AssignmentExpression,
9032 AssignmentPattern,
9033 AwaitExpression,
9034 BinaryExpression,
9035 BlockStatement: BlockStatement$1,
9036 BreakStatement,
9037 CallExpression: CallExpression$1,
9038 CatchClause,
9039 ClassBody,
9040 ClassDeclaration,
9041 ClassExpression,
9042 ConditionalExpression,
9043 ContinueStatement,
9044 DoWhileStatement,
9045 EmptyStatement,
9046 ExportAllDeclaration: ExportAllDeclaration$1,
9047 ExportDefaultDeclaration,
9048 ExportNamedDeclaration,
9049 ExpressionStatement: ExpressionStatement$1,
9050 ForInStatement,
9051 ForOfStatement,
9052 ForStatement,
9053 FunctionDeclaration,
9054 FunctionExpression: FunctionExpression$1,
9055 Identifier: Identifier$1,
9056 IfStatement,
9057 ImportDeclaration,
9058 ImportExpression: Import,
9059 LabeledStatement,
9060 Literal,
9061 LogicalExpression,
9062 MemberExpression,
9063 MetaProperty,
9064 MethodDefinition,
9065 NewExpression,
9066 ObjectExpression,
9067 ObjectPattern,
9068 Program: Program$1,
9069 Property: Property$1,
9070 RestElement,
9071 ReturnStatement: ReturnStatement$1,
9072 SequenceExpression,
9073 SpreadElement,
9074 SwitchCase,
9075 SwitchStatement,
9076 TaggedTemplateExpression,
9077 TemplateElement,
9078 TemplateLiteral,
9079 ThisExpression,
9080 ThrowStatement,
9081 TryStatement,
9082 UnaryExpression,
9083 UnknownNode,
9084 UpdateExpression,
9085 VariableDeclaration: VariableDeclaration$1,
9086 VariableDeclarator,
9087 WhileStatement,
9088 YieldExpression
9089};
9090
9091function getOriginalLocation(sourcemapChain, location) {
9092 // This cast is guaranteed. If it were a missing Map, it wouldn't have a mappings.
9093 const filteredSourcemapChain = sourcemapChain.filter(sourcemap => sourcemap.mappings);
9094 while (filteredSourcemapChain.length > 0) {
9095 const sourcemap = filteredSourcemapChain.pop();
9096 const line = sourcemap.mappings[location.line - 1];
9097 let locationFound = false;
9098 if (line !== undefined) {
9099 for (const segment of line) {
9100 if (segment[0] >= location.column) {
9101 if (segment.length === 1)
9102 break;
9103 location = {
9104 column: segment[3],
9105 line: segment[2] + 1,
9106 name: segment.length === 5 ? sourcemap.names[segment[4]] : undefined,
9107 source: sourcemap.sources[segment[1]]
9108 };
9109 locationFound = true;
9110 break;
9111 }
9112 }
9113 }
9114 if (!locationFound) {
9115 throw new Error("Can't resolve original location of error.");
9116 }
9117 }
9118 return location;
9119}
9120
9121// AST walker module for Mozilla Parser API compatible trees
9122
9123function skipThrough(node, st, c) { c(node, st); }
9124function ignore(_node, _st, _c) {}
9125
9126// Node walkers.
9127
9128var base$1 = {};
9129
9130base$1.Program = base$1.BlockStatement = function (node, st, c) {
9131 for (var i = 0, list = node.body; i < list.length; i += 1)
9132 {
9133 var stmt = list[i];
9134
9135 c(stmt, st, "Statement");
9136 }
9137};
9138base$1.Statement = skipThrough;
9139base$1.EmptyStatement = ignore;
9140base$1.ExpressionStatement = base$1.ParenthesizedExpression =
9141 function (node, st, c) { return c(node.expression, st, "Expression"); };
9142base$1.IfStatement = function (node, st, c) {
9143 c(node.test, st, "Expression");
9144 c(node.consequent, st, "Statement");
9145 if (node.alternate) { c(node.alternate, st, "Statement"); }
9146};
9147base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
9148base$1.BreakStatement = base$1.ContinueStatement = ignore;
9149base$1.WithStatement = function (node, st, c) {
9150 c(node.object, st, "Expression");
9151 c(node.body, st, "Statement");
9152};
9153base$1.SwitchStatement = function (node, st, c) {
9154 c(node.discriminant, st, "Expression");
9155 for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
9156 var cs = list$1[i$1];
9157
9158 if (cs.test) { c(cs.test, st, "Expression"); }
9159 for (var i = 0, list = cs.consequent; i < list.length; i += 1)
9160 {
9161 var cons = list[i];
9162
9163 c(cons, st, "Statement");
9164 }
9165 }
9166};
9167base$1.SwitchCase = function (node, st, c) {
9168 if (node.test) { c(node.test, st, "Expression"); }
9169 for (var i = 0, list = node.consequent; i < list.length; i += 1)
9170 {
9171 var cons = list[i];
9172
9173 c(cons, st, "Statement");
9174 }
9175};
9176base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
9177 if (node.argument) { c(node.argument, st, "Expression"); }
9178};
9179base$1.ThrowStatement = base$1.SpreadElement =
9180 function (node, st, c) { return c(node.argument, st, "Expression"); };
9181base$1.TryStatement = function (node, st, c) {
9182 c(node.block, st, "Statement");
9183 if (node.handler) { c(node.handler, st); }
9184 if (node.finalizer) { c(node.finalizer, st, "Statement"); }
9185};
9186base$1.CatchClause = function (node, st, c) {
9187 if (node.param) { c(node.param, st, "Pattern"); }
9188 c(node.body, st, "Statement");
9189};
9190base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
9191 c(node.test, st, "Expression");
9192 c(node.body, st, "Statement");
9193};
9194base$1.ForStatement = function (node, st, c) {
9195 if (node.init) { c(node.init, st, "ForInit"); }
9196 if (node.test) { c(node.test, st, "Expression"); }
9197 if (node.update) { c(node.update, st, "Expression"); }
9198 c(node.body, st, "Statement");
9199};
9200base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
9201 c(node.left, st, "ForInit");
9202 c(node.right, st, "Expression");
9203 c(node.body, st, "Statement");
9204};
9205base$1.ForInit = function (node, st, c) {
9206 if (node.type === "VariableDeclaration") { c(node, st); }
9207 else { c(node, st, "Expression"); }
9208};
9209base$1.DebuggerStatement = ignore;
9210
9211base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
9212base$1.VariableDeclaration = function (node, st, c) {
9213 for (var i = 0, list = node.declarations; i < list.length; i += 1)
9214 {
9215 var decl = list[i];
9216
9217 c(decl, st);
9218 }
9219};
9220base$1.VariableDeclarator = function (node, st, c) {
9221 c(node.id, st, "Pattern");
9222 if (node.init) { c(node.init, st, "Expression"); }
9223};
9224
9225base$1.Function = function (node, st, c) {
9226 if (node.id) { c(node.id, st, "Pattern"); }
9227 for (var i = 0, list = node.params; i < list.length; i += 1)
9228 {
9229 var param = list[i];
9230
9231 c(param, st, "Pattern");
9232 }
9233 c(node.body, st, node.expression ? "Expression" : "Statement");
9234};
9235
9236base$1.Pattern = function (node, st, c) {
9237 if (node.type === "Identifier")
9238 { c(node, st, "VariablePattern"); }
9239 else if (node.type === "MemberExpression")
9240 { c(node, st, "MemberPattern"); }
9241 else
9242 { c(node, st); }
9243};
9244base$1.VariablePattern = ignore;
9245base$1.MemberPattern = skipThrough;
9246base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
9247base$1.ArrayPattern = function (node, st, c) {
9248 for (var i = 0, list = node.elements; i < list.length; i += 1) {
9249 var elt = list[i];
9250
9251 if (elt) { c(elt, st, "Pattern"); }
9252 }
9253};
9254base$1.ObjectPattern = function (node, st, c) {
9255 for (var i = 0, list = node.properties; i < list.length; i += 1) {
9256 var prop = list[i];
9257
9258 if (prop.type === "Property") {
9259 if (prop.computed) { c(prop.key, st, "Expression"); }
9260 c(prop.value, st, "Pattern");
9261 } else if (prop.type === "RestElement") {
9262 c(prop.argument, st, "Pattern");
9263 }
9264 }
9265};
9266
9267base$1.Expression = skipThrough;
9268base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
9269base$1.ArrayExpression = function (node, st, c) {
9270 for (var i = 0, list = node.elements; i < list.length; i += 1) {
9271 var elt = list[i];
9272
9273 if (elt) { c(elt, st, "Expression"); }
9274 }
9275};
9276base$1.ObjectExpression = function (node, st, c) {
9277 for (var i = 0, list = node.properties; i < list.length; i += 1)
9278 {
9279 var prop = list[i];
9280
9281 c(prop, st);
9282 }
9283};
9284base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
9285base$1.SequenceExpression = function (node, st, c) {
9286 for (var i = 0, list = node.expressions; i < list.length; i += 1)
9287 {
9288 var expr = list[i];
9289
9290 c(expr, st, "Expression");
9291 }
9292};
9293base$1.TemplateLiteral = function (node, st, c) {
9294 for (var i = 0, list = node.quasis; i < list.length; i += 1)
9295 {
9296 var quasi = list[i];
9297
9298 c(quasi, st);
9299 }
9300
9301 for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
9302 {
9303 var expr = list$1[i$1];
9304
9305 c(expr, st, "Expression");
9306 }
9307};
9308base$1.TemplateElement = ignore;
9309base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
9310 c(node.argument, st, "Expression");
9311};
9312base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
9313 c(node.left, st, "Expression");
9314 c(node.right, st, "Expression");
9315};
9316base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
9317 c(node.left, st, "Pattern");
9318 c(node.right, st, "Expression");
9319};
9320base$1.ConditionalExpression = function (node, st, c) {
9321 c(node.test, st, "Expression");
9322 c(node.consequent, st, "Expression");
9323 c(node.alternate, st, "Expression");
9324};
9325base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
9326 c(node.callee, st, "Expression");
9327 if (node.arguments)
9328 { for (var i = 0, list = node.arguments; i < list.length; i += 1)
9329 {
9330 var arg = list[i];
9331
9332 c(arg, st, "Expression");
9333 } }
9334};
9335base$1.MemberExpression = function (node, st, c) {
9336 c(node.object, st, "Expression");
9337 if (node.computed) { c(node.property, st, "Expression"); }
9338};
9339base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
9340 if (node.declaration)
9341 { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
9342 if (node.source) { c(node.source, st, "Expression"); }
9343};
9344base$1.ExportAllDeclaration = function (node, st, c) {
9345 c(node.source, st, "Expression");
9346};
9347base$1.ImportDeclaration = function (node, st, c) {
9348 for (var i = 0, list = node.specifiers; i < list.length; i += 1)
9349 {
9350 var spec = list[i];
9351
9352 c(spec, st);
9353 }
9354 c(node.source, st, "Expression");
9355};
9356base$1.ImportExpression = function (node, st, c) {
9357 c(node.source, st, "Expression");
9358};
9359base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = ignore;
9360
9361base$1.TaggedTemplateExpression = function (node, st, c) {
9362 c(node.tag, st, "Expression");
9363 c(node.quasi, st, "Expression");
9364};
9365base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
9366base$1.Class = function (node, st, c) {
9367 if (node.id) { c(node.id, st, "Pattern"); }
9368 if (node.superClass) { c(node.superClass, st, "Expression"); }
9369 c(node.body, st);
9370};
9371base$1.ClassBody = function (node, st, c) {
9372 for (var i = 0, list = node.body; i < list.length; i += 1)
9373 {
9374 var elt = list[i];
9375
9376 c(elt, st);
9377 }
9378};
9379base$1.MethodDefinition = base$1.Property = function (node, st, c) {
9380 if (node.computed) { c(node.key, st, "Expression"); }
9381 c(node.value, st, "Expression");
9382};
9383
9384// @ts-ignore
9385function handlePureAnnotationsOfNode(node, state, type = node.type) {
9386 let commentNode = state.commentNodes[state.commentIndex];
9387 while (commentNode && node.start >= commentNode.end) {
9388 markPureNode(node, commentNode);
9389 commentNode = state.commentNodes[++state.commentIndex];
9390 }
9391 if (commentNode && commentNode.end <= node.end) {
9392 base$1[type](node, state, handlePureAnnotationsOfNode);
9393 }
9394}
9395function markPureNode(node, comment) {
9396 if (node.annotations) {
9397 node.annotations.push(comment);
9398 }
9399 else {
9400 node.annotations = [comment];
9401 }
9402 if (node.type === 'ExpressionStatement') {
9403 node = node.expression;
9404 }
9405 if (node.type === 'CallExpression' || node.type === 'NewExpression') {
9406 node.annotatedPure = true;
9407 }
9408}
9409const pureCommentRegex = /[@#]__PURE__/;
9410const isPureComment = (comment) => pureCommentRegex.test(comment.text);
9411function markPureCallExpressions(comments, esTreeAst) {
9412 handlePureAnnotationsOfNode(esTreeAst, {
9413 commentIndex: 0,
9414 commentNodes: comments.filter(isPureComment)
9415 });
9416}
9417
9418// this looks ridiculous, but it prevents sourcemap tooling from mistaking
9419// this for an actual sourceMappingURL
9420let SOURCEMAPPING_URL = 'sourceMa';
9421SOURCEMAPPING_URL += 'ppingURL';
9422const SOURCEMAPPING_URL_RE = new RegExp(`^#\\s+${SOURCEMAPPING_URL}=.+\\n?`);
9423
9424const NOOP = () => { };
9425let getStartTime = () => [0, 0];
9426let getElapsedTime = () => 0;
9427let getMemory = () => 0;
9428let timers = {};
9429const normalizeHrTime = (time) => time[0] * 1e3 + time[1] / 1e6;
9430function setTimeHelpers() {
9431 if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
9432 getStartTime = process.hrtime.bind(process);
9433 getElapsedTime = previous => normalizeHrTime(process.hrtime(previous));
9434 }
9435 else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
9436 getStartTime = () => [performance.now(), 0];
9437 getElapsedTime = previous => performance.now() - previous[0];
9438 }
9439 if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
9440 getMemory = () => process.memoryUsage().heapUsed;
9441 }
9442}
9443function getPersistedLabel(label, level) {
9444 switch (level) {
9445 case 1:
9446 return `# ${label}`;
9447 case 2:
9448 return `## ${label}`;
9449 case 3:
9450 return label;
9451 default:
9452 return `${' '.repeat(level - 4)}- ${label}`;
9453 }
9454}
9455function timeStartImpl(label, level = 3) {
9456 label = getPersistedLabel(label, level);
9457 if (!timers.hasOwnProperty(label)) {
9458 timers[label] = {
9459 memory: 0,
9460 startMemory: undefined,
9461 startTime: undefined,
9462 time: 0,
9463 totalMemory: 0
9464 };
9465 }
9466 const currentMemory = getMemory();
9467 timers[label].startTime = getStartTime();
9468 timers[label].startMemory = currentMemory;
9469}
9470function timeEndImpl(label, level = 3) {
9471 label = getPersistedLabel(label, level);
9472 if (timers.hasOwnProperty(label)) {
9473 const currentMemory = getMemory();
9474 timers[label].time += getElapsedTime(timers[label].startTime);
9475 timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
9476 timers[label].memory += currentMemory - timers[label].startMemory;
9477 }
9478}
9479function getTimings() {
9480 const newTimings = {};
9481 Object.keys(timers).forEach(label => {
9482 newTimings[label] = [timers[label].time, timers[label].memory, timers[label].totalMemory];
9483 });
9484 return newTimings;
9485}
9486let timeStart = NOOP, timeEnd = NOOP;
9487const TIMED_PLUGIN_HOOKS = {
9488 load: true,
9489 ongenerate: true,
9490 onwrite: true,
9491 resolveDynamicImport: true,
9492 resolveId: true,
9493 transform: true,
9494 transformBundle: true
9495};
9496function getPluginWithTimers(plugin, index) {
9497 const timedPlugin = {};
9498 for (const hook of Object.keys(plugin)) {
9499 if (TIMED_PLUGIN_HOOKS[hook] === true) {
9500 let timerLabel = `plugin ${index}`;
9501 if (plugin.name) {
9502 timerLabel += ` (${plugin.name})`;
9503 }
9504 timerLabel += ` - ${hook}`;
9505 timedPlugin[hook] = function () {
9506 timeStart(timerLabel, 4);
9507 const result = plugin[hook].apply(this === timedPlugin ? plugin : this, arguments);
9508 timeEnd(timerLabel, 4);
9509 if (result && typeof result.then === 'function') {
9510 timeStart(`${timerLabel} (async)`, 4);
9511 result.then(() => timeEnd(`${timerLabel} (async)`, 4));
9512 }
9513 return result;
9514 };
9515 }
9516 else {
9517 timedPlugin[hook] = plugin[hook];
9518 }
9519 }
9520 return timedPlugin;
9521}
9522function initialiseTimers(inputOptions) {
9523 if (inputOptions.perf) {
9524 timers = {};
9525 setTimeHelpers();
9526 timeStart = timeStartImpl;
9527 timeEnd = timeEndImpl;
9528 inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
9529 }
9530 else {
9531 timeStart = NOOP;
9532 timeEnd = NOOP;
9533 }
9534}
9535
9536const defaultAcornOptions = {
9537 ecmaVersion: 2020,
9538 preserveParens: false,
9539 sourceType: 'module'
9540};
9541function tryParse(module, Parser, acornOptions) {
9542 try {
9543 return Parser.parse(module.code, Object.assign(Object.assign(Object.assign({}, defaultAcornOptions), acornOptions), { onComment: (block, text, start, end) => module.comments.push({ block, text, start, end }) }));
9544 }
9545 catch (err) {
9546 let message = err.message.replace(/ \(\d+:\d+\)$/, '');
9547 if (module.id.endsWith('.json')) {
9548 message += ' (Note that you need rollup-plugin-json to import JSON files)';
9549 }
9550 else if (!module.id.endsWith('.js')) {
9551 message += ' (Note that you need plugins to import files that are not JavaScript)';
9552 }
9553 module.error({
9554 code: 'PARSE_ERROR',
9555 message,
9556 parserError: err
9557 }, err.pos);
9558 }
9559}
9560function handleMissingExport(exportName, importingModule, importedModule, importerStart) {
9561 importingModule.error({
9562 code: 'MISSING_EXPORT',
9563 message: `'${exportName}' is not exported by ${relativeId(importedModule)}`,
9564 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
9565 }, importerStart);
9566}
9567const MISSING_EXPORT_SHIM_DESCRIPTION = {
9568 identifier: null,
9569 localName: MISSING_EXPORT_SHIM_VARIABLE
9570};
9571class Module {
9572 constructor(graph, id, moduleSideEffects, isEntry) {
9573 this.chunkFileNames = new Set();
9574 this.chunkName = null;
9575 this.comments = [];
9576 this.dependencies = [];
9577 this.dynamicallyImportedBy = [];
9578 this.dynamicDependencies = [];
9579 this.dynamicImports = [];
9580 this.entryPointsHash = new Uint8Array(10);
9581 this.execIndex = Infinity;
9582 this.exportAllModules = null;
9583 this.exportAllSources = [];
9584 this.exports = Object.create(null);
9585 this.exportsAll = Object.create(null);
9586 this.exportShimVariable = new ExportShimVariable(this);
9587 this.facadeChunk = null;
9588 this.importDescriptions = Object.create(null);
9589 this.importMetas = [];
9590 this.imports = new Set();
9591 this.isExecuted = false;
9592 this.isUserDefinedEntryPoint = false;
9593 this.manualChunkAlias = null;
9594 this.reexports = Object.create(null);
9595 this.sources = [];
9596 this.userChunkNames = new Set();
9597 this.usesTopLevelAwait = false;
9598 this.namespaceVariable = undefined;
9599 this.transformDependencies = [];
9600 this.id = id;
9601 this.graph = graph;
9602 this.excludeFromSourcemap = /\0/.test(id);
9603 this.context = graph.getModuleContext(id);
9604 this.moduleSideEffects = moduleSideEffects;
9605 this.isEntryPoint = isEntry;
9606 }
9607 basename() {
9608 const base = basename(this.id);
9609 const ext = extname(this.id);
9610 return makeLegal(ext ? base.slice(0, -ext.length) : base);
9611 }
9612 bindReferences() {
9613 this.ast.bind();
9614 }
9615 error(props, pos) {
9616 if (pos !== undefined) {
9617 props.pos = pos;
9618 let location = locate(this.code, pos, { offsetLine: 1 });
9619 try {
9620 location = getOriginalLocation(this.sourcemapChain, location);
9621 }
9622 catch (e) {
9623 this.warn({
9624 code: 'SOURCEMAP_ERROR',
9625 loc: {
9626 column: location.column,
9627 file: this.id,
9628 line: location.line
9629 },
9630 message: `Error when using sourcemap for reporting an error: ${e.message}`,
9631 pos
9632 }, undefined);
9633 }
9634 props.loc = {
9635 column: location.column,
9636 file: this.id,
9637 line: location.line
9638 };
9639 props.frame = getCodeFrame(this.originalCode, location.line, location.column);
9640 }
9641 props.watchFiles = Object.keys(this.graph.watchFiles);
9642 error(props);
9643 }
9644 getAllExportNames() {
9645 if (this.allExportNames) {
9646 return this.allExportNames;
9647 }
9648 const allExportNames = (this.allExportNames = new Set());
9649 for (const name of Object.keys(this.exports)) {
9650 allExportNames.add(name);
9651 }
9652 for (const name of Object.keys(this.reexports)) {
9653 allExportNames.add(name);
9654 }
9655 for (const module of this.exportAllModules) {
9656 if (module instanceof ExternalModule) {
9657 allExportNames.add(`*${module.id}`);
9658 continue;
9659 }
9660 for (const name of module.getAllExportNames()) {
9661 if (name !== 'default')
9662 allExportNames.add(name);
9663 }
9664 }
9665 return allExportNames;
9666 }
9667 getDynamicImportExpressions() {
9668 return this.dynamicImports.map(({ node }) => {
9669 const importArgument = node.source;
9670 if (importArgument instanceof TemplateLiteral &&
9671 importArgument.quasis.length === 1 &&
9672 importArgument.quasis[0].value.cooked) {
9673 return importArgument.quasis[0].value.cooked;
9674 }
9675 if (importArgument instanceof Literal && typeof importArgument.value === 'string') {
9676 return importArgument.value;
9677 }
9678 return importArgument;
9679 });
9680 }
9681 getExportNamesByVariable() {
9682 const exportNamesByVariable = new Map();
9683 for (const exportName of this.getAllExportNames()) {
9684 const tracedVariable = this.getVariableForExportName(exportName);
9685 if (!tracedVariable ||
9686 !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
9687 continue;
9688 }
9689 const existingExportNames = exportNamesByVariable.get(tracedVariable);
9690 if (existingExportNames) {
9691 existingExportNames.push(exportName);
9692 }
9693 else {
9694 exportNamesByVariable.set(tracedVariable, [exportName]);
9695 }
9696 }
9697 return exportNamesByVariable;
9698 }
9699 getExports() {
9700 return Object.keys(this.exports);
9701 }
9702 getOrCreateNamespace() {
9703 if (!this.namespaceVariable) {
9704 this.namespaceVariable = new NamespaceVariable(this.astContext);
9705 this.namespaceVariable.initialise();
9706 }
9707 return this.namespaceVariable;
9708 }
9709 getReexports() {
9710 if (this.transitiveReexports) {
9711 return this.transitiveReexports;
9712 }
9713 // to avoid infinite recursion when using circular `export * from X`
9714 this.transitiveReexports = [];
9715 const reexports = new Set();
9716 for (const name in this.reexports) {
9717 reexports.add(name);
9718 }
9719 for (const module of this.exportAllModules) {
9720 if (module instanceof ExternalModule) {
9721 reexports.add(`*${module.id}`);
9722 }
9723 else {
9724 for (const name of module.getExports().concat(module.getReexports())) {
9725 if (name !== 'default')
9726 reexports.add(name);
9727 }
9728 }
9729 }
9730 return (this.transitiveReexports = Array.from(reexports));
9731 }
9732 getRenderedExports() {
9733 // only direct exports are counted here, not reexports at all
9734 const renderedExports = [];
9735 const removedExports = [];
9736 for (const exportName in this.exports) {
9737 const variable = this.getVariableForExportName(exportName);
9738 (variable && variable.included ? renderedExports : removedExports).push(exportName);
9739 }
9740 return { renderedExports, removedExports };
9741 }
9742 getTransitiveDependencies() {
9743 return this.dependencies.concat(this.getReexports().map(exportName => this.getVariableForExportName(exportName).module));
9744 }
9745 getVariableForExportName(name, isExportAllSearch) {
9746 if (name[0] === '*') {
9747 if (name.length === 1) {
9748 return this.getOrCreateNamespace();
9749 }
9750 else {
9751 // export * from 'external'
9752 const module = this.graph.moduleById.get(name.slice(1));
9753 return module.getVariableForExportName('*');
9754 }
9755 }
9756 // export { foo } from './other'
9757 const reexportDeclaration = this.reexports[name];
9758 if (reexportDeclaration) {
9759 const declaration = reexportDeclaration.module.getVariableForExportName(reexportDeclaration.localName);
9760 if (!declaration) {
9761 handleMissingExport(reexportDeclaration.localName, this, reexportDeclaration.module.id, reexportDeclaration.start);
9762 }
9763 return declaration;
9764 }
9765 const exportDeclaration = this.exports[name];
9766 if (exportDeclaration) {
9767 if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
9768 return this.exportShimVariable;
9769 }
9770 const name = exportDeclaration.localName;
9771 return this.traceVariable(name) || this.graph.scope.findVariable(name);
9772 }
9773 if (name !== 'default') {
9774 for (const module of this.exportAllModules) {
9775 const declaration = module.getVariableForExportName(name, true);
9776 if (declaration)
9777 return declaration;
9778 }
9779 }
9780 // we don't want to create shims when we are just
9781 // probing export * modules for exports
9782 if (this.graph.shimMissingExports && !isExportAllSearch) {
9783 this.shimMissingExport(name);
9784 return this.exportShimVariable;
9785 }
9786 return undefined;
9787 }
9788 include() {
9789 const context = createInclusionContext();
9790 if (this.ast.shouldBeIncluded(context))
9791 this.ast.include(context, false);
9792 }
9793 includeAllExports() {
9794 if (!this.isExecuted) {
9795 this.graph.needsTreeshakingPass = true;
9796 markModuleAndImpureDependenciesAsExecuted(this);
9797 }
9798 const context = createInclusionContext();
9799 for (const exportName of this.getExports()) {
9800 const variable = this.getVariableForExportName(exportName);
9801 variable.deoptimizePath(UNKNOWN_PATH);
9802 if (!variable.included) {
9803 variable.include(context);
9804 this.graph.needsTreeshakingPass = true;
9805 }
9806 }
9807 for (const name of this.getReexports()) {
9808 const variable = this.getVariableForExportName(name);
9809 variable.deoptimizePath(UNKNOWN_PATH);
9810 if (!variable.included) {
9811 variable.include(context);
9812 this.graph.needsTreeshakingPass = true;
9813 }
9814 if (variable instanceof ExternalVariable) {
9815 variable.module.reexported = true;
9816 }
9817 }
9818 }
9819 includeAllInBundle() {
9820 this.ast.include(createInclusionContext(), true);
9821 }
9822 isIncluded() {
9823 return this.ast.included || (this.namespaceVariable && this.namespaceVariable.included);
9824 }
9825 linkDependencies() {
9826 for (const source of this.sources) {
9827 const id = this.resolvedIds[source].id;
9828 if (id) {
9829 const module = this.graph.moduleById.get(id);
9830 this.dependencies.push(module);
9831 }
9832 }
9833 for (const { resolution } of this.dynamicImports) {
9834 if (resolution instanceof Module || resolution instanceof ExternalModule) {
9835 this.dynamicDependencies.push(resolution);
9836 }
9837 }
9838 this.addModulesToSpecifiers(this.importDescriptions);
9839 this.addModulesToSpecifiers(this.reexports);
9840 this.exportAllModules = this.exportAllSources
9841 .map(source => {
9842 const id = this.resolvedIds[source].id;
9843 return this.graph.moduleById.get(id);
9844 })
9845 .sort((moduleA, moduleB) => {
9846 const aExternal = moduleA instanceof ExternalModule;
9847 const bExternal = moduleB instanceof ExternalModule;
9848 return aExternal === bExternal ? 0 : aExternal ? 1 : -1;
9849 });
9850 }
9851 render(options) {
9852 const magicString = this.magicString.clone();
9853 this.ast.render(magicString, options);
9854 this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
9855 return magicString;
9856 }
9857 setSource({ ast, code, customTransformCache, moduleSideEffects, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles }) {
9858 this.code = code;
9859 this.originalCode = originalCode;
9860 this.originalSourcemap = originalSourcemap;
9861 this.sourcemapChain = sourcemapChain;
9862 if (transformFiles) {
9863 this.transformFiles = transformFiles;
9864 }
9865 this.transformDependencies = transformDependencies;
9866 this.customTransformCache = customTransformCache;
9867 if (typeof moduleSideEffects === 'boolean') {
9868 this.moduleSideEffects = moduleSideEffects;
9869 }
9870 timeStart('generate ast', 3);
9871 this.esTreeAst = ast || tryParse(this, this.graph.acornParser, this.graph.acornOptions);
9872 markPureCallExpressions(this.comments, this.esTreeAst);
9873 timeEnd('generate ast', 3);
9874 this.resolvedIds = resolvedIds || Object.create(null);
9875 // By default, `id` is the file name. Custom resolvers and loaders
9876 // can change that, but it makes sense to use it for the source file name
9877 const fileName = this.id;
9878 this.magicString = new MagicString(code, {
9879 filename: (this.excludeFromSourcemap ? null : fileName),
9880 indentExclusionRanges: []
9881 });
9882 this.removeExistingSourceMap();
9883 timeStart('analyse ast', 3);
9884 this.astContext = {
9885 addDynamicImport: this.addDynamicImport.bind(this),
9886 addExport: this.addExport.bind(this),
9887 addImport: this.addImport.bind(this),
9888 addImportMeta: this.addImportMeta.bind(this),
9889 annotations: (this.graph.treeshakingOptions &&
9890 this.graph.treeshakingOptions.annotations),
9891 code,
9892 deoptimizationTracker: this.graph.deoptimizationTracker,
9893 error: this.error.bind(this),
9894 fileName,
9895 getExports: this.getExports.bind(this),
9896 getFileName: this.graph.pluginDriver.getFileName,
9897 getModuleExecIndex: () => this.execIndex,
9898 getModuleName: this.basename.bind(this),
9899 getReexports: this.getReexports.bind(this),
9900 importDescriptions: this.importDescriptions,
9901 includeDynamicImport: this.includeDynamicImport.bind(this),
9902 includeVariable: this.includeVariable.bind(this),
9903 isCrossChunkImport: importDescription => importDescription.module.chunk !== this.chunk,
9904 magicString: this.magicString,
9905 module: this,
9906 moduleContext: this.context,
9907 nodeConstructors,
9908 preserveModules: this.graph.preserveModules,
9909 propertyReadSideEffects: (!this.graph.treeshakingOptions ||
9910 this.graph.treeshakingOptions.propertyReadSideEffects),
9911 traceExport: this.getVariableForExportName.bind(this),
9912 traceVariable: this.traceVariable.bind(this),
9913 treeshake: !!this.graph.treeshakingOptions,
9914 tryCatchDeoptimization: (!this.graph.treeshakingOptions ||
9915 this.graph.treeshakingOptions.tryCatchDeoptimization),
9916 unknownGlobalSideEffects: (!this.graph.treeshakingOptions ||
9917 this.graph.treeshakingOptions.unknownGlobalSideEffects),
9918 usesTopLevelAwait: false,
9919 warn: this.warn.bind(this),
9920 warnDeprecation: this.graph.warnDeprecation.bind(this.graph)
9921 };
9922 this.scope = new ModuleScope(this.graph.scope, this.astContext);
9923 this.ast = new Program$1(this.esTreeAst, { type: 'Module', context: this.astContext }, this.scope);
9924 timeEnd('analyse ast', 3);
9925 }
9926 toJSON() {
9927 return {
9928 ast: this.esTreeAst,
9929 code: this.code,
9930 customTransformCache: this.customTransformCache,
9931 dependencies: this.dependencies.map(module => module.id),
9932 id: this.id,
9933 moduleSideEffects: this.moduleSideEffects,
9934 originalCode: this.originalCode,
9935 originalSourcemap: this.originalSourcemap,
9936 resolvedIds: this.resolvedIds,
9937 sourcemapChain: this.sourcemapChain,
9938 transformDependencies: this.transformDependencies,
9939 transformFiles: this.transformFiles
9940 };
9941 }
9942 traceVariable(name) {
9943 const localVariable = this.scope.variables.get(name);
9944 if (localVariable) {
9945 return localVariable;
9946 }
9947 if (name in this.importDescriptions) {
9948 const importDeclaration = this.importDescriptions[name];
9949 const otherModule = importDeclaration.module;
9950 if (otherModule instanceof Module && importDeclaration.name === '*') {
9951 return otherModule.getOrCreateNamespace();
9952 }
9953 const declaration = otherModule.getVariableForExportName(importDeclaration.name);
9954 if (!declaration) {
9955 handleMissingExport(importDeclaration.name, this, otherModule.id, importDeclaration.start);
9956 }
9957 return declaration;
9958 }
9959 return null;
9960 }
9961 warn(warning, pos) {
9962 if (pos !== undefined) {
9963 warning.pos = pos;
9964 const { line, column } = locate(this.code, pos, { offsetLine: 1 }); // TODO trace sourcemaps, cf. error()
9965 warning.loc = { file: this.id, line, column };
9966 warning.frame = getCodeFrame(this.code, line, column);
9967 }
9968 warning.id = this.id;
9969 this.graph.warn(warning);
9970 }
9971 addDynamicImport(node) {
9972 this.dynamicImports.push({ node, resolution: null });
9973 }
9974 addExport(node) {
9975 const source = node.source && node.source.value;
9976 // export { name } from './other'
9977 if (source) {
9978 if (this.sources.indexOf(source) === -1)
9979 this.sources.push(source);
9980 if (node.type === ExportAllDeclaration) {
9981 // Store `export * from '...'` statements in an array of delegates.
9982 // When an unknown import is encountered, we see if one of them can satisfy it.
9983 this.exportAllSources.push(source);
9984 }
9985 else {
9986 for (const specifier of node.specifiers) {
9987 const name = specifier.exported.name;
9988 if (this.exports[name] || this.reexports[name]) {
9989 this.error({
9990 code: 'DUPLICATE_EXPORT',
9991 message: `A module cannot have multiple exports with the same name ('${name}')`
9992 }, specifier.start);
9993 }
9994 this.reexports[name] = {
9995 localName: specifier.local.name,
9996 module: null,
9997 source,
9998 start: specifier.start
9999 };
10000 }
10001 }
10002 }
10003 else if (node instanceof ExportDefaultDeclaration) {
10004 // export default function foo () {}
10005 // export default foo;
10006 // export default 42;
10007 if (this.exports.default) {
10008 this.error({
10009 code: 'DUPLICATE_EXPORT',
10010 message: `A module can only have one default export`
10011 }, node.start);
10012 }
10013 this.exports.default = {
10014 identifier: node.variable.getAssignedVariableName(),
10015 localName: 'default'
10016 };
10017 }
10018 else if (node.declaration) {
10019 // export var { foo, bar } = ...
10020 // export var foo = 42;
10021 // export var a = 1, b = 2, c = 3;
10022 // export function foo () {}
10023 const declaration = node.declaration;
10024 if (declaration.type === VariableDeclaration) {
10025 for (const decl of declaration.declarations) {
10026 for (const localName of extractAssignedNames(decl.id)) {
10027 this.exports[localName] = { identifier: null, localName };
10028 }
10029 }
10030 }
10031 else {
10032 // export function foo () {}
10033 const localName = declaration.id.name;
10034 this.exports[localName] = { identifier: null, localName };
10035 }
10036 }
10037 else {
10038 // export { foo, bar, baz }
10039 for (const specifier of node.specifiers) {
10040 const localName = specifier.local.name;
10041 const exportedName = specifier.exported.name;
10042 if (this.exports[exportedName] || this.reexports[exportedName]) {
10043 this.error({
10044 code: 'DUPLICATE_EXPORT',
10045 message: `A module cannot have multiple exports with the same name ('${exportedName}')`
10046 }, specifier.start);
10047 }
10048 this.exports[exportedName] = { identifier: null, localName };
10049 }
10050 }
10051 }
10052 addImport(node) {
10053 const source = node.source.value;
10054 if (this.sources.indexOf(source) === -1)
10055 this.sources.push(source);
10056 for (const specifier of node.specifiers) {
10057 const localName = specifier.local.name;
10058 if (this.importDescriptions[localName]) {
10059 this.error({
10060 code: 'DUPLICATE_IMPORT',
10061 message: `Duplicated import '${localName}'`
10062 }, specifier.start);
10063 }
10064 const isDefault = specifier.type === ImportDefaultSpecifier;
10065 const isNamespace = specifier.type === ImportNamespaceSpecifier;
10066 const name = isDefault
10067 ? 'default'
10068 : isNamespace
10069 ? '*'
10070 : specifier.imported.name;
10071 this.importDescriptions[localName] = { source, start: specifier.start, name, module: null };
10072 }
10073 }
10074 addImportMeta(node) {
10075 this.importMetas.push(node);
10076 }
10077 addModulesToSpecifiers(specifiers) {
10078 for (const name of Object.keys(specifiers)) {
10079 const specifier = specifiers[name];
10080 const id = this.resolvedIds[specifier.source].id;
10081 specifier.module = this.graph.moduleById.get(id);
10082 }
10083 }
10084 includeDynamicImport(node) {
10085 const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
10086 if (resolution instanceof Module) {
10087 resolution.dynamicallyImportedBy.push(this);
10088 resolution.includeAllExports();
10089 }
10090 }
10091 includeVariable(context, variable) {
10092 const variableModule = variable.module;
10093 if (!variable.included) {
10094 variable.include(context);
10095 this.graph.needsTreeshakingPass = true;
10096 }
10097 if (variableModule && variableModule !== this) {
10098 this.imports.add(variable);
10099 }
10100 }
10101 removeExistingSourceMap() {
10102 for (const comment of this.comments) {
10103 if (!comment.block && SOURCEMAPPING_URL_RE.test(comment.text)) {
10104 this.magicString.remove(comment.start, comment.end);
10105 }
10106 }
10107 }
10108 shimMissingExport(name) {
10109 if (!this.exports[name]) {
10110 this.graph.warn({
10111 code: 'SHIMMED_EXPORT',
10112 exporter: relativeId(this.id),
10113 exportName: name,
10114 message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
10115 });
10116 this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
10117 }
10118 }
10119}
10120
10121class Source {
10122 constructor(filename, content) {
10123 this.isOriginal = true;
10124 this.filename = filename;
10125 this.content = content;
10126 }
10127 traceSegment(line, column, name) {
10128 return { line, column, name, source: this };
10129 }
10130}
10131class Link {
10132 constructor(map, sources) {
10133 this.sources = sources;
10134 this.names = map.names;
10135 this.mappings = map.mappings;
10136 }
10137 traceMappings() {
10138 const sources = [];
10139 const sourcesContent = [];
10140 const names = [];
10141 const mappings = [];
10142 for (const line of this.mappings) {
10143 const tracedLine = [];
10144 for (const segment of line) {
10145 if (segment.length == 1)
10146 continue;
10147 const source = this.sources[segment[1]];
10148 if (!source)
10149 continue;
10150 const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
10151 if (traced) {
10152 // newer sources are more likely to be used, so search backwards.
10153 let sourceIndex = sources.lastIndexOf(traced.source.filename);
10154 if (sourceIndex === -1) {
10155 sourceIndex = sources.length;
10156 sources.push(traced.source.filename);
10157 sourcesContent[sourceIndex] = traced.source.content;
10158 }
10159 else if (sourcesContent[sourceIndex] == null) {
10160 sourcesContent[sourceIndex] = traced.source.content;
10161 }
10162 else if (traced.source.content != null &&
10163 sourcesContent[sourceIndex] !== traced.source.content) {
10164 error({
10165 message: `Multiple conflicting contents for sourcemap source ${traced.source.filename}`
10166 });
10167 }
10168 const tracedSegment = [
10169 segment[0],
10170 sourceIndex,
10171 traced.line,
10172 traced.column
10173 ];
10174 if (traced.name) {
10175 let nameIndex = names.indexOf(traced.name);
10176 if (nameIndex === -1) {
10177 nameIndex = names.length;
10178 names.push(traced.name);
10179 }
10180 tracedSegment[4] = nameIndex;
10181 }
10182 tracedLine.push(tracedSegment);
10183 }
10184 }
10185 mappings.push(tracedLine);
10186 }
10187 return { sources, sourcesContent, names, mappings };
10188 }
10189 traceSegment(line, column, name) {
10190 const segments = this.mappings[line];
10191 if (!segments)
10192 return null;
10193 // binary search through segments for the given column
10194 let i = 0;
10195 let j = segments.length - 1;
10196 while (i <= j) {
10197 const m = (i + j) >> 1;
10198 const segment = segments[m];
10199 if (segment[0] === column) {
10200 if (segment.length == 1)
10201 return null;
10202 const source = this.sources[segment[1]];
10203 if (!source)
10204 return null;
10205 return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
10206 }
10207 if (segment[0] > column) {
10208 j = m - 1;
10209 }
10210 else {
10211 i = m + 1;
10212 }
10213 }
10214 return null;
10215 }
10216}
10217function getLinkMap(graph) {
10218 return function linkMap(source, map) {
10219 if (map.mappings) {
10220 return new Link(map, [source]);
10221 }
10222 graph.warn({
10223 code: 'SOURCEMAP_BROKEN',
10224 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`,
10225 plugin: map.plugin,
10226 url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
10227 });
10228 return new Link({
10229 mappings: [],
10230 names: []
10231 }, [source]);
10232 };
10233}
10234function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
10235 let source;
10236 if (!originalSourcemap) {
10237 source = new Source(id, originalCode);
10238 }
10239 else {
10240 const sources = originalSourcemap.sources;
10241 const sourcesContent = originalSourcemap.sourcesContent || [];
10242 // TODO indiscriminately treating IDs and sources as normal paths is probably bad.
10243 const directory = dirname(id) || '.';
10244 const sourceRoot = originalSourcemap.sourceRoot || '.';
10245 const baseSources = sources.map((source, i) => new Source(resolve(directory, sourceRoot, source), sourcesContent[i]));
10246 source = new Link(originalSourcemap, baseSources);
10247 }
10248 return sourcemapChain.reduce(linkMap, source);
10249}
10250function collapseSourcemaps(bundle, file, map, modules, bundleSourcemapChain, excludeContent) {
10251 const linkMap = getLinkMap(bundle.graph);
10252 const moduleSources = modules
10253 .filter(module => !module.excludeFromSourcemap)
10254 .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
10255 // DecodedSourceMap (from magic-string) uses a number[] instead of the more
10256 // correct SourceMapSegment tuples. Cast it here to gain type safety.
10257 let source = new Link(map, moduleSources);
10258 source = bundleSourcemapChain.reduce(linkMap, source);
10259 let { sources, sourcesContent, names, mappings } = source.traceMappings();
10260 if (file) {
10261 const directory = dirname(file);
10262 sources = sources.map((source) => relative$1(directory, source));
10263 file = basename(file);
10264 }
10265 sourcesContent = (excludeContent ? null : sourcesContent);
10266 return new SourceMap({ file, sources, sourcesContent, names, mappings });
10267}
10268function collapseSourcemap(graph, id, originalCode, originalSourcemap, sourcemapChain) {
10269 if (!sourcemapChain.length) {
10270 return originalSourcemap;
10271 }
10272 const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(graph));
10273 const map = source.traceMappings();
10274 return Object.assign({ version: 3 }, map);
10275}
10276
10277const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
10278 amd: deconflictImportsOther,
10279 cjs: deconflictImportsOther,
10280 es: deconflictImportsEsm,
10281 iife: deconflictImportsOther,
10282 system: deconflictImportsEsm,
10283 umd: deconflictImportsOther
10284};
10285function deconflictChunk(modules, dependencies, imports, usedNames, format, interop, preserveModules) {
10286 addUsedGlobalNames(usedNames, modules, format);
10287 deconflictTopLevelVariables(usedNames, modules);
10288 DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependencies, interop, preserveModules);
10289 for (const module of modules) {
10290 module.scope.deconflict(format);
10291 }
10292}
10293function addUsedGlobalNames(usedNames, modules, format) {
10294 for (const module of modules) {
10295 const moduleScope = module.scope;
10296 for (const [name, variable] of moduleScope.accessedOutsideVariables) {
10297 if (variable.included) {
10298 usedNames.add(name);
10299 }
10300 }
10301 const accessedGlobalVariables = moduleScope.accessedGlobalVariablesByFormat &&
10302 moduleScope.accessedGlobalVariablesByFormat.get(format);
10303 if (accessedGlobalVariables) {
10304 for (const name of accessedGlobalVariables) {
10305 usedNames.add(name);
10306 }
10307 }
10308 }
10309}
10310function deconflictImportsEsm(usedNames, imports, _dependencies, interop) {
10311 for (const variable of imports) {
10312 const module = variable.module;
10313 const name = variable.name;
10314 let proposedName;
10315 if (module instanceof ExternalModule && (name === '*' || name === 'default')) {
10316 if (name === 'default' && interop && module.exportsNamespace) {
10317 proposedName = module.variableName + '__default';
10318 }
10319 else {
10320 proposedName = module.variableName;
10321 }
10322 }
10323 else {
10324 proposedName = name;
10325 }
10326 variable.setRenderNames(null, getSafeName(proposedName, usedNames));
10327 }
10328}
10329function deconflictImportsOther(usedNames, imports, dependencies, interop, preserveModules) {
10330 for (const chunkOrExternalModule of dependencies) {
10331 chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.variableName, usedNames);
10332 }
10333 for (const variable of imports) {
10334 const module = variable.module;
10335 if (module instanceof ExternalModule) {
10336 const name = variable.name;
10337 if (name === 'default' && interop && (module.exportsNamespace || module.exportsNames)) {
10338 variable.setRenderNames(null, module.variableName + '__default');
10339 }
10340 else if (name === '*' || name === 'default') {
10341 variable.setRenderNames(null, module.variableName);
10342 }
10343 else {
10344 variable.setRenderNames(module.variableName, null);
10345 }
10346 }
10347 else {
10348 const chunk = module.chunk;
10349 if (chunk.exportMode === 'default' || (preserveModules && variable.isNamespace)) {
10350 variable.setRenderNames(null, chunk.variableName);
10351 }
10352 else {
10353 variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
10354 }
10355 }
10356 }
10357}
10358function deconflictTopLevelVariables(usedNames, modules) {
10359 for (const module of modules) {
10360 for (const variable of module.scope.variables.values()) {
10361 if (variable.included &&
10362 // this will only happen for exports in some formats
10363 !(variable.renderBaseName ||
10364 (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
10365 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
10366 }
10367 }
10368 const namespace = module.getOrCreateNamespace();
10369 if (namespace.included) {
10370 namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
10371 }
10372 }
10373}
10374
10375const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
10376function sortByExecutionOrder(units) {
10377 units.sort(compareExecIndex);
10378}
10379function analyseModuleExecution(entryModules) {
10380 let nextExecIndex = 0;
10381 const cyclePaths = [];
10382 const analysedModules = {};
10383 const orderedModules = [];
10384 const dynamicImports = [];
10385 const parents = {};
10386 const analyseModule = (module) => {
10387 if (analysedModules[module.id])
10388 return;
10389 if (module instanceof ExternalModule) {
10390 module.execIndex = nextExecIndex++;
10391 analysedModules[module.id] = true;
10392 return;
10393 }
10394 for (const dependency of module.dependencies) {
10395 if (dependency.id in parents) {
10396 if (!analysedModules[dependency.id]) {
10397 cyclePaths.push(getCyclePath(dependency.id, module.id, parents));
10398 }
10399 continue;
10400 }
10401 parents[dependency.id] = module.id;
10402 analyseModule(dependency);
10403 }
10404 for (const { resolution } of module.dynamicImports) {
10405 if (resolution instanceof Module && dynamicImports.indexOf(resolution) === -1) {
10406 dynamicImports.push(resolution);
10407 }
10408 }
10409 module.execIndex = nextExecIndex++;
10410 analysedModules[module.id] = true;
10411 orderedModules.push(module);
10412 };
10413 for (const curEntry of entryModules) {
10414 if (!parents[curEntry.id]) {
10415 parents[curEntry.id] = null;
10416 analyseModule(curEntry);
10417 }
10418 }
10419 for (const curEntry of dynamicImports) {
10420 if (!parents[curEntry.id]) {
10421 parents[curEntry.id] = null;
10422 analyseModule(curEntry);
10423 }
10424 }
10425 return { orderedModules, cyclePaths };
10426}
10427function getCyclePath(id, parentId, parents) {
10428 const path = [relativeId(id)];
10429 let curId = parentId;
10430 while (curId !== id) {
10431 path.push(relativeId(curId));
10432 curId = parents[curId];
10433 if (!curId)
10434 break;
10435 }
10436 path.push(path[0]);
10437 path.reverse();
10438 return path;
10439}
10440
10441function guessIndentString(code) {
10442 const lines = code.split('\n');
10443 const tabbed = lines.filter(line => /^\t+/.test(line));
10444 const spaced = lines.filter(line => /^ {2,}/.test(line));
10445 if (tabbed.length === 0 && spaced.length === 0) {
10446 return null;
10447 }
10448 // More lines tabbed than spaced? Assume tabs, and
10449 // default to tabs in the case of a tie (or nothing
10450 // to go on)
10451 if (tabbed.length >= spaced.length) {
10452 return '\t';
10453 }
10454 // Otherwise, we need to guess the multiple
10455 const min = spaced.reduce((previous, current) => {
10456 const numSpaces = /^ +/.exec(current)[0].length;
10457 return Math.min(numSpaces, previous);
10458 }, Infinity);
10459 return new Array(min + 1).join(' ');
10460}
10461function getIndentString(modules, options) {
10462 if (options.indent !== true)
10463 return options.indent || '';
10464 for (let i = 0; i < modules.length; i++) {
10465 const indent = guessIndentString(modules[i].originalCode);
10466 if (indent !== null)
10467 return indent;
10468 }
10469 return '\t';
10470}
10471
10472function decodedSourcemap(map) {
10473 if (!map)
10474 return null;
10475 if (typeof map === 'string') {
10476 map = JSON.parse(map);
10477 }
10478 if (map.mappings === '') {
10479 return {
10480 mappings: [],
10481 names: [],
10482 sources: [],
10483 version: 3
10484 };
10485 }
10486 let mappings;
10487 if (typeof map.mappings === 'string') {
10488 mappings = decode(map.mappings);
10489 }
10490 else {
10491 mappings = map.mappings;
10492 }
10493 return Object.assign(Object.assign({}, map), { mappings });
10494}
10495
10496function renderChunk({ graph, chunk, renderChunk, code, sourcemapChain, options }) {
10497 const renderChunkReducer = (code, result, plugin) => {
10498 if (result == null)
10499 return code;
10500 if (typeof result === 'string')
10501 result = {
10502 code: result,
10503 map: undefined
10504 };
10505 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
10506 if (result.map !== null) {
10507 const map = decodedSourcemap(result.map);
10508 sourcemapChain.push(map || { missing: true, plugin: plugin.name });
10509 }
10510 return result.code;
10511 };
10512 let inTransformBundle = false;
10513 let inRenderChunk = true;
10514 return graph.pluginDriver
10515 .hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer)
10516 .then(code => {
10517 inRenderChunk = false;
10518 return graph.pluginDriver.hookReduceArg0('transformChunk', [code, options, chunk], renderChunkReducer);
10519 })
10520 .then(code => {
10521 inTransformBundle = true;
10522 return graph.pluginDriver.hookReduceArg0('transformBundle', [code, options, chunk], renderChunkReducer);
10523 })
10524 .catch(err => {
10525 if (inRenderChunk)
10526 throw err;
10527 return error(err, {
10528 code: inTransformBundle ? 'BAD_BUNDLE_TRANSFORMER' : 'BAD_CHUNK_TRANSFORMER',
10529 message: `Error transforming ${(inTransformBundle ? 'bundle' : 'chunk') +
10530 (err.plugin ? ` with '${err.plugin}' plugin` : '')}: ${err.message}`,
10531 plugin: err.plugin
10532 });
10533 });
10534}
10535
10536function renderNamePattern(pattern, patternName, replacements) {
10537 if (!isPlainPathFragment(pattern))
10538 return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths and must not contain invalid characters.`));
10539 return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
10540 if (!replacements.hasOwnProperty(type)) {
10541 return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
10542 }
10543 const replacement = replacements[type]();
10544 if (!isPlainPathFragment(replacement))
10545 return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
10546 return replacement;
10547 });
10548}
10549function makeUnique(name, existingNames) {
10550 if (name in existingNames === false)
10551 return name;
10552 const ext = extname(name);
10553 name = name.substr(0, name.length - ext.length);
10554 let uniqueName, uniqueIndex = 1;
10555 while (existingNames[(uniqueName = name + ++uniqueIndex + ext)])
10556 ;
10557 return uniqueName;
10558}
10559
10560const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
10561function getGlobalName(module, globals, graph, hasExports) {
10562 let globalName;
10563 if (typeof globals === 'function') {
10564 globalName = globals(module.id);
10565 }
10566 else if (globals) {
10567 globalName = globals[module.id];
10568 }
10569 if (globalName) {
10570 return globalName;
10571 }
10572 if (hasExports) {
10573 graph.warn({
10574 code: 'MISSING_GLOBAL_NAME',
10575 guess: module.variableName,
10576 message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
10577 source: module.id
10578 });
10579 return module.variableName;
10580 }
10581}
10582function isChunkRendered(chunk) {
10583 return !chunk.isEmpty || chunk.entryModules.length > 0 || chunk.manualChunkAlias !== null;
10584}
10585class Chunk$1 {
10586 constructor(graph, orderedModules) {
10587 this.entryModules = [];
10588 this.exportMode = 'named';
10589 this.facadeModule = null;
10590 this.id = null;
10591 this.indentString = undefined;
10592 this.manualChunkAlias = null;
10593 this.usedModules = undefined;
10594 this.variableName = 'chunk';
10595 this.dependencies = undefined;
10596 this.dynamicDependencies = undefined;
10597 this.exportNames = Object.create(null);
10598 this.exports = new Set();
10599 this.fileName = null;
10600 this.imports = new Set();
10601 this.name = null;
10602 this.needsExportsShim = false;
10603 this.renderedDeclarations = undefined;
10604 this.renderedHash = undefined;
10605 this.renderedModuleSources = new Map();
10606 this.renderedSource = null;
10607 this.renderedSourceLength = undefined;
10608 this.sortedExportNames = null;
10609 this.graph = graph;
10610 this.orderedModules = orderedModules;
10611 this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
10612 this.isEmpty = true;
10613 for (const module of orderedModules) {
10614 if (this.isEmpty && module.isIncluded()) {
10615 this.isEmpty = false;
10616 }
10617 if (module.manualChunkAlias) {
10618 this.manualChunkAlias = module.manualChunkAlias;
10619 }
10620 module.chunk = this;
10621 if (module.isEntryPoint ||
10622 module.dynamicallyImportedBy.some(module => orderedModules.indexOf(module) === -1)) {
10623 this.entryModules.push(module);
10624 }
10625 }
10626 const moduleForNaming = this.entryModules[0] || this.orderedModules[this.orderedModules.length - 1];
10627 if (moduleForNaming) {
10628 this.variableName = makeLegal(basename(moduleForNaming.chunkName ||
10629 moduleForNaming.manualChunkAlias ||
10630 getAliasName(moduleForNaming.id)));
10631 }
10632 }
10633 static generateFacade(graph, facadedModule, facadeName) {
10634 const chunk = new Chunk$1(graph, []);
10635 chunk.assignFacadeName(facadeName, facadedModule);
10636 if (!facadedModule.facadeChunk) {
10637 facadedModule.facadeChunk = chunk;
10638 }
10639 chunk.dependencies = [facadedModule.chunk];
10640 chunk.dynamicDependencies = [];
10641 chunk.facadeModule = facadedModule;
10642 for (const exportName of facadedModule.getAllExportNames()) {
10643 const tracedVariable = facadedModule.getVariableForExportName(exportName);
10644 chunk.exports.add(tracedVariable);
10645 chunk.exportNames[exportName] = tracedVariable;
10646 }
10647 return chunk;
10648 }
10649 canModuleBeFacade(moduleExportNamesByVariable) {
10650 for (const exposedVariable of this.exports) {
10651 if (!moduleExportNamesByVariable.has(exposedVariable)) {
10652 return false;
10653 }
10654 }
10655 return true;
10656 }
10657 generateFacades() {
10658 const facades = [];
10659 for (const module of this.entryModules) {
10660 const requiredFacades = Array.from(module.userChunkNames).map(name => ({
10661 name
10662 }));
10663 if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
10664 requiredFacades.push({});
10665 }
10666 requiredFacades.push(...Array.from(module.chunkFileNames).map(fileName => ({ fileName })));
10667 if (requiredFacades.length === 0) {
10668 requiredFacades.push({});
10669 }
10670 if (!this.facadeModule) {
10671 const exportNamesByVariable = module.getExportNamesByVariable();
10672 if (this.graph.preserveModules || this.canModuleBeFacade(exportNamesByVariable)) {
10673 this.facadeModule = module;
10674 module.facadeChunk = this;
10675 for (const [variable, exportNames] of exportNamesByVariable) {
10676 for (const exportName of exportNames) {
10677 this.exportNames[exportName] = variable;
10678 }
10679 }
10680 this.assignFacadeName(requiredFacades.shift(), module);
10681 }
10682 }
10683 for (const facadeName of requiredFacades) {
10684 facades.push(Chunk$1.generateFacade(this.graph, module, facadeName));
10685 }
10686 }
10687 return facades;
10688 }
10689 generateId(addons, options, existingNames, includeHash) {
10690 if (this.fileName !== null) {
10691 return this.fileName;
10692 }
10693 const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
10694 ? [options.entryFileNames || '[name].js', 'output.entryFileNames']
10695 : [options.chunkFileNames || '[name]-[hash].js', 'output.chunkFileNames'];
10696 return makeUnique(renderNamePattern(pattern, patternName, {
10697 format: () => (options.format === 'es' ? 'esm' : options.format),
10698 hash: () => includeHash
10699 ? this.computeContentHashWithDependencies(addons, options, existingNames)
10700 : '[hash]',
10701 name: () => this.getChunkName()
10702 }), existingNames);
10703 }
10704 generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames) {
10705 const id = this.orderedModules[0].id;
10706 const sanitizedId = sanitizeFileName(id);
10707 let path;
10708 if (isAbsolute(id)) {
10709 const extension = extname(id);
10710 const name = renderNamePattern(options.entryFileNames ||
10711 (NON_ASSET_EXTENSIONS.includes(extension) ? '[name].js' : '[name][extname].js'), 'output.entryFileNames', {
10712 ext: () => extension.substr(1),
10713 extname: () => extension,
10714 format: () => (options.format === 'es' ? 'esm' : options.format),
10715 name: () => this.getChunkName()
10716 });
10717 path = relative(preserveModulesRelativeDir, `${dirname(sanitizedId)}/${name}`);
10718 }
10719 else {
10720 path = `_virtual/${basename(sanitizedId)}`;
10721 }
10722 return makeUnique(normalize(path), existingNames);
10723 }
10724 generateInternalExports(options) {
10725 if (this.facadeModule !== null)
10726 return;
10727 const mangle = options.format === 'system' || options.format === 'es' || options.compact;
10728 let i = 0, safeExportName;
10729 this.exportNames = Object.create(null);
10730 this.sortedExportNames = null;
10731 if (mangle) {
10732 for (const variable of this.exports) {
10733 const suggestedName = variable.name[0];
10734 if (!this.exportNames[suggestedName]) {
10735 this.exportNames[suggestedName] = variable;
10736 }
10737 else {
10738 do {
10739 safeExportName = toBase64(++i);
10740 // skip past leading number identifiers
10741 if (safeExportName.charCodeAt(0) === 49 /* '1' */) {
10742 i += 9 * Math.pow(64, (safeExportName.length - 1));
10743 safeExportName = toBase64(i);
10744 }
10745 } while (RESERVED_NAMES[safeExportName] || this.exportNames[safeExportName]);
10746 this.exportNames[safeExportName] = variable;
10747 }
10748 }
10749 }
10750 else {
10751 for (const variable of this.exports) {
10752 i = 0;
10753 safeExportName = variable.name;
10754 while (this.exportNames[safeExportName]) {
10755 safeExportName = variable.name + '$' + ++i;
10756 }
10757 this.exportNames[safeExportName] = variable;
10758 }
10759 }
10760 }
10761 getChunkName() {
10762 return this.name || (this.name = sanitizeFileName(this.getFallbackChunkName()));
10763 }
10764 getDynamicImportIds() {
10765 return this.dynamicDependencies.map(chunk => chunk.id).filter(Boolean);
10766 }
10767 getExportNames() {
10768 return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportNames).sort()));
10769 }
10770 getImportIds() {
10771 return this.dependencies.map(chunk => chunk.id).filter(Boolean);
10772 }
10773 getRenderedHash() {
10774 if (this.renderedHash)
10775 return this.renderedHash;
10776 if (!this.renderedSource)
10777 return '';
10778 const hash = _256();
10779 const hashAugmentation = this.calculateHashAugmentation();
10780 hash.update(hashAugmentation);
10781 hash.update(this.renderedSource.toString());
10782 hash.update(this.getExportNames()
10783 .map(exportName => {
10784 const variable = this.exportNames[exportName];
10785 return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
10786 })
10787 .join(','));
10788 return (this.renderedHash = hash.digest('hex'));
10789 }
10790 getRenderedSourceLength() {
10791 if (this.renderedSourceLength !== undefined)
10792 return this.renderedSourceLength;
10793 return (this.renderedSourceLength = this.renderedSource.length());
10794 }
10795 getVariableExportName(variable) {
10796 if (this.graph.preserveModules && variable instanceof NamespaceVariable) {
10797 return '*';
10798 }
10799 for (const exportName of Object.keys(this.exportNames)) {
10800 if (this.exportNames[exportName] === variable)
10801 return exportName;
10802 }
10803 throw new Error(`Internal Error: Could not find export name for variable ${variable.name}.`);
10804 }
10805 link() {
10806 const dependencies = new Set();
10807 const dynamicDependencies = new Set();
10808 for (const module of this.orderedModules) {
10809 this.addDependenciesToChunk(module.getTransitiveDependencies(), dependencies);
10810 this.addDependenciesToChunk(module.dynamicDependencies, dynamicDependencies);
10811 this.setUpChunkImportsAndExportsForModule(module);
10812 }
10813 this.dependencies = Array.from(dependencies);
10814 this.dynamicDependencies = Array.from(dynamicDependencies);
10815 }
10816 /*
10817 * Performs a full merge of another chunk into this chunk
10818 * chunkList allows updating references in other chunks for the merged chunk to this chunk
10819 * A new facade will be added to chunkList if tainting exports of either as an entry point
10820 */
10821 merge(chunk, chunkList, options, inputBase) {
10822 if (this.facadeModule !== null || chunk.facadeModule !== null)
10823 throw new Error('Internal error: Code splitting chunk merges not supported for facades');
10824 for (const module of chunk.orderedModules) {
10825 module.chunk = this;
10826 this.orderedModules.push(module);
10827 }
10828 for (const variable of chunk.imports) {
10829 if (!this.imports.has(variable) && variable.module.chunk !== this) {
10830 this.imports.add(variable);
10831 }
10832 }
10833 // NB detect when exported variables are orphaned by the merge itself
10834 // (involves reverse tracing dependents)
10835 for (const variable of chunk.exports) {
10836 if (!this.exports.has(variable)) {
10837 this.exports.add(variable);
10838 }
10839 }
10840 const thisOldExportNames = this.exportNames;
10841 // regenerate internal names
10842 this.generateInternalExports(options);
10843 const updateRenderedDeclaration = (dep, oldExportNames) => {
10844 if (dep.imports) {
10845 for (const impt of dep.imports) {
10846 impt.imported = this.getVariableExportName(oldExportNames[impt.imported]);
10847 }
10848 }
10849 if (dep.reexports) {
10850 for (const reexport of dep.reexports) {
10851 reexport.imported = this.getVariableExportName(oldExportNames[reexport.imported]);
10852 }
10853 }
10854 };
10855 const mergeRenderedDeclaration = (into, from) => {
10856 if (from.imports) {
10857 if (!into.imports) {
10858 into.imports = from.imports;
10859 }
10860 else {
10861 into.imports = into.imports.concat(from.imports);
10862 }
10863 }
10864 if (from.reexports) {
10865 if (!into.reexports) {
10866 into.reexports = from.reexports;
10867 }
10868 else {
10869 into.reexports = into.reexports.concat(from.reexports);
10870 }
10871 }
10872 if (!into.exportsNames && from.exportsNames) {
10873 into.exportsNames = true;
10874 }
10875 if (!into.exportsDefault && from.exportsDefault) {
10876 into.exportsDefault = true;
10877 }
10878 into.name = this.variableName;
10879 };
10880 // go through the other chunks and update their dependencies
10881 // also update their import and reexport names in the process
10882 for (const c of chunkList) {
10883 let includedDeclaration = undefined;
10884 for (let i = 0; i < c.dependencies.length; i++) {
10885 const dep = c.dependencies[i];
10886 if ((dep === chunk || dep === this) && includedDeclaration) {
10887 const duplicateDeclaration = c.renderedDeclarations.dependencies[i];
10888 updateRenderedDeclaration(duplicateDeclaration, dep === chunk ? chunk.exportNames : thisOldExportNames);
10889 mergeRenderedDeclaration(includedDeclaration, duplicateDeclaration);
10890 c.renderedDeclarations.dependencies.splice(i, 1);
10891 c.dependencies.splice(i--, 1);
10892 }
10893 else if (dep === chunk) {
10894 c.dependencies[i] = this;
10895 includedDeclaration = c.renderedDeclarations.dependencies[i];
10896 updateRenderedDeclaration(includedDeclaration, chunk.exportNames);
10897 }
10898 else if (dep === this) {
10899 includedDeclaration = c.renderedDeclarations.dependencies[i];
10900 updateRenderedDeclaration(includedDeclaration, thisOldExportNames);
10901 }
10902 }
10903 }
10904 // re-render the merged chunk
10905 this.preRender(options, inputBase);
10906 }
10907 // prerender allows chunk hashes and names to be generated before finalizing
10908 preRender(options, inputBase) {
10909 timeStart('render modules', 3);
10910 const magicString = new Bundle({ separator: options.compact ? '' : '\n\n' });
10911 this.usedModules = [];
10912 this.indentString = options.compact ? '' : getIndentString(this.orderedModules, options);
10913 const n = options.compact ? '' : '\n';
10914 const _ = options.compact ? '' : ' ';
10915 const renderOptions = {
10916 compact: options.compact,
10917 dynamicImportFunction: options.dynamicImportFunction,
10918 format: options.format,
10919 freeze: options.freeze !== false,
10920 indent: this.indentString,
10921 namespaceToStringTag: options.namespaceToStringTag === true,
10922 varOrConst: options.preferConst ? 'const' : 'var'
10923 };
10924 // Make sure the direct dependencies of a chunk are present to maintain execution order
10925 for (const { module } of this.imports) {
10926 const chunkOrExternal = (module instanceof Module ? module.chunk : module);
10927 if (this.dependencies.indexOf(chunkOrExternal) === -1) {
10928 this.dependencies.push(chunkOrExternal);
10929 }
10930 }
10931 // for static and dynamic entry points, inline the execution list to avoid loading latency
10932 if (!this.graph.preserveModules && this.facadeModule !== null) {
10933 for (const dep of this.dependencies) {
10934 if (dep instanceof Chunk$1)
10935 this.inlineChunkDependencies(dep, true);
10936 }
10937 }
10938 // prune empty dependency chunks, inlining their side-effect dependencies
10939 for (let i = 0; i < this.dependencies.length; i++) {
10940 const dep = this.dependencies[i];
10941 if (dep instanceof Chunk$1 && dep.isEmpty) {
10942 this.dependencies.splice(i--, 1);
10943 this.inlineChunkDependencies(dep, false);
10944 }
10945 }
10946 sortByExecutionOrder(this.dependencies);
10947 this.prepareDynamicImports();
10948 this.setIdentifierRenderResolutions(options);
10949 let hoistedSource = '';
10950 const renderedModules = (this.renderedModules = Object.create(null));
10951 for (const module of this.orderedModules) {
10952 let renderedLength = 0;
10953 if (module.isIncluded()) {
10954 const source = module.render(renderOptions).trim();
10955 if (options.compact && source.lastLine().indexOf('//') !== -1)
10956 source.append('\n');
10957 const namespace = module.getOrCreateNamespace();
10958 if (namespace.included || source.length() > 0) {
10959 renderedLength = source.length();
10960 this.renderedModuleSources.set(module, source);
10961 magicString.addSource(source);
10962 this.usedModules.push(module);
10963 if (namespace.included && !this.graph.preserveModules) {
10964 const rendered = namespace.renderBlock(renderOptions);
10965 if (namespace.renderFirst())
10966 hoistedSource += n + rendered;
10967 else
10968 magicString.addSource(new MagicString(rendered));
10969 }
10970 }
10971 }
10972 const { renderedExports, removedExports } = module.getRenderedExports();
10973 renderedModules[module.id] = {
10974 originalLength: module.originalCode.length,
10975 removedExports,
10976 renderedExports,
10977 renderedLength
10978 };
10979 }
10980 if (hoistedSource)
10981 magicString.prepend(hoistedSource + n + n);
10982 if (this.needsExportsShim) {
10983 magicString.prepend(`${n}${renderOptions.varOrConst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
10984 }
10985 if (options.compact) {
10986 this.renderedSource = magicString;
10987 }
10988 else {
10989 this.renderedSource = magicString.trim();
10990 }
10991 this.renderedSourceLength = undefined;
10992 this.renderedHash = undefined;
10993 if (this.getExportNames().length === 0 && this.getImportIds().length === 0 && this.isEmpty) {
10994 this.graph.warn({
10995 code: 'EMPTY_BUNDLE',
10996 message: 'Generated an empty bundle'
10997 });
10998 }
10999 this.setExternalRenderPaths(options, inputBase);
11000 this.renderedDeclarations = {
11001 dependencies: this.getChunkDependencyDeclarations(options),
11002 exports: this.exportMode === 'none' ? [] : this.getChunkExportDeclarations()
11003 };
11004 timeEnd('render modules', 3);
11005 }
11006 render(options, addons, outputChunk) {
11007 timeStart('render format', 3);
11008 if (!this.renderedSource)
11009 throw new Error('Internal error: Chunk render called before preRender');
11010 const format = options.format;
11011 const finalise = finalisers[format];
11012 if (!finalise) {
11013 error({
11014 code: 'INVALID_OPTION',
11015 message: `Invalid format: ${format} - valid options are ${Object.keys(finalisers).join(', ')}.`
11016 });
11017 }
11018 if (options.dynamicImportFunction && format !== 'es') {
11019 this.graph.warn({
11020 code: 'INVALID_OPTION',
11021 message: '"output.dynamicImportFunction" is ignored for formats other than "esm".'
11022 });
11023 }
11024 // populate ids in the rendered declarations only here
11025 // as chunk ids known only after prerender
11026 for (let i = 0; i < this.dependencies.length; i++) {
11027 const dep = this.dependencies[i];
11028 if (dep instanceof ExternalModule && !dep.renormalizeRenderPath)
11029 continue;
11030 const renderedDependency = this.renderedDeclarations.dependencies[i];
11031 const depId = dep instanceof ExternalModule ? renderedDependency.id : dep.id;
11032 if (dep instanceof Chunk$1)
11033 renderedDependency.namedExportsMode = dep.exportMode !== 'default';
11034 renderedDependency.id = this.getRelativePath(depId);
11035 }
11036 this.finaliseDynamicImports(format);
11037 this.finaliseImportMetas(format);
11038 const hasExports = this.renderedDeclarations.exports.length !== 0 ||
11039 this.renderedDeclarations.dependencies.some(dep => (dep.reexports && dep.reexports.length !== 0));
11040 let usesTopLevelAwait = false;
11041 const accessedGlobals = new Set();
11042 for (const module of this.orderedModules) {
11043 if (module.usesTopLevelAwait) {
11044 usesTopLevelAwait = true;
11045 }
11046 const accessedGlobalVariablesByFormat = module.scope.accessedGlobalVariablesByFormat;
11047 const accessedGlobalVariables = accessedGlobalVariablesByFormat && accessedGlobalVariablesByFormat.get(format);
11048 if (accessedGlobalVariables) {
11049 for (const name of accessedGlobalVariables) {
11050 accessedGlobals.add(name);
11051 }
11052 }
11053 }
11054 if (usesTopLevelAwait && format !== 'es' && format !== 'system') {
11055 error({
11056 code: 'INVALID_TLA_FORMAT',
11057 message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
11058 });
11059 }
11060 const magicString = finalise(this.renderedSource, {
11061 accessedGlobals,
11062 dependencies: this.renderedDeclarations.dependencies,
11063 exports: this.renderedDeclarations.exports,
11064 hasExports,
11065 indentString: this.indentString,
11066 intro: addons.intro,
11067 isEntryModuleFacade: this.facadeModule !== null && this.facadeModule.isEntryPoint,
11068 namedExportsMode: this.exportMode !== 'default',
11069 outro: addons.outro,
11070 usesTopLevelAwait,
11071 varOrConst: options.preferConst ? 'const' : 'var',
11072 warn: this.graph.warn.bind(this.graph)
11073 }, options);
11074 if (addons.banner)
11075 magicString.prepend(addons.banner);
11076 if (addons.footer)
11077 magicString.append(addons.footer);
11078 const prevCode = magicString.toString();
11079 timeEnd('render format', 3);
11080 let map = null;
11081 const chunkSourcemapChain = [];
11082 return renderChunk({
11083 chunk: this,
11084 code: prevCode,
11085 graph: this.graph,
11086 options,
11087 renderChunk: outputChunk,
11088 sourcemapChain: chunkSourcemapChain
11089 }).then((code) => {
11090 if (options.sourcemap) {
11091 timeStart('sourcemap', 3);
11092 let file;
11093 if (options.file)
11094 file = resolve(options.sourcemapFile || options.file);
11095 else if (options.dir)
11096 file = resolve(options.dir, this.id);
11097 else
11098 file = resolve(this.id);
11099 const decodedMap = magicString.generateDecodedMap({});
11100 map = collapseSourcemaps(this, file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources);
11101 map.sources = map.sources.map(sourcePath => normalize(options.sourcemapPathTransform ? options.sourcemapPathTransform(sourcePath) : sourcePath));
11102 timeEnd('sourcemap', 3);
11103 }
11104 if (options.compact !== true && code[code.length - 1] !== '\n')
11105 code += '\n';
11106 return { code, map };
11107 });
11108 }
11109 visitDependencies(handleDependency) {
11110 const toBeVisited = [this];
11111 const visited = new Set();
11112 for (const current of toBeVisited) {
11113 handleDependency(current);
11114 if (current instanceof ExternalModule)
11115 continue;
11116 for (const dependency of current.dependencies.concat(current.dynamicDependencies)) {
11117 if (!visited.has(dependency)) {
11118 visited.add(dependency);
11119 toBeVisited.push(dependency);
11120 }
11121 }
11122 }
11123 }
11124 visitStaticDependenciesUntilCondition(isConditionSatisfied) {
11125 const seen = new Set();
11126 function visitDep(dep) {
11127 if (seen.has(dep))
11128 return undefined;
11129 seen.add(dep);
11130 if (dep instanceof Chunk$1) {
11131 for (const subDep of dep.dependencies) {
11132 if (visitDep(subDep))
11133 return true;
11134 }
11135 }
11136 return isConditionSatisfied(dep) === true;
11137 }
11138 return visitDep(this);
11139 }
11140 addDependenciesToChunk(moduleDependencies, chunkDependencies) {
11141 for (const depModule of moduleDependencies) {
11142 if (depModule.chunk === this) {
11143 continue;
11144 }
11145 let dependency;
11146 if (depModule instanceof Module) {
11147 dependency = depModule.chunk;
11148 }
11149 else {
11150 if (!(depModule.used || depModule.moduleSideEffects)) {
11151 continue;
11152 }
11153 dependency = depModule;
11154 }
11155 chunkDependencies.add(dependency);
11156 }
11157 }
11158 assignFacadeName({ fileName, name }, facadedModule) {
11159 if (fileName) {
11160 this.fileName = fileName;
11161 }
11162 else {
11163 this.name = sanitizeFileName(name || facadedModule.chunkName || getAliasName(facadedModule.id));
11164 }
11165 }
11166 calculateHashAugmentation() {
11167 const facadeModule = this.facadeModule;
11168 const getChunkName = this.getChunkName.bind(this);
11169 const preRenderedChunk = {
11170 dynamicImports: this.getDynamicImportIds(),
11171 exports: this.getExportNames(),
11172 facadeModuleId: facadeModule && facadeModule.id,
11173 imports: this.getImportIds(),
11174 isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0,
11175 isEntry: facadeModule !== null && facadeModule.isEntryPoint,
11176 modules: this.renderedModules,
11177 get name() {
11178 return getChunkName();
11179 }
11180 };
11181 const hashAugmentation = this.graph.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [preRenderedChunk], (hashAugmentation, pluginHash) => {
11182 if (pluginHash) {
11183 hashAugmentation += pluginHash;
11184 }
11185 return hashAugmentation;
11186 });
11187 return hashAugmentation;
11188 }
11189 computeContentHashWithDependencies(addons, options, existingNames) {
11190 const hash = _256();
11191 hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':'));
11192 hash.update(options.format);
11193 this.visitDependencies(dep => {
11194 if (dep instanceof ExternalModule) {
11195 hash.update(':' + dep.renderPath);
11196 }
11197 else {
11198 hash.update(dep.getRenderedHash());
11199 hash.update(dep.generateId(addons, options, existingNames, false));
11200 }
11201 });
11202 return hash.digest('hex').substr(0, 8);
11203 }
11204 finaliseDynamicImports(format) {
11205 for (const [module, code] of this.renderedModuleSources) {
11206 for (const { node, resolution } of module.dynamicImports) {
11207 if (!resolution)
11208 continue;
11209 if (resolution instanceof Module) {
11210 if (resolution.chunk !== this && isChunkRendered(resolution.chunk)) {
11211 const resolutionChunk = resolution.facadeChunk || resolution.chunk;
11212 node.renderFinalResolution(code, `'${this.getRelativePath(resolutionChunk.id)}'`, format);
11213 }
11214 }
11215 else {
11216 node.renderFinalResolution(code, resolution instanceof ExternalModule
11217 ? `'${resolution.renormalizeRenderPath
11218 ? this.getRelativePath(resolution.renderPath)
11219 : resolution.id}'`
11220 : resolution, format);
11221 }
11222 }
11223 }
11224 }
11225 finaliseImportMetas(format) {
11226 for (const [module, code] of this.renderedModuleSources) {
11227 for (const importMeta of module.importMetas) {
11228 importMeta.renderFinalMechanism(code, this.id, format, this.graph.pluginDriver);
11229 }
11230 }
11231 }
11232 getChunkDependencyDeclarations(options) {
11233 const reexportDeclarations = new Map();
11234 for (let exportName of this.getExportNames()) {
11235 let exportChunk;
11236 let importName;
11237 let needsLiveBinding = false;
11238 if (exportName[0] === '*') {
11239 needsLiveBinding = options.externalLiveBindings !== false;
11240 exportChunk = this.graph.moduleById.get(exportName.substr(1));
11241 importName = exportName = '*';
11242 }
11243 else {
11244 const variable = this.exportNames[exportName];
11245 const module = variable.module;
11246 // skip local exports
11247 if (!module || module.chunk === this)
11248 continue;
11249 if (module instanceof Module) {
11250 exportChunk = module.chunk;
11251 importName = exportChunk.getVariableExportName(variable);
11252 needsLiveBinding = variable.isReassigned;
11253 }
11254 else {
11255 exportChunk = module;
11256 importName = variable.name;
11257 needsLiveBinding = options.externalLiveBindings !== false;
11258 }
11259 }
11260 let reexportDeclaration = reexportDeclarations.get(exportChunk);
11261 if (!reexportDeclaration)
11262 reexportDeclarations.set(exportChunk, (reexportDeclaration = []));
11263 reexportDeclaration.push({ imported: importName, reexported: exportName, needsLiveBinding });
11264 }
11265 const renderedImports = new Set();
11266 const dependencies = [];
11267 for (const dep of this.dependencies) {
11268 const imports = [];
11269 for (const variable of this.imports) {
11270 const renderedVariable = variable instanceof ExportDefaultVariable ? variable.getOriginalVariable() : variable;
11271 if ((variable.module instanceof Module
11272 ? variable.module.chunk === dep
11273 : variable.module === dep) &&
11274 !renderedImports.has(renderedVariable)) {
11275 renderedImports.add(renderedVariable);
11276 imports.push({
11277 imported: variable.module instanceof ExternalModule
11278 ? variable.name
11279 : variable.module.chunk.getVariableExportName(variable),
11280 local: variable.getName()
11281 });
11282 }
11283 }
11284 const reexports = reexportDeclarations.get(dep);
11285 let exportsNames, exportsDefault;
11286 let namedExportsMode = true;
11287 if (dep instanceof ExternalModule) {
11288 exportsNames = dep.exportsNames || dep.exportsNamespace;
11289 exportsDefault = 'default' in dep.declarations;
11290 }
11291 else {
11292 exportsNames = true;
11293 // we don't want any interop patterns to trigger
11294 exportsDefault = false;
11295 namedExportsMode = dep.exportMode !== 'default';
11296 }
11297 let id = undefined;
11298 let globalName = undefined;
11299 if (dep instanceof ExternalModule) {
11300 id = dep.renderPath;
11301 if (options.format === 'umd' || options.format === 'iife') {
11302 globalName = getGlobalName(dep, options.globals, this.graph, exportsNames || exportsDefault);
11303 }
11304 }
11305 dependencies.push({
11306 exportsDefault,
11307 exportsNames,
11308 globalName,
11309 id,
11310 imports: imports.length > 0 ? imports : null,
11311 isChunk: dep instanceof Chunk$1,
11312 name: dep.variableName,
11313 namedExportsMode,
11314 reexports
11315 });
11316 }
11317 return dependencies;
11318 }
11319 getChunkExportDeclarations() {
11320 const exports = [];
11321 for (const exportName of this.getExportNames()) {
11322 if (exportName[0] === '*')
11323 continue;
11324 const variable = this.exportNames[exportName];
11325 const module = variable.module;
11326 if (module && module.chunk !== this)
11327 continue;
11328 let hoisted = false;
11329 let uninitialized = false;
11330 if (variable instanceof LocalVariable) {
11331 if (variable.init === UNDEFINED_EXPRESSION) {
11332 uninitialized = true;
11333 }
11334 for (const declaration of variable.declarations) {
11335 if (declaration.parent instanceof FunctionDeclaration ||
11336 (declaration instanceof ExportDefaultDeclaration &&
11337 declaration.declaration instanceof FunctionDeclaration)) {
11338 hoisted = true;
11339 break;
11340 }
11341 }
11342 }
11343 else if (variable instanceof GlobalVariable) {
11344 hoisted = true;
11345 }
11346 const localName = variable.getName();
11347 exports.push({
11348 exported: exportName === '*' ? localName : exportName,
11349 hoisted,
11350 local: localName,
11351 uninitialized
11352 });
11353 }
11354 return exports;
11355 }
11356 getFallbackChunkName() {
11357 if (this.manualChunkAlias) {
11358 return this.manualChunkAlias;
11359 }
11360 if (this.fileName) {
11361 return getAliasName(this.fileName);
11362 }
11363 return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
11364 }
11365 getRelativePath(targetPath) {
11366 const relativePath = normalize(relative(dirname(this.id), targetPath));
11367 return relativePath.startsWith('../') ? relativePath : './' + relativePath;
11368 }
11369 inlineChunkDependencies(chunk, deep) {
11370 for (const dep of chunk.dependencies) {
11371 if (dep instanceof ExternalModule) {
11372 if (this.dependencies.indexOf(dep) === -1)
11373 this.dependencies.push(dep);
11374 }
11375 else {
11376 if (dep === this || this.dependencies.indexOf(dep) !== -1)
11377 continue;
11378 if (!dep.isEmpty)
11379 this.dependencies.push(dep);
11380 if (deep)
11381 this.inlineChunkDependencies(dep, true);
11382 }
11383 }
11384 }
11385 prepareDynamicImports() {
11386 for (const module of this.orderedModules) {
11387 for (const { node, resolution } of module.dynamicImports) {
11388 if (!node.included)
11389 continue;
11390 if (resolution instanceof Module) {
11391 if (resolution.chunk === this) {
11392 const namespace = resolution.getOrCreateNamespace();
11393 node.setResolution('named', namespace);
11394 }
11395 else {
11396 node.setResolution(resolution.chunk.exportMode);
11397 }
11398 }
11399 else {
11400 node.setResolution('auto');
11401 }
11402 }
11403 }
11404 }
11405 setExternalRenderPaths(options, inputBase) {
11406 for (const dependency of this.dependencies.concat(this.dynamicDependencies)) {
11407 if (dependency instanceof ExternalModule) {
11408 dependency.setRenderPath(options, inputBase);
11409 }
11410 }
11411 }
11412 setIdentifierRenderResolutions(options) {
11413 for (const exportName of this.getExportNames()) {
11414 const exportVariable = this.exportNames[exportName];
11415 if (exportVariable) {
11416 if (exportVariable instanceof ExportShimVariable) {
11417 this.needsExportsShim = true;
11418 }
11419 exportVariable.exportName = exportName;
11420 if (options.format !== 'es' &&
11421 options.format !== 'system' &&
11422 exportVariable.isReassigned &&
11423 !exportVariable.isId &&
11424 !(exportVariable instanceof ExportDefaultVariable && exportVariable.hasId)) {
11425 exportVariable.setRenderNames('exports', exportName);
11426 }
11427 else {
11428 exportVariable.setRenderNames(null, null);
11429 }
11430 }
11431 }
11432 const usedNames = new Set();
11433 if (this.needsExportsShim) {
11434 usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
11435 }
11436 if (options.format !== 'es') {
11437 usedNames.add('exports');
11438 if (options.format === 'cjs') {
11439 usedNames
11440 .add(INTEROP_DEFAULT_VARIABLE)
11441 .add('require')
11442 .add('module')
11443 .add('__filename')
11444 .add('__dirname');
11445 }
11446 }
11447 deconflictChunk(this.orderedModules, this.dependencies, this.imports, usedNames, options.format, options.interop !== false, this.graph.preserveModules);
11448 }
11449 setUpChunkImportsAndExportsForModule(module) {
11450 for (const variable of module.imports) {
11451 if (variable.module.chunk !== this) {
11452 this.imports.add(variable);
11453 if (variable.module instanceof Module) {
11454 variable.module.chunk.exports.add(variable);
11455 }
11456 }
11457 }
11458 if (module.isEntryPoint ||
11459 module.dynamicallyImportedBy.some(importer => importer.chunk !== this)) {
11460 const map = module.getExportNamesByVariable();
11461 for (const exportedVariable of map.keys()) {
11462 this.exports.add(exportedVariable);
11463 const exportingModule = exportedVariable.module;
11464 if (exportingModule && exportingModule.chunk && exportingModule.chunk !== this) {
11465 exportingModule.chunk.exports.add(exportedVariable);
11466 }
11467 }
11468 }
11469 if (module.getOrCreateNamespace().included) {
11470 for (const reexportName of Object.keys(module.reexports)) {
11471 const reexport = module.reexports[reexportName];
11472 const variable = reexport.module.getVariableForExportName(reexport.localName);
11473 if (variable.module.chunk !== this) {
11474 this.imports.add(variable);
11475 if (variable.module instanceof Module) {
11476 variable.module.chunk.exports.add(variable);
11477 }
11478 }
11479 }
11480 }
11481 const context = createInclusionContext();
11482 for (const { node, resolution } of module.dynamicImports) {
11483 if (node.included && resolution instanceof Module && resolution.chunk === this)
11484 resolution.getOrCreateNamespace().include(context);
11485 }
11486 }
11487}
11488
11489/*
11490 * Given a chunk list, perform optimizations on that chunk list
11491 * to reduce the mumber of chunks. Mutates the chunks array.
11492 *
11493 * Manual chunks (with chunk.chunkAlias already set) are preserved
11494 * Entry points are carefully preserved as well
11495 *
11496 */
11497function optimizeChunks(chunks, options, CHUNK_GROUPING_SIZE, inputBase) {
11498 for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
11499 const mainChunk = chunks[chunkIndex];
11500 const execGroup = [];
11501 mainChunk.visitStaticDependenciesUntilCondition(dep => {
11502 if (dep instanceof Chunk$1) {
11503 execGroup.push(dep);
11504 }
11505 });
11506 if (execGroup.length < 2) {
11507 continue;
11508 }
11509 let execGroupIndex = 1;
11510 let seekingFirstMergeCandidate = true;
11511 let lastChunk = undefined, chunk = execGroup[0], nextChunk = execGroup[1];
11512 const isMergeCandidate = (chunk) => {
11513 if (chunk.facadeModule !== null || chunk.manualChunkAlias !== null) {
11514 return false;
11515 }
11516 if (!nextChunk || nextChunk.facadeModule !== null) {
11517 return false;
11518 }
11519 if (chunk.getRenderedSourceLength() > CHUNK_GROUPING_SIZE) {
11520 return false;
11521 }
11522 // if (!chunk.isPure()) continue;
11523 return true;
11524 };
11525 do {
11526 if (seekingFirstMergeCandidate) {
11527 if (isMergeCandidate(chunk)) {
11528 seekingFirstMergeCandidate = false;
11529 }
11530 continue;
11531 }
11532 let remainingSize = CHUNK_GROUPING_SIZE - lastChunk.getRenderedSourceLength() - chunk.getRenderedSourceLength();
11533 if (remainingSize <= 0) {
11534 if (!isMergeCandidate(chunk)) {
11535 seekingFirstMergeCandidate = true;
11536 }
11537 continue;
11538 }
11539 // if (!chunk.isPure()) continue;
11540 const chunkDependencies = new Set();
11541 chunk.visitStaticDependenciesUntilCondition(dep => chunkDependencies.add(dep));
11542 const ignoreSizeChunks = new Set([chunk, lastChunk]);
11543 if (lastChunk.visitStaticDependenciesUntilCondition(dep => {
11544 if (dep === chunk || dep === lastChunk) {
11545 return false;
11546 }
11547 if (chunkDependencies.has(dep)) {
11548 return false;
11549 }
11550 if (dep instanceof ExternalModule) {
11551 return true;
11552 }
11553 remainingSize -= dep.getRenderedSourceLength();
11554 if (remainingSize <= 0) {
11555 return true;
11556 }
11557 ignoreSizeChunks.add(dep);
11558 })) {
11559 if (!isMergeCandidate(chunk)) {
11560 seekingFirstMergeCandidate = true;
11561 }
11562 continue;
11563 }
11564 if (chunk.visitStaticDependenciesUntilCondition(dep => {
11565 if (ignoreSizeChunks.has(dep)) {
11566 return false;
11567 }
11568 if (dep instanceof ExternalModule) {
11569 return true;
11570 }
11571 remainingSize -= dep.getRenderedSourceLength();
11572 if (remainingSize <= 0) {
11573 return true;
11574 }
11575 })) {
11576 if (!isMergeCandidate(chunk)) {
11577 seekingFirstMergeCandidate = true;
11578 }
11579 continue;
11580 }
11581 // within the size limit -> merge!
11582 const optimizedChunkIndex = chunks.indexOf(chunk);
11583 if (optimizedChunkIndex <= chunkIndex)
11584 chunkIndex--;
11585 chunks.splice(optimizedChunkIndex, 1);
11586 lastChunk.merge(chunk, chunks, options, inputBase);
11587 execGroup.splice(--execGroupIndex, 1);
11588 chunk = lastChunk;
11589 // keep going to see if we can merge this with the next again
11590 if (nextChunk && !isMergeCandidate(nextChunk)) {
11591 seekingFirstMergeCandidate = true;
11592 }
11593 } while (((lastChunk = chunk), (chunk = nextChunk), (nextChunk = execGroup[++execGroupIndex]), chunk));
11594 }
11595 return chunks;
11596}
11597
11598const tt = acorn__default.tokTypes;
11599const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
11600const nextTokenIsDot = parser => {
11601 skipWhiteSpace.lastIndex = parser.pos;
11602 let skip = skipWhiteSpace.exec(parser.input);
11603 let next = parser.pos + skip[0].length;
11604 return parser.input.slice(next, next + 1) === ".";
11605};
11606var acornImportMeta = function (Parser) {
11607 return class extends Parser {
11608 parseExprAtom(refDestructuringErrors) {
11609 if (this.type !== tt._import || !nextTokenIsDot(this))
11610 return super.parseExprAtom(refDestructuringErrors);
11611 if (!this.options.allowImportExportEverywhere && !this.inModule) {
11612 this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
11613 }
11614 let node = this.startNode();
11615 node.meta = this.parseIdent(true);
11616 this.expect(tt.dot);
11617 node.property = this.parseIdent(true);
11618 if (node.property.name !== "meta") {
11619 this.raiseRecoverable(node.property.start, "The only valid meta property for import is import.meta");
11620 }
11621 if (this.containsEsc) {
11622 this.raiseRecoverable(node.property.start, "\"meta\" in import.meta must not contain escape sequences");
11623 }
11624 return this.finishNode(node, "MetaProperty");
11625 }
11626 parseStatement(context, topLevel, exports) {
11627 if (this.type !== tt._import || !nextTokenIsDot(this)) {
11628 return super.parseStatement(context, topLevel, exports);
11629 }
11630 let node = this.startNode();
11631 let expr = this.parseExpression();
11632 return this.parseExpressionStatement(node, expr);
11633 }
11634 };
11635};
11636
11637class UndefinedVariable extends Variable {
11638 constructor() {
11639 super('undefined');
11640 }
11641 getLiteralValueAtPath() {
11642 return undefined;
11643 }
11644}
11645
11646class GlobalScope extends Scope {
11647 constructor() {
11648 super();
11649 this.variables.set('undefined', new UndefinedVariable());
11650 }
11651 findVariable(name) {
11652 let variable = this.variables.get(name);
11653 if (!variable) {
11654 variable = new GlobalVariable(name);
11655 this.variables.set(name, variable);
11656 }
11657 return variable;
11658 }
11659}
11660
11661var BuildPhase;
11662(function (BuildPhase) {
11663 BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
11664 BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
11665 BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
11666})(BuildPhase || (BuildPhase = {}));
11667
11668function generateAssetFileName(name, source, output) {
11669 const emittedName = name || 'asset';
11670 return makeUnique(renderNamePattern(output.assetFileNames, 'output.assetFileNames', {
11671 hash() {
11672 const hash = _256();
11673 hash.update(emittedName);
11674 hash.update(':');
11675 hash.update(source);
11676 return hash.digest('hex').substr(0, 8);
11677 },
11678 ext: () => extname(emittedName).substr(1),
11679 extname: () => extname(emittedName),
11680 name: () => emittedName.substr(0, emittedName.length - extname(emittedName).length)
11681 }), output.bundle);
11682}
11683function reserveFileNameInBundle(fileName, bundle) {
11684 // TODO this should warn if the fileName is already in the bundle,
11685 // but until #3174 is fixed, this raises spurious warnings and is disabled
11686 bundle[fileName] = FILE_PLACEHOLDER;
11687}
11688const FILE_PLACEHOLDER = {
11689 type: 'placeholder'
11690};
11691function hasValidType(emittedFile) {
11692 return (emittedFile &&
11693 (emittedFile.type === 'asset' ||
11694 emittedFile.type === 'chunk'));
11695}
11696function hasValidName(emittedFile) {
11697 const validatedName = emittedFile.fileName || emittedFile.name;
11698 return (!validatedName || (typeof validatedName === 'string' && isPlainPathFragment(validatedName)));
11699}
11700function getValidSource(source, emittedFile, fileReferenceId) {
11701 if (typeof source !== 'string' && !Buffer.isBuffer(source)) {
11702 const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
11703 return error(errFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string of Buffer.`));
11704 }
11705 return source;
11706}
11707function getAssetFileName(file, referenceId) {
11708 if (typeof file.fileName !== 'string') {
11709 return error(errAssetNotFinalisedForFileName(file.name || referenceId));
11710 }
11711 return file.fileName;
11712}
11713function getChunkFileName(file) {
11714 const fileName = file.fileName || (file.module && file.module.facadeChunk.id);
11715 if (!fileName)
11716 return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
11717 return fileName;
11718}
11719class FileEmitter {
11720 constructor(graph) {
11721 this.filesByReferenceId = new Map();
11722 // tslint:disable member-ordering
11723 this.buildFilesByReferenceId = this.filesByReferenceId;
11724 this.output = null;
11725 this.emitFile = (emittedFile) => {
11726 if (!hasValidType(emittedFile)) {
11727 return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile &&
11728 emittedFile.type}".`));
11729 }
11730 if (!hasValidName(emittedFile)) {
11731 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 ||
11732 emittedFile.name}".`));
11733 }
11734 if (emittedFile.type === 'chunk') {
11735 return this.emitChunk(emittedFile);
11736 }
11737 else {
11738 return this.emitAsset(emittedFile);
11739 }
11740 };
11741 this.getFileName = (fileReferenceId) => {
11742 const emittedFile = this.filesByReferenceId.get(fileReferenceId);
11743 if (!emittedFile)
11744 return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
11745 if (emittedFile.type === 'chunk') {
11746 return getChunkFileName(emittedFile);
11747 }
11748 else {
11749 return getAssetFileName(emittedFile, fileReferenceId);
11750 }
11751 };
11752 this.setAssetSource = (referenceId, requestedSource) => {
11753 const consumedFile = this.filesByReferenceId.get(referenceId);
11754 if (!consumedFile)
11755 return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
11756 if (consumedFile.type !== 'asset') {
11757 return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
11758 }
11759 if (consumedFile.source !== undefined) {
11760 return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
11761 }
11762 const source = getValidSource(requestedSource, consumedFile, referenceId);
11763 if (this.output) {
11764 this.finalizeAsset(consumedFile, source, referenceId, this.output);
11765 }
11766 else {
11767 consumedFile.source = source;
11768 }
11769 };
11770 this.graph = graph;
11771 }
11772 startOutput(outputBundle, assetFileNames) {
11773 this.filesByReferenceId = new Map(this.buildFilesByReferenceId);
11774 this.output = {
11775 assetFileNames,
11776 bundle: outputBundle
11777 };
11778 for (const emittedFile of this.filesByReferenceId.values()) {
11779 if (emittedFile.fileName) {
11780 reserveFileNameInBundle(emittedFile.fileName, this.output.bundle);
11781 }
11782 }
11783 for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) {
11784 if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
11785 this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.output);
11786 }
11787 }
11788 }
11789 assertAssetsFinalized() {
11790 for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) {
11791 if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
11792 error(errNoAssetSourceSet(emittedFile.name || referenceId));
11793 }
11794 }
11795 emitAsset(emittedAsset) {
11796 const source = typeof emittedAsset.source !== 'undefined'
11797 ? getValidSource(emittedAsset.source, emittedAsset, null)
11798 : undefined;
11799 const consumedAsset = {
11800 fileName: emittedAsset.fileName,
11801 name: emittedAsset.name,
11802 source,
11803 type: 'asset'
11804 };
11805 const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
11806 if (this.output) {
11807 if (emittedAsset.fileName) {
11808 reserveFileNameInBundle(emittedAsset.fileName, this.output.bundle);
11809 }
11810 if (source !== undefined) {
11811 this.finalizeAsset(consumedAsset, source, referenceId, this.output);
11812 }
11813 }
11814 return referenceId;
11815 }
11816 emitChunk(emittedChunk) {
11817 if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
11818 error(errInvalidRollupPhaseForChunkEmission());
11819 }
11820 if (typeof emittedChunk.id !== 'string') {
11821 return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
11822 }
11823 const consumedChunk = {
11824 fileName: emittedChunk.fileName,
11825 module: null,
11826 name: emittedChunk.name || emittedChunk.id,
11827 type: 'chunk'
11828 };
11829 this.graph.moduleLoader
11830 .addEntryModules([
11831 {
11832 fileName: emittedChunk.fileName || null,
11833 id: emittedChunk.id,
11834 name: emittedChunk.name || null
11835 }
11836 ], false)
11837 .then(({ newEntryModules: [module] }) => {
11838 consumedChunk.module = module;
11839 })
11840 .catch(() => {
11841 // Avoid unhandled Promise rejection as the error will be thrown later
11842 // once module loading has finished
11843 });
11844 return this.assignReferenceId(consumedChunk, emittedChunk.id);
11845 }
11846 assignReferenceId(file, idBase) {
11847 let referenceId;
11848 do {
11849 const hash = _256();
11850 if (referenceId) {
11851 hash.update(referenceId);
11852 }
11853 else {
11854 hash.update(idBase);
11855 }
11856 referenceId = hash.digest('hex').substr(0, 8);
11857 } while (this.filesByReferenceId.has(referenceId));
11858 this.filesByReferenceId.set(referenceId, file);
11859 return referenceId;
11860 }
11861 finalizeAsset(consumedFile, source, referenceId, output) {
11862 const fileName = consumedFile.fileName ||
11863 this.findExistingAssetFileNameWithSource(output.bundle, source) ||
11864 generateAssetFileName(consumedFile.name, source, output);
11865 // We must not modify the original assets to avoid interaction between outputs
11866 const assetWithFileName = Object.assign(Object.assign({}, consumedFile), { source, fileName });
11867 this.filesByReferenceId.set(referenceId, assetWithFileName);
11868 const graph = this.graph;
11869 output.bundle[fileName] = {
11870 fileName,
11871 get isAsset() {
11872 graph.warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', false);
11873 return true;
11874 },
11875 source,
11876 type: 'asset'
11877 };
11878 }
11879 findExistingAssetFileNameWithSource(bundle, source) {
11880 for (const fileName of Object.keys(bundle)) {
11881 const outputFile = bundle[fileName];
11882 if (outputFile.type === 'asset' &&
11883 (Buffer.isBuffer(source) && Buffer.isBuffer(outputFile.source)
11884 ? source.equals(outputFile.source)
11885 : source === outputFile.source))
11886 return fileName;
11887 }
11888 return null;
11889 }
11890}
11891
11892const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
11893const deprecatedHooks = [
11894 { active: true, deprecated: 'ongenerate', replacement: 'generateBundle' },
11895 { active: true, deprecated: 'onwrite', replacement: 'generateBundle/writeBundle' },
11896 { active: true, deprecated: 'transformBundle', replacement: 'renderChunk' },
11897 { active: true, deprecated: 'transformChunk', replacement: 'renderChunk' },
11898 { active: false, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
11899];
11900function warnDeprecatedHooks(plugins, graph) {
11901 for (const { active, deprecated, replacement } of deprecatedHooks) {
11902 for (const plugin of plugins) {
11903 if (deprecated in plugin) {
11904 graph.warnDeprecation({
11905 message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
11906 plugin: plugin.name
11907 }, active);
11908 }
11909 }
11910 }
11911}
11912function throwPluginError(err, plugin, { hook, id } = {}) {
11913 if (typeof err === 'string')
11914 err = { message: err };
11915 if (err.code && err.code !== Errors.PLUGIN_ERROR) {
11916 err.pluginCode = err.code;
11917 }
11918 err.code = Errors.PLUGIN_ERROR;
11919 err.plugin = plugin;
11920 if (hook) {
11921 err.hook = hook;
11922 }
11923 if (id) {
11924 err.id = id;
11925 }
11926 return error(err);
11927}
11928function createPluginDriver(graph, options, pluginCache, watcher) {
11929 warnDeprecatedHooks(options.plugins, graph);
11930 function getDeprecatedHookHandler(handler, handlerName, newHandlerName, pluginName, acitveDeprecation) {
11931 let deprecationWarningShown = false;
11932 return ((...args) => {
11933 if (!deprecationWarningShown) {
11934 deprecationWarningShown = true;
11935 graph.warnDeprecation({
11936 message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
11937 plugin: pluginName
11938 }, acitveDeprecation);
11939 }
11940 return handler(...args);
11941 });
11942 }
11943 const plugins = [
11944 ...options.plugins,
11945 getRollupDefaultPlugin(options.preserveSymlinks)
11946 ];
11947 const fileEmitter = new FileEmitter(graph);
11948 const existingPluginKeys = new Set();
11949 const pluginContexts = plugins.map((plugin, pidx) => {
11950 let cacheable = true;
11951 if (typeof plugin.cacheKey !== 'string') {
11952 if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) || existingPluginKeys.has(plugin.name)) {
11953 cacheable = false;
11954 }
11955 else {
11956 existingPluginKeys.add(plugin.name);
11957 }
11958 }
11959 let cacheInstance;
11960 if (!pluginCache) {
11961 cacheInstance = noCache;
11962 }
11963 else if (cacheable) {
11964 const cacheKey = plugin.cacheKey || plugin.name;
11965 cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
11966 }
11967 else {
11968 cacheInstance = uncacheablePlugin(plugin.name);
11969 }
11970 const context = {
11971 addWatchFile(id) {
11972 if (graph.phase >= BuildPhase.GENERATE)
11973 this.error(errInvalidRollupPhaseForAddWatchFile());
11974 graph.watchFiles[id] = true;
11975 },
11976 cache: cacheInstance,
11977 emitAsset: getDeprecatedHookHandler((name, source) => fileEmitter.emitFile({ type: 'asset', name, source }), 'emitAsset', 'emitFile', plugin.name, false),
11978 emitChunk: getDeprecatedHookHandler((id, options) => fileEmitter.emitFile({ type: 'chunk', id, name: options && options.name }), 'emitChunk', 'emitFile', plugin.name, false),
11979 emitFile: fileEmitter.emitFile,
11980 error(err) {
11981 return throwPluginError(err, plugin.name);
11982 },
11983 getAssetFileName: getDeprecatedHookHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, false),
11984 getChunkFileName: getDeprecatedHookHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, false),
11985 getFileName: fileEmitter.getFileName,
11986 getModuleInfo(moduleId) {
11987 const foundModule = graph.moduleById.get(moduleId);
11988 if (foundModule == null) {
11989 throw new Error(`Unable to find module ${moduleId}`);
11990 }
11991 return {
11992 hasModuleSideEffects: foundModule.moduleSideEffects,
11993 id: foundModule.id,
11994 importedIds: foundModule instanceof ExternalModule
11995 ? []
11996 : foundModule.sources.map(id => foundModule.resolvedIds[id].id),
11997 isEntry: foundModule instanceof Module && foundModule.isEntryPoint,
11998 isExternal: foundModule instanceof ExternalModule
11999 };
12000 },
12001 isExternal: getDeprecatedHookHandler((id, parentId, isResolved = false) => graph.moduleLoader.isExternal(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, false),
12002 meta: {
12003 rollupVersion: version
12004 },
12005 get moduleIds() {
12006 return graph.moduleById.keys();
12007 },
12008 parse: graph.contextParse,
12009 resolve(source, importer, options) {
12010 return graph.moduleLoader.resolveId(source, importer, options && options.skipSelf ? pidx : null);
12011 },
12012 resolveId: getDeprecatedHookHandler((source, importer) => graph.moduleLoader
12013 .resolveId(source, importer)
12014 .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, false),
12015 setAssetSource: fileEmitter.setAssetSource,
12016 warn(warning) {
12017 if (typeof warning === 'string')
12018 warning = { message: warning };
12019 if (warning.code)
12020 warning.pluginCode = warning.code;
12021 warning.code = 'PLUGIN_WARNING';
12022 warning.plugin = plugin.name;
12023 graph.warn(warning);
12024 },
12025 watcher: watcher
12026 ? (() => {
12027 let deprecationWarningShown = false;
12028 function deprecatedWatchListener(event, handler) {
12029 if (!deprecationWarningShown) {
12030 context.warn({
12031 code: 'PLUGIN_WATCHER_DEPRECATED',
12032 message: `this.watcher usage is deprecated in plugins. Use the watchChange plugin hook and this.addWatchFile() instead.`
12033 });
12034 deprecationWarningShown = true;
12035 }
12036 return watcher.on(event, handler);
12037 }
12038 return Object.assign(Object.assign({}, watcher), { addListener: deprecatedWatchListener, on: deprecatedWatchListener });
12039 })()
12040 : undefined
12041 };
12042 return context;
12043 });
12044 function runHookSync(hookName, args, pluginIndex, permitValues = false, hookContext) {
12045 const plugin = plugins[pluginIndex];
12046 let context = pluginContexts[pluginIndex];
12047 const hook = plugin[hookName];
12048 if (!hook)
12049 return undefined;
12050 if (hookContext) {
12051 context = hookContext(context, plugin);
12052 if (!context || context === pluginContexts[pluginIndex])
12053 throw new Error('Internal Rollup error: hookContext must return a new context object.');
12054 }
12055 try {
12056 // permit values allows values to be returned instead of a functional hook
12057 if (typeof hook !== 'function') {
12058 if (permitValues)
12059 return hook;
12060 error({
12061 code: 'INVALID_PLUGIN_HOOK',
12062 message: `Error running plugin hook ${hookName} for ${plugin.name}, expected a function hook.`
12063 });
12064 }
12065 return hook.apply(context, args);
12066 }
12067 catch (err) {
12068 return throwPluginError(err, plugin.name, { hook: hookName });
12069 }
12070 }
12071 function runHook(hookName, args, pluginIndex, permitValues = false, hookContext) {
12072 const plugin = plugins[pluginIndex];
12073 let context = pluginContexts[pluginIndex];
12074 const hook = plugin[hookName];
12075 if (!hook)
12076 return undefined;
12077 if (hookContext) {
12078 context = hookContext(context, plugin);
12079 if (!context || context === pluginContexts[pluginIndex])
12080 throw new Error('Internal Rollup error: hookContext must return a new context object.');
12081 }
12082 return Promise.resolve()
12083 .then(() => {
12084 // permit values allows values to be returned instead of a functional hook
12085 if (typeof hook !== 'function') {
12086 if (permitValues)
12087 return hook;
12088 error({
12089 code: 'INVALID_PLUGIN_HOOK',
12090 message: `Error running plugin hook ${hookName} for ${plugin.name}, expected a function hook.`
12091 });
12092 }
12093 return hook.apply(context, args);
12094 })
12095 .catch(err => throwPluginError(err, plugin.name, { hook: hookName }));
12096 }
12097 const pluginDriver = {
12098 emitFile: fileEmitter.emitFile,
12099 finaliseAssets() {
12100 fileEmitter.assertAssetsFinalized();
12101 },
12102 getFileName: fileEmitter.getFileName,
12103 // chains, ignores returns
12104 hookSeq(name, args, hookContext) {
12105 let promise = Promise.resolve();
12106 for (let i = 0; i < plugins.length; i++)
12107 promise = promise.then(() => runHook(name, args, i, false, hookContext));
12108 return promise;
12109 },
12110 // chains, ignores returns
12111 hookSeqSync(name, args, hookContext) {
12112 for (let i = 0; i < plugins.length; i++)
12113 runHookSync(name, args, i, false, hookContext);
12114 },
12115 // chains, first non-null result stops and returns
12116 hookFirst(name, args, hookContext, skip) {
12117 let promise = Promise.resolve();
12118 for (let i = 0; i < plugins.length; i++) {
12119 if (skip === i)
12120 continue;
12121 promise = promise.then((result) => {
12122 if (result != null)
12123 return result;
12124 return runHook(name, args, i, false, hookContext);
12125 });
12126 }
12127 return promise;
12128 },
12129 // chains synchronously, first non-null result stops and returns
12130 hookFirstSync(name, args, hookContext) {
12131 for (let i = 0; i < plugins.length; i++) {
12132 const result = runHookSync(name, args, i, false, hookContext);
12133 if (result != null)
12134 return result;
12135 }
12136 return null;
12137 },
12138 // parallel, ignores returns
12139 hookParallel(name, args, hookContext) {
12140 const promises = [];
12141 for (let i = 0; i < plugins.length; i++) {
12142 const hookPromise = runHook(name, args, i, false, hookContext);
12143 if (!hookPromise)
12144 continue;
12145 promises.push(hookPromise);
12146 }
12147 return Promise.all(promises).then(() => { });
12148 },
12149 // chains, reduces returns of type R, to type T, handling the reduced value as the first hook argument
12150 hookReduceArg0(name, [arg0, ...args], reduce, hookContext) {
12151 let promise = Promise.resolve(arg0);
12152 for (let i = 0; i < plugins.length; i++) {
12153 promise = promise.then(arg0 => {
12154 const hookPromise = runHook(name, [arg0, ...args], i, false, hookContext);
12155 if (!hookPromise)
12156 return arg0;
12157 return hookPromise.then((result) => reduce.call(pluginContexts[i], arg0, result, plugins[i]));
12158 });
12159 }
12160 return promise;
12161 },
12162 // chains synchronously, reduces returns of type R, to type T, handling the reduced value as the first hook argument
12163 hookReduceArg0Sync(name, [arg0, ...args], reduce, hookContext) {
12164 for (let i = 0; i < plugins.length; i++) {
12165 const result = runHookSync(name, [arg0, ...args], i, false, hookContext);
12166 arg0 = reduce.call(pluginContexts[i], arg0, result, plugins[i]);
12167 }
12168 return arg0;
12169 },
12170 // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values.
12171 hookReduceValue(name, initial, args, reduce, hookContext) {
12172 let promise = Promise.resolve(initial);
12173 for (let i = 0; i < plugins.length; i++) {
12174 promise = promise.then(value => {
12175 const hookPromise = runHook(name, args, i, true, hookContext);
12176 if (!hookPromise)
12177 return value;
12178 return hookPromise.then((result) => reduce.call(pluginContexts[i], value, result, plugins[i]));
12179 });
12180 }
12181 return promise;
12182 },
12183 // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values.
12184 hookReduceValueSync(name, initial, args, reduce, hookContext) {
12185 let acc = initial;
12186 for (let i = 0; i < plugins.length; i++) {
12187 const result = runHookSync(name, args, i, true, hookContext);
12188 acc = reduce.call(pluginContexts[i], acc, result, plugins[i]);
12189 }
12190 return acc;
12191 },
12192 startOutput(outputBundle, assetFileNames) {
12193 fileEmitter.startOutput(outputBundle, assetFileNames);
12194 }
12195 };
12196 return pluginDriver;
12197}
12198function createPluginCache(cache) {
12199 return {
12200 has(id) {
12201 const item = cache[id];
12202 if (!item)
12203 return false;
12204 item[0] = 0;
12205 return true;
12206 },
12207 get(id) {
12208 const item = cache[id];
12209 if (!item)
12210 return undefined;
12211 item[0] = 0;
12212 return item[1];
12213 },
12214 set(id, value) {
12215 cache[id] = [0, value];
12216 },
12217 delete(id) {
12218 return delete cache[id];
12219 }
12220 };
12221}
12222function trackPluginCache(pluginCache) {
12223 const result = { used: false, cache: undefined };
12224 result.cache = {
12225 has(id) {
12226 result.used = true;
12227 return pluginCache.has(id);
12228 },
12229 get(id) {
12230 result.used = true;
12231 return pluginCache.get(id);
12232 },
12233 set(id, value) {
12234 result.used = true;
12235 return pluginCache.set(id, value);
12236 },
12237 delete(id) {
12238 result.used = true;
12239 return pluginCache.delete(id);
12240 }
12241 };
12242 return result;
12243}
12244const noCache = {
12245 has() {
12246 return false;
12247 },
12248 get() {
12249 return undefined;
12250 },
12251 set() { },
12252 delete() {
12253 return false;
12254 }
12255};
12256function uncacheablePluginError(pluginName) {
12257 if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX))
12258 error({
12259 code: 'ANONYMOUS_PLUGIN_CACHE',
12260 message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
12261 });
12262 else
12263 error({
12264 code: 'DUPLICATE_PLUGIN_NAME',
12265 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).`
12266 });
12267}
12268const uncacheablePlugin = pluginName => ({
12269 has() {
12270 uncacheablePluginError(pluginName);
12271 return false;
12272 },
12273 get() {
12274 uncacheablePluginError(pluginName);
12275 return undefined;
12276 },
12277 set() {
12278 uncacheablePluginError(pluginName);
12279 },
12280 delete() {
12281 uncacheablePluginError(pluginName);
12282 return false;
12283 }
12284});
12285
12286function transform(graph, source, module) {
12287 const id = module.id;
12288 const sourcemapChain = [];
12289 let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
12290 const originalCode = source.code;
12291 let ast = source.ast;
12292 const transformDependencies = [];
12293 const emittedFiles = [];
12294 let customTransformCache = false;
12295 let moduleSideEffects = null;
12296 let trackedPluginCache;
12297 let curPlugin;
12298 const curSource = source.code;
12299 function transformReducer(code, result, plugin) {
12300 // track which plugins use the custom this.cache to opt-out of transform caching
12301 if (!customTransformCache && trackedPluginCache.used)
12302 customTransformCache = true;
12303 if (customTransformCache) {
12304 if (result && typeof result === 'object' && Array.isArray(result.dependencies)) {
12305 for (const dep of result.dependencies) {
12306 graph.watchFiles[resolve(dirname(id), dep)] = true;
12307 }
12308 }
12309 }
12310 else {
12311 // files emitted by a transform hook need to be emitted again if the hook is skipped
12312 if (emittedFiles.length)
12313 module.transformFiles = emittedFiles;
12314 if (result && typeof result === 'object' && Array.isArray(result.dependencies)) {
12315 // not great, but a useful way to track this without assuming WeakMap
12316 if (!curPlugin.warnedTransformDependencies)
12317 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);
12318 curPlugin.warnedTransformDependencies = true;
12319 for (const dep of result.dependencies)
12320 transformDependencies.push(resolve(dirname(id), dep));
12321 }
12322 }
12323 if (typeof result === 'string') {
12324 result = {
12325 ast: undefined,
12326 code: result,
12327 map: undefined
12328 };
12329 }
12330 else if (result && typeof result === 'object') {
12331 if (typeof result.map === 'string') {
12332 result.map = JSON.parse(result.map);
12333 }
12334 if (typeof result.moduleSideEffects === 'boolean') {
12335 moduleSideEffects = result.moduleSideEffects;
12336 }
12337 }
12338 else {
12339 return code;
12340 }
12341 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
12342 if (result.map !== null) {
12343 const map = decodedSourcemap(result.map);
12344 sourcemapChain.push(map || { missing: true, plugin: plugin.name });
12345 }
12346 ast = result.ast;
12347 return result.code;
12348 }
12349 let setAssetSourceErr;
12350 return graph.pluginDriver
12351 .hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
12352 curPlugin = plugin;
12353 if (curPlugin.cacheKey)
12354 customTransformCache = true;
12355 else
12356 trackedPluginCache = trackPluginCache(pluginContext.cache);
12357 return Object.assign(Object.assign({}, pluginContext), { cache: trackedPluginCache ? trackedPluginCache.cache : pluginContext.cache, warn(warning, pos) {
12358 if (typeof warning === 'string')
12359 warning = { message: warning };
12360 if (pos)
12361 augmentCodeLocation(warning, pos, curSource, id);
12362 warning.id = id;
12363 warning.hook = 'transform';
12364 pluginContext.warn(warning);
12365 },
12366 error(err, pos) {
12367 if (typeof err === 'string')
12368 err = { message: err };
12369 if (pos)
12370 augmentCodeLocation(err, pos, curSource, id);
12371 err.id = id;
12372 err.hook = 'transform';
12373 return pluginContext.error(err);
12374 },
12375 emitAsset(name, source) {
12376 const emittedFile = { type: 'asset', name, source };
12377 emittedFiles.push(Object.assign({}, emittedFile));
12378 return graph.pluginDriver.emitFile(emittedFile);
12379 },
12380 emitChunk(id, options) {
12381 const emittedFile = { type: 'chunk', id, name: options && options.name };
12382 emittedFiles.push(Object.assign({}, emittedFile));
12383 return graph.pluginDriver.emitFile(emittedFile);
12384 },
12385 emitFile(emittedFile) {
12386 emittedFiles.push(emittedFile);
12387 return graph.pluginDriver.emitFile(emittedFile);
12388 },
12389 addWatchFile(id) {
12390 transformDependencies.push(id);
12391 pluginContext.addWatchFile(id);
12392 },
12393 setAssetSource(assetReferenceId, source) {
12394 pluginContext.setAssetSource(assetReferenceId, source);
12395 if (!customTransformCache && !setAssetSourceErr) {
12396 try {
12397 this.error({
12398 code: 'INVALID_SETASSETSOURCE',
12399 message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
12400 });
12401 }
12402 catch (err) {
12403 setAssetSourceErr = err;
12404 }
12405 }
12406 },
12407 getCombinedSourcemap() {
12408 const combinedMap = collapseSourcemap(graph, id, originalCode, originalSourcemap, sourcemapChain);
12409 if (!combinedMap) {
12410 const magicString = new MagicString(originalCode);
12411 return magicString.generateMap({ includeContent: true, hires: true, source: id });
12412 }
12413 if (originalSourcemap !== combinedMap) {
12414 originalSourcemap = combinedMap;
12415 sourcemapChain.length = 0;
12416 }
12417 return new SourceMap(Object.assign(Object.assign({}, combinedMap), { file: null, sourcesContent: combinedMap.sourcesContent }));
12418 } });
12419 })
12420 .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id }))
12421 .then(code => {
12422 if (!customTransformCache && setAssetSourceErr)
12423 throw setAssetSourceErr;
12424 return {
12425 ast: ast,
12426 code,
12427 customTransformCache,
12428 moduleSideEffects,
12429 originalCode,
12430 originalSourcemap,
12431 sourcemapChain,
12432 transformDependencies
12433 };
12434 });
12435}
12436
12437function normalizeRelativeExternalId(importer, source) {
12438 return isRelative(source) ? resolve(importer, '..', source) : source;
12439}
12440function getIdMatcher(option) {
12441 if (option === true) {
12442 return () => true;
12443 }
12444 if (typeof option === 'function') {
12445 return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
12446 }
12447 if (option) {
12448 const ids = new Set(Array.isArray(option) ? option : option ? [option] : []);
12449 return (id => ids.has(id));
12450 }
12451 return () => false;
12452}
12453function getHasModuleSideEffects(moduleSideEffectsOption, pureExternalModules, graph) {
12454 if (typeof moduleSideEffectsOption === 'boolean') {
12455 return () => moduleSideEffectsOption;
12456 }
12457 if (moduleSideEffectsOption === 'no-external') {
12458 return (_id, external) => !external;
12459 }
12460 if (typeof moduleSideEffectsOption === 'function') {
12461 return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
12462 }
12463 if (Array.isArray(moduleSideEffectsOption)) {
12464 const ids = new Set(moduleSideEffectsOption);
12465 return id => ids.has(id);
12466 }
12467 if (moduleSideEffectsOption) {
12468 graph.warn(errInvalidOption('treeshake.moduleSideEffects', 'please use one of false, "no-external", a function or an array'));
12469 }
12470 const isPureExternalModule = getIdMatcher(pureExternalModules);
12471 return (id, external) => !(external && isPureExternalModule(id));
12472}
12473class ModuleLoader {
12474 constructor(graph, modulesById, pluginDriver, external, getManualChunk, moduleSideEffects, pureExternalModules) {
12475 this.indexedEntryModules = [];
12476 this.latestLoadModulesPromise = Promise.resolve();
12477 this.manualChunkModules = {};
12478 this.nextEntryModuleIndex = 0;
12479 this.loadEntryModule = (unresolvedId, isEntry) => this.pluginDriver.hookFirst('resolveId', [unresolvedId, undefined]).then(resolveIdResult => {
12480 if (resolveIdResult === false ||
12481 (resolveIdResult && typeof resolveIdResult === 'object' && resolveIdResult.external)) {
12482 return error(errEntryCannotBeExternal(unresolvedId));
12483 }
12484 const id = resolveIdResult && typeof resolveIdResult === 'object'
12485 ? resolveIdResult.id
12486 : resolveIdResult;
12487 if (typeof id === 'string') {
12488 return this.fetchModule(id, undefined, true, isEntry);
12489 }
12490 return error(errUnresolvedEntry(unresolvedId));
12491 });
12492 this.graph = graph;
12493 this.modulesById = modulesById;
12494 this.pluginDriver = pluginDriver;
12495 this.isExternal = getIdMatcher(external);
12496 this.hasModuleSideEffects = getHasModuleSideEffects(moduleSideEffects, pureExternalModules, graph);
12497 this.getManualChunk = typeof getManualChunk === 'function' ? getManualChunk : () => null;
12498 }
12499 addEntryModules(unresolvedEntryModules, isUserDefined) {
12500 const firstEntryModuleIndex = this.nextEntryModuleIndex;
12501 this.nextEntryModuleIndex += unresolvedEntryModules.length;
12502 const loadNewEntryModulesPromise = Promise.all(unresolvedEntryModules.map(({ fileName, id, name }) => this.loadEntryModule(id, true).then(module => {
12503 if (fileName !== null) {
12504 module.chunkFileNames.add(fileName);
12505 }
12506 else if (name !== null) {
12507 if (module.chunkName === null) {
12508 module.chunkName = name;
12509 }
12510 if (isUserDefined) {
12511 module.userChunkNames.add(name);
12512 }
12513 }
12514 return module;
12515 }))).then(entryModules => {
12516 let moduleIndex = firstEntryModuleIndex;
12517 for (const entryModule of entryModules) {
12518 entryModule.isUserDefinedEntryPoint = entryModule.isUserDefinedEntryPoint || isUserDefined;
12519 const existingIndexModule = this.indexedEntryModules.find(indexedModule => indexedModule.module.id === entryModule.id);
12520 if (!existingIndexModule) {
12521 this.indexedEntryModules.push({ module: entryModule, index: moduleIndex });
12522 }
12523 else {
12524 existingIndexModule.index = Math.min(existingIndexModule.index, moduleIndex);
12525 }
12526 moduleIndex++;
12527 }
12528 this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
12529 return entryModules;
12530 });
12531 return this.awaitLoadModulesPromise(loadNewEntryModulesPromise).then(newEntryModules => ({
12532 entryModules: this.indexedEntryModules.map(({ module }) => module),
12533 manualChunkModulesByAlias: this.manualChunkModules,
12534 newEntryModules
12535 }));
12536 }
12537 addManualChunks(manualChunks) {
12538 const unresolvedManualChunks = [];
12539 for (const alias of Object.keys(manualChunks)) {
12540 const manualChunkIds = manualChunks[alias];
12541 for (const id of manualChunkIds) {
12542 unresolvedManualChunks.push({ id, alias });
12543 }
12544 }
12545 const loadNewManualChunkModulesPromise = Promise.all(unresolvedManualChunks.map(({ id }) => this.loadEntryModule(id, false))).then(manualChunkModules => {
12546 for (let index = 0; index < manualChunkModules.length; index++) {
12547 this.addModuleToManualChunk(unresolvedManualChunks[index].alias, manualChunkModules[index]);
12548 }
12549 });
12550 return this.awaitLoadModulesPromise(loadNewManualChunkModulesPromise);
12551 }
12552 resolveId(source, importer, skip) {
12553 return __awaiter(this, void 0, void 0, function* () {
12554 return this.normalizeResolveIdResult(this.isExternal(source, importer, false)
12555 ? false
12556 : yield this.pluginDriver.hookFirst('resolveId', [source, importer], null, skip), importer, source);
12557 });
12558 }
12559 addModuleToManualChunk(alias, module) {
12560 if (module.manualChunkAlias !== null && module.manualChunkAlias !== alias) {
12561 error(errCannotAssignModuleToChunk(module.id, alias, module.manualChunkAlias));
12562 }
12563 module.manualChunkAlias = alias;
12564 if (!this.manualChunkModules[alias]) {
12565 this.manualChunkModules[alias] = [];
12566 }
12567 this.manualChunkModules[alias].push(module);
12568 }
12569 awaitLoadModulesPromise(loadNewModulesPromise) {
12570 this.latestLoadModulesPromise = Promise.all([
12571 loadNewModulesPromise,
12572 this.latestLoadModulesPromise
12573 ]);
12574 const getCombinedPromise = () => {
12575 const startingPromise = this.latestLoadModulesPromise;
12576 return startingPromise.then(() => {
12577 if (this.latestLoadModulesPromise !== startingPromise) {
12578 return getCombinedPromise();
12579 }
12580 });
12581 };
12582 return getCombinedPromise().then(() => loadNewModulesPromise);
12583 }
12584 fetchAllDependencies(module) {
12585 const fetchDynamicImportsPromise = Promise.all(module.getDynamicImportExpressions().map((specifier, index) => this.resolveDynamicImport(module, specifier, module.id).then(resolvedId => {
12586 if (resolvedId === null)
12587 return;
12588 const dynamicImport = module.dynamicImports[index];
12589 if (typeof resolvedId === 'string') {
12590 dynamicImport.resolution = resolvedId;
12591 return;
12592 }
12593 return this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId).then(module => {
12594 dynamicImport.resolution = module;
12595 });
12596 })));
12597 fetchDynamicImportsPromise.catch(() => { });
12598 return Promise.all(module.sources.map(source => this.resolveAndFetchDependency(module, source))).then(() => fetchDynamicImportsPromise);
12599 }
12600 fetchModule(id, importer, moduleSideEffects, isEntry) {
12601 const existingModule = this.modulesById.get(id);
12602 if (existingModule) {
12603 if (existingModule instanceof ExternalModule)
12604 throw new Error(`Cannot fetch external module ${id}`);
12605 existingModule.isEntryPoint = existingModule.isEntryPoint || isEntry;
12606 return Promise.resolve(existingModule);
12607 }
12608 const module = new Module(this.graph, id, moduleSideEffects, isEntry);
12609 this.modulesById.set(id, module);
12610 this.graph.watchFiles[id] = true;
12611 const manualChunkAlias = this.getManualChunk(id);
12612 if (typeof manualChunkAlias === 'string') {
12613 this.addModuleToManualChunk(manualChunkAlias, module);
12614 }
12615 timeStart('load modules', 3);
12616 return Promise.resolve(this.pluginDriver.hookFirst('load', [id]))
12617 .catch((err) => {
12618 timeEnd('load modules', 3);
12619 let msg = `Could not load ${id}`;
12620 if (importer)
12621 msg += ` (imported by ${importer})`;
12622 msg += `: ${err.message}`;
12623 err.message = msg;
12624 throw err;
12625 })
12626 .then(source => {
12627 timeEnd('load modules', 3);
12628 if (typeof source === 'string')
12629 return { code: source };
12630 if (source && typeof source === 'object' && typeof source.code === 'string')
12631 return source;
12632 return error(errBadLoader(id));
12633 })
12634 .then(sourceDescription => {
12635 const cachedModule = this.graph.cachedModules.get(id);
12636 if (cachedModule &&
12637 !cachedModule.customTransformCache &&
12638 cachedModule.originalCode === sourceDescription.code) {
12639 if (cachedModule.transformFiles) {
12640 for (const emittedFile of cachedModule.transformFiles)
12641 this.pluginDriver.emitFile(emittedFile);
12642 }
12643 return cachedModule;
12644 }
12645 if (typeof sourceDescription.moduleSideEffects === 'boolean') {
12646 module.moduleSideEffects = sourceDescription.moduleSideEffects;
12647 }
12648 return transform(this.graph, sourceDescription, module);
12649 })
12650 .then((source) => {
12651 module.setSource(source);
12652 this.modulesById.set(id, module);
12653 return this.fetchAllDependencies(module).then(() => {
12654 for (const name in module.exports) {
12655 if (name !== 'default') {
12656 module.exportsAll[name] = module.id;
12657 }
12658 }
12659 module.exportAllSources.forEach(source => {
12660 const id = module.resolvedIds[source].id;
12661 const exportAllModule = this.modulesById.get(id);
12662 if (exportAllModule instanceof ExternalModule)
12663 return;
12664 for (const name in exportAllModule.exportsAll) {
12665 if (name in module.exportsAll) {
12666 this.graph.warn(errNamespaceConflict(name, module, exportAllModule));
12667 }
12668 else {
12669 module.exportsAll[name] = exportAllModule.exportsAll[name];
12670 }
12671 }
12672 });
12673 return module;
12674 });
12675 });
12676 }
12677 fetchResolvedDependency(source, importer, resolvedId) {
12678 if (resolvedId.external) {
12679 if (!this.modulesById.has(resolvedId.id)) {
12680 this.modulesById.set(resolvedId.id, new ExternalModule(this.graph, resolvedId.id, resolvedId.moduleSideEffects));
12681 }
12682 const externalModule = this.modulesById.get(resolvedId.id);
12683 if (!(externalModule instanceof ExternalModule)) {
12684 return error(errInternalIdCannotBeExternal(source, importer));
12685 }
12686 return Promise.resolve(externalModule);
12687 }
12688 else {
12689 return this.fetchModule(resolvedId.id, importer, resolvedId.moduleSideEffects, false);
12690 }
12691 }
12692 handleMissingImports(resolvedId, source, importer) {
12693 if (resolvedId === null) {
12694 if (isRelative(source)) {
12695 error(errUnresolvedImport(source, importer));
12696 }
12697 this.graph.warn(errUnresolvedImportTreatedAsExternal(source, importer));
12698 return {
12699 external: true,
12700 id: source,
12701 moduleSideEffects: this.hasModuleSideEffects(source, true)
12702 };
12703 }
12704 return resolvedId;
12705 }
12706 normalizeResolveIdResult(resolveIdResult, importer, source) {
12707 let id = '';
12708 let external = false;
12709 let moduleSideEffects = null;
12710 if (resolveIdResult) {
12711 if (typeof resolveIdResult === 'object') {
12712 id = resolveIdResult.id;
12713 if (resolveIdResult.external) {
12714 external = true;
12715 }
12716 if (typeof resolveIdResult.moduleSideEffects === 'boolean') {
12717 moduleSideEffects = resolveIdResult.moduleSideEffects;
12718 }
12719 }
12720 else {
12721 if (this.isExternal(resolveIdResult, importer, true)) {
12722 external = true;
12723 }
12724 id = external ? normalizeRelativeExternalId(importer, resolveIdResult) : resolveIdResult;
12725 }
12726 }
12727 else {
12728 id = normalizeRelativeExternalId(importer, source);
12729 if (resolveIdResult !== false && !this.isExternal(id, importer, true)) {
12730 return null;
12731 }
12732 external = true;
12733 }
12734 return {
12735 external,
12736 id,
12737 moduleSideEffects: typeof moduleSideEffects === 'boolean'
12738 ? moduleSideEffects
12739 : this.hasModuleSideEffects(id, external)
12740 };
12741 }
12742 resolveAndFetchDependency(module, source) {
12743 return __awaiter(this, void 0, void 0, function* () {
12744 return this.fetchResolvedDependency(source, module.id, (module.resolvedIds[source] =
12745 module.resolvedIds[source] ||
12746 this.handleMissingImports(yield this.resolveId(source, module.id), source, module.id)));
12747 });
12748 }
12749 resolveDynamicImport(module, specifier, importer) {
12750 return __awaiter(this, void 0, void 0, function* () {
12751 // TODO we only should expose the acorn AST here
12752 const resolution = yield this.pluginDriver.hookFirst('resolveDynamicImport', [
12753 specifier,
12754 importer
12755 ]);
12756 if (typeof specifier !== 'string') {
12757 if (typeof resolution === 'string') {
12758 return resolution;
12759 }
12760 if (!resolution) {
12761 return null;
12762 }
12763 return Object.assign({ external: false, moduleSideEffects: true }, resolution);
12764 }
12765 if (resolution == null) {
12766 return (module.resolvedIds[specifier] =
12767 module.resolvedIds[specifier] ||
12768 this.handleMissingImports(yield this.resolveId(specifier, module.id), specifier, module.id));
12769 }
12770 return this.handleMissingImports(this.normalizeResolveIdResult(resolution, importer, specifier), specifier, importer);
12771 });
12772 }
12773}
12774
12775const CHAR_CODE_A = 97;
12776const CHAR_CODE_0 = 48;
12777function intToHex(num) {
12778 if (num < 10)
12779 return String.fromCharCode(CHAR_CODE_0 + num);
12780 else
12781 return String.fromCharCode(CHAR_CODE_A + (num - 10));
12782}
12783function Uint8ArrayToHexString(buffer) {
12784 let str = '';
12785 // hex conversion - 2 chars per 8 bit component
12786 for (let i = 0; i < buffer.length; i++) {
12787 const num = buffer[i];
12788 // big endian conversion, but whatever
12789 str += intToHex(num >> 4);
12790 str += intToHex(num & 0xf);
12791 }
12792 return str;
12793}
12794function Uint8ArrayXor(to, from) {
12795 for (let i = 0; i < to.length; i++)
12796 to[i] = to[i] ^ from[i];
12797 return to;
12798}
12799function randomUint8Array(len) {
12800 const buffer = new Uint8Array(len);
12801 for (let i = 0; i < buffer.length; i++)
12802 buffer[i] = Math.random() * (2 << 8);
12803 return buffer;
12804}
12805
12806function assignChunkColouringHashes(entryModules, manualChunkModules) {
12807 let currentEntry, currentEntryHash;
12808 let modulesVisitedForCurrentEntry;
12809 const handledEntryPoints = new Set();
12810 const dynamicImports = [];
12811 const addCurrentEntryColourToModule = (module) => {
12812 if (currentEntry.manualChunkAlias) {
12813 module.manualChunkAlias = currentEntry.manualChunkAlias;
12814 module.entryPointsHash = currentEntryHash;
12815 }
12816 else {
12817 Uint8ArrayXor(module.entryPointsHash, currentEntryHash);
12818 }
12819 for (const dependency of module.dependencies) {
12820 if (dependency instanceof ExternalModule ||
12821 modulesVisitedForCurrentEntry.has(dependency.id)) {
12822 continue;
12823 }
12824 modulesVisitedForCurrentEntry.add(dependency.id);
12825 if (!handledEntryPoints.has(dependency.id) && !dependency.manualChunkAlias) {
12826 addCurrentEntryColourToModule(dependency);
12827 }
12828 }
12829 for (const { resolution } of module.dynamicImports) {
12830 if (resolution instanceof Module &&
12831 resolution.dynamicallyImportedBy.length > 0 &&
12832 !resolution.manualChunkAlias) {
12833 dynamicImports.push(resolution);
12834 }
12835 }
12836 };
12837 if (manualChunkModules) {
12838 for (const chunkName of Object.keys(manualChunkModules)) {
12839 currentEntryHash = randomUint8Array(10);
12840 for (currentEntry of manualChunkModules[chunkName]) {
12841 modulesVisitedForCurrentEntry = new Set(currentEntry.id);
12842 addCurrentEntryColourToModule(currentEntry);
12843 }
12844 }
12845 }
12846 for (currentEntry of entryModules) {
12847 handledEntryPoints.add(currentEntry.id);
12848 currentEntryHash = randomUint8Array(10);
12849 modulesVisitedForCurrentEntry = new Set(currentEntry.id);
12850 if (!currentEntry.manualChunkAlias) {
12851 addCurrentEntryColourToModule(currentEntry);
12852 }
12853 }
12854 for (currentEntry of dynamicImports) {
12855 if (handledEntryPoints.has(currentEntry.id)) {
12856 continue;
12857 }
12858 handledEntryPoints.add(currentEntry.id);
12859 currentEntryHash = randomUint8Array(10);
12860 modulesVisitedForCurrentEntry = new Set(currentEntry.id);
12861 addCurrentEntryColourToModule(currentEntry);
12862 }
12863}
12864
12865function makeOnwarn() {
12866 const warned = Object.create(null);
12867 return (warning) => {
12868 const str = warning.toString();
12869 if (str in warned)
12870 return;
12871 console.error(str);
12872 warned[str] = true;
12873 };
12874}
12875function normalizeEntryModules(entryModules) {
12876 if (typeof entryModules === 'string') {
12877 return [{ fileName: null, name: null, id: entryModules }];
12878 }
12879 if (Array.isArray(entryModules)) {
12880 return entryModules.map(id => ({ fileName: null, name: null, id }));
12881 }
12882 return Object.keys(entryModules).map(name => ({
12883 fileName: null,
12884 id: entryModules[name],
12885 name
12886 }));
12887}
12888class Graph {
12889 constructor(options, watcher) {
12890 this.moduleById = new Map();
12891 this.needsTreeshakingPass = false;
12892 this.phase = BuildPhase.LOAD_AND_PARSE;
12893 this.watchFiles = Object.create(null);
12894 this.externalModules = [];
12895 this.modules = [];
12896 this.onwarn = options.onwarn || makeOnwarn();
12897 this.deoptimizationTracker = new PathTracker();
12898 this.cachedModules = new Map();
12899 if (options.cache) {
12900 if (options.cache.modules)
12901 for (const module of options.cache.modules)
12902 this.cachedModules.set(module.id, module);
12903 }
12904 if (options.cache !== false) {
12905 this.pluginCache = (options.cache && options.cache.plugins) || Object.create(null);
12906 // increment access counter
12907 for (const name in this.pluginCache) {
12908 const cache = this.pluginCache[name];
12909 for (const key of Object.keys(cache))
12910 cache[key][0]++;
12911 }
12912 }
12913 this.preserveModules = options.preserveModules;
12914 this.strictDeprecations = options.strictDeprecations;
12915 this.cacheExpiry = options.experimentalCacheExpiry;
12916 if (options.treeshake !== false) {
12917 this.treeshakingOptions = options.treeshake
12918 ? {
12919 annotations: options.treeshake.annotations !== false,
12920 moduleSideEffects: options.treeshake.moduleSideEffects,
12921 propertyReadSideEffects: options.treeshake.propertyReadSideEffects !== false,
12922 pureExternalModules: options.treeshake.pureExternalModules,
12923 tryCatchDeoptimization: options.treeshake.tryCatchDeoptimization !== false,
12924 unknownGlobalSideEffects: options.treeshake.unknownGlobalSideEffects !== false
12925 }
12926 : {
12927 annotations: true,
12928 moduleSideEffects: true,
12929 propertyReadSideEffects: true,
12930 tryCatchDeoptimization: true,
12931 unknownGlobalSideEffects: true
12932 };
12933 if (typeof this.treeshakingOptions.pureExternalModules !== 'undefined') {
12934 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);
12935 }
12936 }
12937 this.contextParse = (code, options = {}) => this.acornParser.parse(code, Object.assign(Object.assign(Object.assign({}, defaultAcornOptions), options), this.acornOptions));
12938 this.pluginDriver = createPluginDriver(this, options, this.pluginCache, watcher);
12939 if (watcher) {
12940 const handleChange = (id) => this.pluginDriver.hookSeqSync('watchChange', [id]);
12941 watcher.on('change', handleChange);
12942 watcher.once('restart', () => {
12943 watcher.removeListener('change', handleChange);
12944 });
12945 }
12946 this.shimMissingExports = options.shimMissingExports;
12947 this.scope = new GlobalScope();
12948 this.context = String(options.context);
12949 const optionsModuleContext = options.moduleContext;
12950 if (typeof optionsModuleContext === 'function') {
12951 this.getModuleContext = id => optionsModuleContext(id) || this.context;
12952 }
12953 else if (typeof optionsModuleContext === 'object') {
12954 const moduleContext = new Map();
12955 for (const key in optionsModuleContext) {
12956 moduleContext.set(resolve(key), optionsModuleContext[key]);
12957 }
12958 this.getModuleContext = id => moduleContext.get(id) || this.context;
12959 }
12960 else {
12961 this.getModuleContext = () => this.context;
12962 }
12963 this.acornOptions = options.acorn ? Object.assign({}, options.acorn) : {};
12964 const acornPluginsToInject = [];
12965 acornPluginsToInject.push(acornImportMeta);
12966 if (options.experimentalTopLevelAwait) {
12967 this.acornOptions.allowAwaitOutsideFunction = true;
12968 }
12969 const acornInjectPlugins = options.acornInjectPlugins;
12970 acornPluginsToInject.push(...(Array.isArray(acornInjectPlugins)
12971 ? acornInjectPlugins
12972 : acornInjectPlugins
12973 ? [acornInjectPlugins]
12974 : []));
12975 this.acornParser = Parser.extend(...acornPluginsToInject);
12976 this.moduleLoader = new ModuleLoader(this, this.moduleById, this.pluginDriver, options.external, (typeof options.manualChunks === 'function' && options.manualChunks), (this.treeshakingOptions
12977 ? this.treeshakingOptions.moduleSideEffects
12978 : null), (this.treeshakingOptions
12979 ? this.treeshakingOptions.pureExternalModules
12980 : false));
12981 }
12982 build(entryModules, manualChunks, inlineDynamicImports) {
12983 // Phase 1 – discovery. We load the entry module and find which
12984 // modules it imports, and import those, until we have all
12985 // of the entry module's dependencies
12986 timeStart('parse modules', 2);
12987 return Promise.all([
12988 this.moduleLoader.addEntryModules(normalizeEntryModules(entryModules), true),
12989 (manualChunks &&
12990 typeof manualChunks === 'object' &&
12991 this.moduleLoader.addManualChunks(manualChunks))
12992 ]).then(([{ entryModules, manualChunkModulesByAlias }]) => {
12993 if (entryModules.length === 0) {
12994 throw new Error('You must supply options.input to rollup');
12995 }
12996 for (const module of this.moduleById.values()) {
12997 if (module instanceof Module) {
12998 this.modules.push(module);
12999 }
13000 else {
13001 this.externalModules.push(module);
13002 }
13003 }
13004 timeEnd('parse modules', 2);
13005 this.phase = BuildPhase.ANALYSE;
13006 // Phase 2 - linking. We populate the module dependency links and
13007 // determine the topological execution order for the bundle
13008 timeStart('analyse dependency graph', 2);
13009 this.link(entryModules);
13010 timeEnd('analyse dependency graph', 2);
13011 // Phase 3 – marking. We include all statements that should be included
13012 timeStart('mark included statements', 2);
13013 if (inlineDynamicImports) {
13014 if (entryModules.length > 1) {
13015 throw new Error('Internal Error: can only inline dynamic imports for single-file builds.');
13016 }
13017 }
13018 for (const module of entryModules) {
13019 module.includeAllExports();
13020 }
13021 this.includeMarked(this.modules);
13022 // check for unused external imports
13023 for (const externalModule of this.externalModules)
13024 externalModule.warnUnusedImports();
13025 timeEnd('mark included statements', 2);
13026 // Phase 4 – we construct the chunks, working out the optimal chunking using
13027 // entry point graph colouring, before generating the import and export facades
13028 timeStart('generate chunks', 2);
13029 if (!this.preserveModules && !inlineDynamicImports) {
13030 assignChunkColouringHashes(entryModules, manualChunkModulesByAlias);
13031 }
13032 // TODO: there is one special edge case unhandled here and that is that any module
13033 // exposed as an unresolvable export * (to a graph external export *,
13034 // either as a namespace import reexported or top-level export *)
13035 // should be made to be its own entry point module before chunking
13036 let chunks = [];
13037 if (this.preserveModules) {
13038 for (const module of this.modules) {
13039 const chunk = new Chunk$1(this, [module]);
13040 if (module.isEntryPoint || !chunk.isEmpty) {
13041 chunk.entryModules = [module];
13042 }
13043 chunks.push(chunk);
13044 }
13045 }
13046 else {
13047 const chunkModules = {};
13048 for (const module of this.modules) {
13049 const entryPointsHashStr = Uint8ArrayToHexString(module.entryPointsHash);
13050 const curChunk = chunkModules[entryPointsHashStr];
13051 if (curChunk) {
13052 curChunk.push(module);
13053 }
13054 else {
13055 chunkModules[entryPointsHashStr] = [module];
13056 }
13057 }
13058 for (const entryHashSum in chunkModules) {
13059 const chunkModulesOrdered = chunkModules[entryHashSum];
13060 sortByExecutionOrder(chunkModulesOrdered);
13061 const chunk = new Chunk$1(this, chunkModulesOrdered);
13062 chunks.push(chunk);
13063 }
13064 }
13065 for (const chunk of chunks) {
13066 chunk.link();
13067 }
13068 chunks = chunks.filter(isChunkRendered);
13069 const facades = [];
13070 for (const chunk of chunks) {
13071 facades.push(...chunk.generateFacades());
13072 }
13073 timeEnd('generate chunks', 2);
13074 this.phase = BuildPhase.GENERATE;
13075 return chunks.concat(facades);
13076 });
13077 }
13078 getCache() {
13079 // handle plugin cache eviction
13080 for (const name in this.pluginCache) {
13081 const cache = this.pluginCache[name];
13082 let allDeleted = true;
13083 for (const key of Object.keys(cache)) {
13084 if (cache[key][0] >= this.cacheExpiry)
13085 delete cache[key];
13086 else
13087 allDeleted = false;
13088 }
13089 if (allDeleted)
13090 delete this.pluginCache[name];
13091 }
13092 return {
13093 modules: this.modules.map(module => module.toJSON()),
13094 plugins: this.pluginCache
13095 };
13096 }
13097 includeMarked(modules) {
13098 if (this.treeshakingOptions) {
13099 let treeshakingPass = 1;
13100 do {
13101 timeStart(`treeshaking pass ${treeshakingPass}`, 3);
13102 this.needsTreeshakingPass = false;
13103 for (const module of modules) {
13104 if (module.isExecuted)
13105 module.include();
13106 }
13107 timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
13108 } while (this.needsTreeshakingPass);
13109 }
13110 else {
13111 // Necessary to properly replace namespace imports
13112 for (const module of modules)
13113 module.includeAllInBundle();
13114 }
13115 }
13116 warn(warning) {
13117 warning.toString = () => {
13118 let str = '';
13119 if (warning.plugin)
13120 str += `(${warning.plugin} plugin) `;
13121 if (warning.loc)
13122 str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
13123 str += warning.message;
13124 return str;
13125 };
13126 this.onwarn(warning);
13127 }
13128 warnDeprecation(deprecation, activeDeprecation) {
13129 if (activeDeprecation || this.strictDeprecations) {
13130 const warning = errDeprecation(deprecation);
13131 if (this.strictDeprecations) {
13132 return error(warning);
13133 }
13134 this.warn(warning);
13135 }
13136 }
13137 link(entryModules) {
13138 for (const module of this.modules) {
13139 module.linkDependencies();
13140 }
13141 const { orderedModules, cyclePaths } = analyseModuleExecution(entryModules);
13142 for (const cyclePath of cyclePaths) {
13143 this.warn({
13144 code: 'CIRCULAR_DEPENDENCY',
13145 importer: cyclePath[0],
13146 message: `Circular dependency: ${cyclePath.join(' -> ')}`
13147 });
13148 }
13149 this.modules = orderedModules;
13150 for (const module of this.modules) {
13151 module.bindReferences();
13152 }
13153 this.warnForMissingExports();
13154 }
13155 warnForMissingExports() {
13156 for (const module of this.modules) {
13157 for (const importName of Object.keys(module.importDescriptions)) {
13158 const importDescription = module.importDescriptions[importName];
13159 if (importDescription.name !== '*' &&
13160 !importDescription.module.getVariableForExportName(importDescription.name)) {
13161 module.warn({
13162 code: 'NON_EXISTENT_EXPORT',
13163 message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
13164 name: importDescription.name,
13165 source: importDescription.module.id
13166 }, importDescription.start);
13167 }
13168 }
13169 }
13170 }
13171}
13172
13173function evalIfFn(strOrFn) {
13174 switch (typeof strOrFn) {
13175 case 'function':
13176 return strOrFn();
13177 case 'string':
13178 return strOrFn;
13179 default:
13180 return '';
13181 }
13182}
13183const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
13184const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
13185function createAddons(graph, options) {
13186 const pluginDriver = graph.pluginDriver;
13187 return Promise.all([
13188 pluginDriver.hookReduceValue('banner', evalIfFn(options.banner), [], concatSep),
13189 pluginDriver.hookReduceValue('footer', evalIfFn(options.footer), [], concatSep),
13190 pluginDriver.hookReduceValue('intro', evalIfFn(options.intro), [], concatDblSep),
13191 pluginDriver.hookReduceValue('outro', evalIfFn(options.outro), [], concatDblSep)
13192 ])
13193 .then(([banner, footer, intro, outro]) => {
13194 if (intro)
13195 intro += '\n\n';
13196 if (outro)
13197 outro = `\n\n${outro}`;
13198 if (banner.length)
13199 banner += '\n';
13200 if (footer.length)
13201 footer = '\n' + footer;
13202 return { intro, outro, banner, footer };
13203 })
13204 .catch((err) => {
13205 error({
13206 code: 'ADDON_ERROR',
13207 message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
13208\tError Message: ${err.message}`
13209 });
13210 });
13211}
13212
13213function assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, bundle) {
13214 const entryChunks = [];
13215 const otherChunks = [];
13216 for (const chunk of chunks) {
13217 (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
13218 ? entryChunks
13219 : otherChunks).push(chunk);
13220 }
13221 // make sure entry chunk names take precedence with regard to deconflicting
13222 const chunksForNaming = entryChunks.concat(otherChunks);
13223 for (const chunk of chunksForNaming) {
13224 if (outputOptions.file) {
13225 chunk.id = basename(outputOptions.file);
13226 }
13227 else if (inputOptions.preserveModules) {
13228 chunk.id = chunk.generateIdPreserveModules(inputBase, outputOptions, bundle);
13229 }
13230 else {
13231 chunk.id = chunk.generateId(addons, outputOptions, bundle, true);
13232 }
13233 bundle[chunk.id] = FILE_PLACEHOLDER;
13234 }
13235}
13236
13237// ported from https://github.com/substack/node-commondir
13238function commondir(files) {
13239 if (files.length === 0)
13240 return '/';
13241 if (files.length === 1)
13242 return dirname(files[0]);
13243 const commonSegments = files.slice(1).reduce((commonSegments, file) => {
13244 const pathSegements = file.split(/\/+|\\+/);
13245 let i;
13246 for (i = 0; commonSegments[i] === pathSegements[i] &&
13247 i < Math.min(commonSegments.length, pathSegements.length); i++)
13248 ;
13249 return commonSegments.slice(0, i);
13250 }, files[0].split(/\/+|\\+/));
13251 // Windows correctly handles paths with forward-slashes
13252 return commonSegments.length > 1 ? commonSegments.join('/') : '/';
13253}
13254
13255function badExports(option, keys) {
13256 error({
13257 code: 'INVALID_EXPORT_OPTION',
13258 message: `'${option}' was specified for output.exports, but entry module has following exports: ${keys.join(', ')}`
13259 });
13260}
13261function getExportMode(chunk, { exports: exportMode, name, format }) {
13262 const exportKeys = chunk.getExportNames();
13263 if (exportMode === 'default') {
13264 if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
13265 badExports('default', exportKeys);
13266 }
13267 }
13268 else if (exportMode === 'none' && exportKeys.length) {
13269 badExports('none', exportKeys);
13270 }
13271 if (!exportMode || exportMode === 'auto') {
13272 if (exportKeys.length === 0) {
13273 exportMode = 'none';
13274 }
13275 else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
13276 exportMode = 'default';
13277 }
13278 else {
13279 if (chunk.facadeModule !== null &&
13280 chunk.facadeModule.isEntryPoint &&
13281 format !== 'es' &&
13282 exportKeys.indexOf('default') !== -1) {
13283 chunk.graph.warn({
13284 code: 'MIXED_EXPORTS',
13285 message: `Using named and default exports together. Consumers of your bundle will have to use ${name ||
13286 'bundle'}['default'] to access the default export, which may not be what you want. Use \`output.exports: 'named'\` to disable this warning`,
13287 url: `https://rollupjs.org/guide/en/#output-exports`
13288 });
13289 }
13290 exportMode = 'named';
13291 }
13292 }
13293 if (!/(?:default|named|none)/.test(exportMode)) {
13294 error({
13295 code: 'INVALID_EXPORT_OPTION',
13296 message: `output.exports must be 'default', 'named', 'none', 'auto', or left unspecified (defaults to 'auto')`,
13297 url: `https://rollupjs.org/guide/en/#output-exports`
13298 });
13299 }
13300 return exportMode;
13301}
13302
13303const createGetOption = (config, command) => (name, defaultValue) => command[name] !== undefined
13304 ? command[name]
13305 : config[name] !== undefined
13306 ? config[name]
13307 : defaultValue;
13308const normalizeObjectOptionValue = (optionValue) => {
13309 if (!optionValue) {
13310 return optionValue;
13311 }
13312 if (typeof optionValue !== 'object') {
13313 return {};
13314 }
13315 return optionValue;
13316};
13317const getObjectOption = (config, command, name) => {
13318 const commandOption = normalizeObjectOptionValue(command[name]);
13319 const configOption = normalizeObjectOptionValue(config[name]);
13320 if (commandOption !== undefined) {
13321 return commandOption && configOption ? Object.assign(Object.assign({}, configOption), commandOption) : commandOption;
13322 }
13323 return configOption;
13324};
13325const defaultOnWarn = warning => {
13326 if (typeof warning === 'string') {
13327 console.warn(warning);
13328 }
13329 else {
13330 console.warn(warning.message);
13331 }
13332};
13333const getOnWarn = (config, defaultOnWarnHandler = defaultOnWarn) => config.onwarn
13334 ? warning => config.onwarn(warning, defaultOnWarnHandler)
13335 : defaultOnWarnHandler;
13336const getExternal = (config, command) => {
13337 const configExternal = config.external;
13338 return typeof configExternal === 'function'
13339 ? (id, ...rest) => configExternal(id, ...rest) || command.external.indexOf(id) !== -1
13340 : (typeof config.external === 'string'
13341 ? [configExternal]
13342 : Array.isArray(configExternal)
13343 ? configExternal
13344 : []).concat(command.external);
13345};
13346const commandAliases = {
13347 c: 'config',
13348 d: 'dir',
13349 e: 'external',
13350 f: 'format',
13351 g: 'globals',
13352 h: 'help',
13353 i: 'input',
13354 m: 'sourcemap',
13355 n: 'name',
13356 o: 'file',
13357 v: 'version',
13358 w: 'watch'
13359};
13360function mergeOptions({ config = {}, command: rawCommandOptions = {}, defaultOnWarnHandler }) {
13361 const command = getCommandOptions(rawCommandOptions);
13362 const inputOptions = getInputOptions(config, command, defaultOnWarnHandler);
13363 if (command.output) {
13364 Object.assign(command, command.output);
13365 }
13366 const output = config.output;
13367 const normalizedOutputOptions = Array.isArray(output) ? output : output ? [output] : [];
13368 if (normalizedOutputOptions.length === 0)
13369 normalizedOutputOptions.push({});
13370 const outputOptions = normalizedOutputOptions.map(singleOutputOptions => getOutputOptions(singleOutputOptions, command));
13371 const unknownOptionErrors = [];
13372 const validInputOptions = Object.keys(inputOptions);
13373 addUnknownOptionErrors(unknownOptionErrors, Object.keys(config), validInputOptions, 'input option', /^output$/);
13374 const validOutputOptions = Object.keys(outputOptions[0]);
13375 addUnknownOptionErrors(unknownOptionErrors, outputOptions.reduce((allKeys, options) => allKeys.concat(Object.keys(options)), []), validOutputOptions, 'output option');
13376 const validCliOutputOptions = validOutputOptions.filter(option => option !== 'sourcemapPathTransform');
13377 addUnknownOptionErrors(unknownOptionErrors, Object.keys(command), validInputOptions.concat(validCliOutputOptions, Object.keys(commandAliases), 'config', 'environment', 'silent'), 'CLI flag', /^_|output|(config.*)$/);
13378 return {
13379 inputOptions,
13380 optionError: unknownOptionErrors.length > 0 ? unknownOptionErrors.join('\n') : null,
13381 outputOptions
13382 };
13383}
13384function addUnknownOptionErrors(errors, options, validOptions, optionType, ignoredKeys = /$./) {
13385 const unknownOptions = options.filter(key => validOptions.indexOf(key) === -1 && !ignoredKeys.test(key));
13386 if (unknownOptions.length > 0)
13387 errors.push(`Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${validOptions.sort().join(', ')}`);
13388}
13389function getCommandOptions(rawCommandOptions) {
13390 const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
13391 ? rawCommandOptions.external.split(',')
13392 : [];
13393 return Object.assign(Object.assign({}, rawCommandOptions), { external, globals: typeof rawCommandOptions.globals === 'string'
13394 ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
13395 const [id, variableName] = globalDefinition.split(':');
13396 globals[id] = variableName;
13397 if (external.indexOf(id) === -1) {
13398 external.push(id);
13399 }
13400 return globals;
13401 }, Object.create(null))
13402 : undefined });
13403}
13404function getInputOptions(config, command = { external: [], globals: undefined }, defaultOnWarnHandler) {
13405 const getOption = createGetOption(config, command);
13406 const inputOptions = {
13407 acorn: config.acorn,
13408 acornInjectPlugins: config.acornInjectPlugins,
13409 cache: getOption('cache'),
13410 chunkGroupingSize: getOption('chunkGroupingSize', 5000),
13411 context: getOption('context'),
13412 experimentalCacheExpiry: getOption('experimentalCacheExpiry', 10),
13413 experimentalOptimizeChunks: getOption('experimentalOptimizeChunks'),
13414 experimentalTopLevelAwait: getOption('experimentalTopLevelAwait'),
13415 external: getExternal(config, command),
13416 inlineDynamicImports: getOption('inlineDynamicImports', false),
13417 input: getOption('input', []),
13418 manualChunks: getOption('manualChunks'),
13419 moduleContext: config.moduleContext,
13420 onwarn: getOnWarn(config, defaultOnWarnHandler),
13421 perf: getOption('perf', false),
13422 plugins: config.plugins,
13423 preserveModules: getOption('preserveModules'),
13424 preserveSymlinks: getOption('preserveSymlinks'),
13425 shimMissingExports: getOption('shimMissingExports'),
13426 strictDeprecations: getOption('strictDeprecations', false),
13427 treeshake: getObjectOption(config, command, 'treeshake'),
13428 watch: config.watch
13429 };
13430 // support rollup({ cache: prevBuildObject })
13431 if (inputOptions.cache && inputOptions.cache.cache)
13432 inputOptions.cache = inputOptions.cache.cache;
13433 return inputOptions;
13434}
13435function getOutputOptions(config, command = {}) {
13436 const getOption = createGetOption(config, command);
13437 let format = getOption('format');
13438 // Handle format aliases
13439 switch (format) {
13440 case 'esm':
13441 case 'module':
13442 format = 'es';
13443 break;
13444 case 'commonjs':
13445 format = 'cjs';
13446 }
13447 return {
13448 amd: Object.assign(Object.assign({}, config.amd), command.amd),
13449 assetFileNames: getOption('assetFileNames'),
13450 banner: getOption('banner'),
13451 chunkFileNames: getOption('chunkFileNames'),
13452 compact: getOption('compact', false),
13453 dir: getOption('dir'),
13454 dynamicImportFunction: getOption('dynamicImportFunction'),
13455 entryFileNames: getOption('entryFileNames'),
13456 esModule: getOption('esModule', true),
13457 exports: getOption('exports'),
13458 extend: getOption('extend'),
13459 externalLiveBindings: getOption('externalLiveBindings', true),
13460 file: getOption('file'),
13461 footer: getOption('footer'),
13462 format: format === 'esm' ? 'es' : format,
13463 freeze: getOption('freeze', true),
13464 globals: getOption('globals'),
13465 indent: getOption('indent', true),
13466 interop: getOption('interop', true),
13467 intro: getOption('intro'),
13468 name: getOption('name'),
13469 namespaceToStringTag: getOption('namespaceToStringTag', false),
13470 noConflict: getOption('noConflict'),
13471 outro: getOption('outro'),
13472 paths: getOption('paths'),
13473 preferConst: getOption('preferConst'),
13474 sourcemap: getOption('sourcemap'),
13475 sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
13476 sourcemapFile: getOption('sourcemapFile'),
13477 sourcemapPathTransform: getOption('sourcemapPathTransform'),
13478 strict: getOption('strict', true)
13479 };
13480}
13481
13482function checkOutputOptions(options) {
13483 if (options.format === 'es6') {
13484 error(errDeprecation({
13485 message: 'The "es6" output format is deprecated – use "esm" instead',
13486 url: `https://rollupjs.org/guide/en/#output-format`
13487 }));
13488 }
13489 if (['amd', 'cjs', 'system', 'es', 'iife', 'umd'].indexOf(options.format) < 0) {
13490 error({
13491 message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "esm", "iife" or "umd".`,
13492 url: `https://rollupjs.org/guide/en/#output-format`
13493 });
13494 }
13495}
13496function getAbsoluteEntryModulePaths(chunks) {
13497 const absoluteEntryModulePaths = [];
13498 for (const chunk of chunks) {
13499 for (const entryModule of chunk.entryModules) {
13500 if (isAbsolute(entryModule.id)) {
13501 absoluteEntryModulePaths.push(entryModule.id);
13502 }
13503 }
13504 }
13505 return absoluteEntryModulePaths;
13506}
13507const throwAsyncGenerateError = {
13508 get() {
13509 throw new Error(`bundle.generate(...) now returns a Promise instead of a { code, map } object`);
13510 }
13511};
13512function applyOptionHook(inputOptions, plugin) {
13513 if (plugin.options)
13514 return plugin.options.call({ meta: { rollupVersion: version } }, inputOptions) || inputOptions;
13515 return inputOptions;
13516}
13517function ensureArray(items) {
13518 if (Array.isArray(items)) {
13519 return items.filter(Boolean);
13520 }
13521 if (items) {
13522 return [items];
13523 }
13524 return [];
13525}
13526function getInputOptions$1(rawInputOptions) {
13527 if (!rawInputOptions) {
13528 throw new Error('You must supply an options object to rollup');
13529 }
13530 let { inputOptions, optionError } = mergeOptions({
13531 config: rawInputOptions
13532 });
13533 if (optionError)
13534 inputOptions.onwarn({ message: optionError, code: 'UNKNOWN_OPTION' });
13535 inputOptions = ensureArray(inputOptions.plugins).reduce(applyOptionHook, inputOptions);
13536 inputOptions.plugins = ensureArray(inputOptions.plugins);
13537 for (let pluginIndex = 0; pluginIndex < inputOptions.plugins.length; pluginIndex++) {
13538 const plugin = inputOptions.plugins[pluginIndex];
13539 if (!plugin.name) {
13540 plugin.name = `${ANONYMOUS_PLUGIN_PREFIX}${pluginIndex + 1}`;
13541 }
13542 }
13543 if (inputOptions.inlineDynamicImports) {
13544 if (inputOptions.preserveModules)
13545 error({
13546 code: 'INVALID_OPTION',
13547 message: `"preserveModules" does not support the "inlineDynamicImports" option.`
13548 });
13549 if (inputOptions.manualChunks)
13550 error({
13551 code: 'INVALID_OPTION',
13552 message: '"manualChunks" option is not supported for "inlineDynamicImports".'
13553 });
13554 if (inputOptions.experimentalOptimizeChunks)
13555 error({
13556 code: 'INVALID_OPTION',
13557 message: '"experimentalOptimizeChunks" option is not supported for "inlineDynamicImports".'
13558 });
13559 if ((inputOptions.input instanceof Array && inputOptions.input.length > 1) ||
13560 (typeof inputOptions.input === 'object' && Object.keys(inputOptions.input).length > 1))
13561 error({
13562 code: 'INVALID_OPTION',
13563 message: 'Multiple inputs are not supported for "inlineDynamicImports".'
13564 });
13565 }
13566 else if (inputOptions.preserveModules) {
13567 if (inputOptions.manualChunks)
13568 error({
13569 code: 'INVALID_OPTION',
13570 message: '"preserveModules" does not support the "manualChunks" option.'
13571 });
13572 if (inputOptions.experimentalOptimizeChunks)
13573 error({
13574 code: 'INVALID_OPTION',
13575 message: '"preserveModules" does not support the "experimentalOptimizeChunks" option.'
13576 });
13577 }
13578 return inputOptions;
13579}
13580let curWatcher;
13581function setWatcher(watcher) {
13582 curWatcher = watcher;
13583}
13584function assignChunksToBundle(chunks, outputBundle) {
13585 for (let i = 0; i < chunks.length; i++) {
13586 const chunk = chunks[i];
13587 const facadeModule = chunk.facadeModule;
13588 outputBundle[chunk.id] = {
13589 code: undefined,
13590 dynamicImports: chunk.getDynamicImportIds(),
13591 exports: chunk.getExportNames(),
13592 facadeModuleId: facadeModule && facadeModule.id,
13593 fileName: chunk.id,
13594 imports: chunk.getImportIds(),
13595 isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0,
13596 isEntry: facadeModule !== null && facadeModule.isEntryPoint,
13597 map: undefined,
13598 modules: chunk.renderedModules,
13599 get name() {
13600 return chunk.getChunkName();
13601 },
13602 type: 'chunk'
13603 };
13604 }
13605 return outputBundle;
13606}
13607function rollup(rawInputOptions) {
13608 return __awaiter(this, void 0, void 0, function* () {
13609 const inputOptions = getInputOptions$1(rawInputOptions);
13610 initialiseTimers(inputOptions);
13611 const graph = new Graph(inputOptions, curWatcher);
13612 curWatcher = undefined;
13613 // remove the cache option from the memory after graph creation (cache is not used anymore)
13614 const useCache = rawInputOptions.cache !== false;
13615 delete inputOptions.cache;
13616 delete rawInputOptions.cache;
13617 timeStart('BUILD', 1);
13618 let chunks;
13619 try {
13620 yield graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
13621 chunks = yield graph.build(inputOptions.input, inputOptions.manualChunks, inputOptions.inlineDynamicImports);
13622 }
13623 catch (err) {
13624 yield graph.pluginDriver.hookParallel('buildEnd', [err]);
13625 throw err;
13626 }
13627 yield graph.pluginDriver.hookParallel('buildEnd', []);
13628 timeEnd('BUILD', 1);
13629 // ensure we only do one optimization pass per build
13630 let optimized = false;
13631 function getOutputOptions(rawOutputOptions) {
13632 return normalizeOutputOptions(inputOptions, rawOutputOptions, chunks.length > 1, graph.pluginDriver);
13633 }
13634 function generate(outputOptions, isWrite) {
13635 return __awaiter(this, void 0, void 0, function* () {
13636 timeStart('GENERATE', 1);
13637 const assetFileNames = outputOptions.assetFileNames || 'assets/[name]-[hash][extname]';
13638 const outputBundleWithPlaceholders = Object.create(null);
13639 let outputBundle;
13640 const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
13641 graph.pluginDriver.startOutput(outputBundleWithPlaceholders, assetFileNames);
13642 try {
13643 yield graph.pluginDriver.hookParallel('renderStart', []);
13644 const addons = yield createAddons(graph, outputOptions);
13645 for (const chunk of chunks) {
13646 if (!inputOptions.preserveModules)
13647 chunk.generateInternalExports(outputOptions);
13648 if (chunk.facadeModule && chunk.facadeModule.isEntryPoint)
13649 chunk.exportMode = getExportMode(chunk, outputOptions);
13650 }
13651 for (const chunk of chunks) {
13652 chunk.preRender(outputOptions, inputBase);
13653 }
13654 if (!optimized && inputOptions.experimentalOptimizeChunks) {
13655 optimizeChunks(chunks, outputOptions, inputOptions.chunkGroupingSize, inputBase);
13656 optimized = true;
13657 }
13658 assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, outputBundleWithPlaceholders);
13659 outputBundle = assignChunksToBundle(chunks, outputBundleWithPlaceholders);
13660 yield Promise.all(chunks.map(chunk => {
13661 const outputChunk = outputBundleWithPlaceholders[chunk.id];
13662 return chunk.render(outputOptions, addons, outputChunk).then(rendered => {
13663 outputChunk.code = rendered.code;
13664 outputChunk.map = rendered.map;
13665 return graph.pluginDriver.hookParallel('ongenerate', [
13666 Object.assign({ bundle: outputChunk }, outputOptions),
13667 outputChunk
13668 ]);
13669 });
13670 }));
13671 }
13672 catch (error) {
13673 yield graph.pluginDriver.hookParallel('renderError', [error]);
13674 throw error;
13675 }
13676 yield graph.pluginDriver.hookSeq('generateBundle', [outputOptions, outputBundle, isWrite]);
13677 for (const key of Object.keys(outputBundle)) {
13678 const file = outputBundle[key];
13679 if (!file.type) {
13680 graph.warnDeprecation('A plugin is directly adding properties to the bundle object in the "generateBundle" hook. This is deprecated and will be removed in a future Rollup version, please use "this.emitFile" instead.', false);
13681 file.type = 'asset';
13682 }
13683 }
13684 graph.pluginDriver.finaliseAssets();
13685 timeEnd('GENERATE', 1);
13686 return outputBundle;
13687 });
13688 }
13689 const cache = useCache ? graph.getCache() : undefined;
13690 const result = {
13691 cache: cache,
13692 generate: ((rawOutputOptions) => {
13693 const promise = generate(getOutputOptions(rawOutputOptions), false).then(result => createOutput(result));
13694 Object.defineProperty(promise, 'code', throwAsyncGenerateError);
13695 Object.defineProperty(promise, 'map', throwAsyncGenerateError);
13696 return promise;
13697 }),
13698 watchFiles: Object.keys(graph.watchFiles),
13699 write: ((rawOutputOptions) => {
13700 const outputOptions = getOutputOptions(rawOutputOptions);
13701 if (!outputOptions.dir && !outputOptions.file) {
13702 error({
13703 code: 'MISSING_OPTION',
13704 message: 'You must specify "output.file" or "output.dir" for the build.'
13705 });
13706 }
13707 return generate(outputOptions, true).then((bundle) => __awaiter(this, void 0, void 0, function* () {
13708 let chunkCnt = 0;
13709 for (const fileName of Object.keys(bundle)) {
13710 const file = bundle[fileName];
13711 if (file.type === 'asset')
13712 continue;
13713 chunkCnt++;
13714 if (chunkCnt > 1)
13715 break;
13716 }
13717 if (chunkCnt > 1) {
13718 if (outputOptions.sourcemapFile)
13719 error({
13720 code: 'INVALID_OPTION',
13721 message: '"output.sourcemapFile" is only supported for single-file builds.'
13722 });
13723 if (typeof outputOptions.file === 'string')
13724 error({
13725 code: 'INVALID_OPTION',
13726 message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file".' +
13727 (typeof inputOptions.input !== 'string' ||
13728 inputOptions.inlineDynamicImports === true
13729 ? ''
13730 : ' To inline dynamic imports, set the "inlineDynamicImports" option.')
13731 });
13732 }
13733 yield Promise.all(Object.keys(bundle).map(chunkId => writeOutputFile(graph, result, bundle[chunkId], outputOptions)));
13734 yield graph.pluginDriver.hookParallel('writeBundle', [bundle]);
13735 return createOutput(bundle);
13736 }));
13737 })
13738 };
13739 if (inputOptions.perf === true)
13740 result.getTimings = getTimings;
13741 return result;
13742 });
13743}
13744var SortingFileType;
13745(function (SortingFileType) {
13746 SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
13747 SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
13748 SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
13749})(SortingFileType || (SortingFileType = {}));
13750function getSortingFileType(file) {
13751 if (file.type === 'asset') {
13752 return SortingFileType.ASSET;
13753 }
13754 if (file.isEntry) {
13755 return SortingFileType.ENTRY_CHUNK;
13756 }
13757 return SortingFileType.SECONDARY_CHUNK;
13758}
13759function createOutput(outputBundle) {
13760 return {
13761 output: Object.keys(outputBundle)
13762 .map(fileName => outputBundle[fileName])
13763 .filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
13764 const fileTypeA = getSortingFileType(outputFileA);
13765 const fileTypeB = getSortingFileType(outputFileB);
13766 if (fileTypeA === fileTypeB)
13767 return 0;
13768 return fileTypeA < fileTypeB ? -1 : 1;
13769 })
13770 };
13771}
13772function writeOutputFile(graph, build, outputFile, outputOptions) {
13773 const fileName = resolve(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
13774 let writeSourceMapPromise;
13775 let source;
13776 if (outputFile.type === 'asset') {
13777 source = outputFile.source;
13778 }
13779 else {
13780 source = outputFile.code;
13781 if (outputOptions.sourcemap && outputFile.map) {
13782 let url;
13783 if (outputOptions.sourcemap === 'inline') {
13784 url = outputFile.map.toUrl();
13785 }
13786 else {
13787 url = `${basename(outputFile.fileName)}.map`;
13788 writeSourceMapPromise = writeFile(`${fileName}.map`, outputFile.map.toString());
13789 }
13790 if (outputOptions.sourcemap !== 'hidden') {
13791 source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
13792 }
13793 }
13794 }
13795 return writeFile(fileName, source)
13796 .then(() => writeSourceMapPromise)
13797 .then(() => outputFile.type === 'chunk' &&
13798 graph.pluginDriver.hookSeq('onwrite', [
13799 Object.assign({ bundle: build }, outputOptions),
13800 outputFile
13801 ]))
13802 .then(() => { });
13803}
13804function normalizeOutputOptions(inputOptions, rawOutputOptions, hasMultipleChunks, pluginDriver) {
13805 if (!rawOutputOptions) {
13806 throw new Error('You must supply an options object');
13807 }
13808 const mergedOptions = mergeOptions({
13809 config: {
13810 output: Object.assign(Object.assign(Object.assign({}, rawOutputOptions), rawOutputOptions.output), inputOptions.output)
13811 }
13812 });
13813 if (mergedOptions.optionError)
13814 throw new Error(mergedOptions.optionError);
13815 // now outputOptions is an array, but rollup.rollup API doesn't support arrays
13816 const mergedOutputOptions = mergedOptions.outputOptions[0];
13817 const outputOptionsReducer = (outputOptions, result) => result || outputOptions;
13818 const outputOptions = pluginDriver.hookReduceArg0Sync('outputOptions', [mergedOutputOptions], outputOptionsReducer, pluginContext => {
13819 const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
13820 return Object.assign(Object.assign({}, pluginContext), { emitFile: emitError, setAssetSource: emitError });
13821 });
13822 checkOutputOptions(outputOptions);
13823 if (typeof outputOptions.file === 'string') {
13824 if (typeof outputOptions.dir === 'string')
13825 error({
13826 code: 'INVALID_OPTION',
13827 message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
13828 });
13829 if (inputOptions.preserveModules) {
13830 error({
13831 code: 'INVALID_OPTION',
13832 message: 'You must set "output.dir" instead of "output.file" when using the "preserveModules" option.'
13833 });
13834 }
13835 if (typeof inputOptions.input === 'object' && !Array.isArray(inputOptions.input))
13836 error({
13837 code: 'INVALID_OPTION',
13838 message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
13839 });
13840 }
13841 if (hasMultipleChunks) {
13842 if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
13843 error({
13844 code: 'INVALID_OPTION',
13845 message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
13846 });
13847 if (typeof outputOptions.file === 'string')
13848 error({
13849 code: 'INVALID_OPTION',
13850 message: 'You must set "output.dir" instead of "output.file" when generating multiple chunks.'
13851 });
13852 }
13853 return outputOptions;
13854}
13855
13856var utils$1 = createCommonjsModule(function (module, exports) {
13857 exports.isInteger = num => {
13858 if (typeof num === 'number') {
13859 return Number.isInteger(num);
13860 }
13861 if (typeof num === 'string' && num.trim() !== '') {
13862 return Number.isInteger(Number(num));
13863 }
13864 return false;
13865 };
13866 /**
13867 * Find a node of the given type
13868 */
13869 exports.find = (node, type) => node.nodes.find(node => node.type === type);
13870 /**
13871 * Find a node of the given type
13872 */
13873 exports.exceedsLimit = (min, max, step = 1, limit) => {
13874 if (limit === false)
13875 return false;
13876 if (!exports.isInteger(min) || !exports.isInteger(max))
13877 return false;
13878 return ((Number(max) - Number(min)) / Number(step)) >= limit;
13879 };
13880 /**
13881 * Escape the given node with '\\' before node.value
13882 */
13883 exports.escapeNode = (block, n = 0, type) => {
13884 let node = block.nodes[n];
13885 if (!node)
13886 return;
13887 if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
13888 if (node.escaped !== true) {
13889 node.value = '\\' + node.value;
13890 node.escaped = true;
13891 }
13892 }
13893 };
13894 /**
13895 * Returns true if the given brace node should be enclosed in literal braces
13896 */
13897 exports.encloseBrace = node => {
13898 if (node.type !== 'brace')
13899 return false;
13900 if ((node.commas >> 0 + node.ranges >> 0) === 0) {
13901 node.invalid = true;
13902 return true;
13903 }
13904 return false;
13905 };
13906 /**
13907 * Returns true if a brace node is invalid.
13908 */
13909 exports.isInvalidBrace = block => {
13910 if (block.type !== 'brace')
13911 return false;
13912 if (block.invalid === true || block.dollar)
13913 return true;
13914 if ((block.commas >> 0 + block.ranges >> 0) === 0) {
13915 block.invalid = true;
13916 return true;
13917 }
13918 if (block.open !== true || block.close !== true) {
13919 block.invalid = true;
13920 return true;
13921 }
13922 return false;
13923 };
13924 /**
13925 * Returns true if a node is an open or close node
13926 */
13927 exports.isOpenOrClose = node => {
13928 if (node.type === 'open' || node.type === 'close') {
13929 return true;
13930 }
13931 return node.open === true || node.close === true;
13932 };
13933 /**
13934 * Reduce an array of text nodes.
13935 */
13936 exports.reduce = nodes => nodes.reduce((acc, node) => {
13937 if (node.type === 'text')
13938 acc.push(node.value);
13939 if (node.type === 'range')
13940 node.type = 'text';
13941 return acc;
13942 }, []);
13943 /**
13944 * Flatten an array
13945 */
13946 exports.flatten = (...args) => {
13947 const result = [];
13948 const flat = arr => {
13949 for (let i = 0; i < arr.length; i++) {
13950 let ele = arr[i];
13951 Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
13952 }
13953 return result;
13954 };
13955 flat(args);
13956 return result;
13957 };
13958});
13959
13960var stringify = (ast, options = {}) => {
13961 let stringify = (node, parent = {}) => {
13962 let invalidBlock = options.escapeInvalid && utils$1.isInvalidBrace(parent);
13963 let invalidNode = node.invalid === true && options.escapeInvalid === true;
13964 let output = '';
13965 if (node.value) {
13966 if ((invalidBlock || invalidNode) && utils$1.isOpenOrClose(node)) {
13967 return '\\' + node.value;
13968 }
13969 return node.value;
13970 }
13971 if (node.value) {
13972 return node.value;
13973 }
13974 if (node.nodes) {
13975 for (let child of node.nodes) {
13976 output += stringify(child);
13977 }
13978 }
13979 return output;
13980 };
13981 return stringify(ast);
13982};
13983
13984/*!
13985 * is-number <https://github.com/jonschlinkert/is-number>
13986 *
13987 * Copyright (c) 2014-present, Jon Schlinkert.
13988 * Released under the MIT License.
13989 */
13990var isNumber = function (num) {
13991 if (typeof num === 'number') {
13992 return num - num === 0;
13993 }
13994 if (typeof num === 'string' && num.trim() !== '') {
13995 return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
13996 }
13997 return false;
13998};
13999
14000const toRegexRange = (min, max, options) => {
14001 if (isNumber(min) === false) {
14002 throw new TypeError('toRegexRange: expected the first argument to be a number');
14003 }
14004 if (max === void 0 || min === max) {
14005 return String(min);
14006 }
14007 if (isNumber(max) === false) {
14008 throw new TypeError('toRegexRange: expected the second argument to be a number.');
14009 }
14010 let opts = Object.assign({ relaxZeros: true }, options);
14011 if (typeof opts.strictZeros === 'boolean') {
14012 opts.relaxZeros = opts.strictZeros === false;
14013 }
14014 let relax = String(opts.relaxZeros);
14015 let shorthand = String(opts.shorthand);
14016 let capture = String(opts.capture);
14017 let wrap = String(opts.wrap);
14018 let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
14019 if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
14020 return toRegexRange.cache[cacheKey].result;
14021 }
14022 let a = Math.min(min, max);
14023 let b = Math.max(min, max);
14024 if (Math.abs(a - b) === 1) {
14025 let result = min + '|' + max;
14026 if (opts.capture) {
14027 return `(${result})`;
14028 }
14029 if (opts.wrap === false) {
14030 return result;
14031 }
14032 return `(?:${result})`;
14033 }
14034 let isPadded = hasPadding(min) || hasPadding(max);
14035 let state = { min, max, a, b };
14036 let positives = [];
14037 let negatives = [];
14038 if (isPadded) {
14039 state.isPadded = isPadded;
14040 state.maxLen = String(state.max).length;
14041 }
14042 if (a < 0) {
14043 let newMin = b < 0 ? Math.abs(b) : 1;
14044 negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
14045 a = state.a = 0;
14046 }
14047 if (b >= 0) {
14048 positives = splitToPatterns(a, b, state, opts);
14049 }
14050 state.negatives = negatives;
14051 state.positives = positives;
14052 state.result = collatePatterns(negatives, positives);
14053 if (opts.capture === true) {
14054 state.result = `(${state.result})`;
14055 }
14056 else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
14057 state.result = `(?:${state.result})`;
14058 }
14059 toRegexRange.cache[cacheKey] = state;
14060 return state.result;
14061};
14062function collatePatterns(neg, pos, options) {
14063 let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
14064 let onlyPositive = filterPatterns(pos, neg, '', false) || [];
14065 let intersected = filterPatterns(neg, pos, '-?', true) || [];
14066 let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
14067 return subpatterns.join('|');
14068}
14069function splitToRanges(min, max) {
14070 let nines = 1;
14071 let zeros = 1;
14072 let stop = countNines(min, nines);
14073 let stops = new Set([max]);
14074 while (min <= stop && stop <= max) {
14075 stops.add(stop);
14076 nines += 1;
14077 stop = countNines(min, nines);
14078 }
14079 stop = countZeros(max + 1, zeros) - 1;
14080 while (min < stop && stop <= max) {
14081 stops.add(stop);
14082 zeros += 1;
14083 stop = countZeros(max + 1, zeros) - 1;
14084 }
14085 stops = [...stops];
14086 stops.sort(compare);
14087 return stops;
14088}
14089/**
14090 * Convert a range to a regex pattern
14091 * @param {Number} `start`
14092 * @param {Number} `stop`
14093 * @return {String}
14094 */
14095function rangeToPattern(start, stop, options) {
14096 if (start === stop) {
14097 return { pattern: start, count: [], digits: 0 };
14098 }
14099 let zipped = zip(start, stop);
14100 let digits = zipped.length;
14101 let pattern = '';
14102 let count = 0;
14103 for (let i = 0; i < digits; i++) {
14104 let [startDigit, stopDigit] = zipped[i];
14105 if (startDigit === stopDigit) {
14106 pattern += startDigit;
14107 }
14108 else if (startDigit !== '0' || stopDigit !== '9') {
14109 pattern += toCharacterClass(startDigit, stopDigit);
14110 }
14111 else {
14112 count++;
14113 }
14114 }
14115 if (count) {
14116 pattern += options.shorthand === true ? '\\d' : '[0-9]';
14117 }
14118 return { pattern, count: [count], digits };
14119}
14120function splitToPatterns(min, max, tok, options) {
14121 let ranges = splitToRanges(min, max);
14122 let tokens = [];
14123 let start = min;
14124 let prev;
14125 for (let i = 0; i < ranges.length; i++) {
14126 let max = ranges[i];
14127 let obj = rangeToPattern(String(start), String(max), options);
14128 let zeros = '';
14129 if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
14130 if (prev.count.length > 1) {
14131 prev.count.pop();
14132 }
14133 prev.count.push(obj.count[0]);
14134 prev.string = prev.pattern + toQuantifier(prev.count);
14135 start = max + 1;
14136 continue;
14137 }
14138 if (tok.isPadded) {
14139 zeros = padZeros(max, tok, options);
14140 }
14141 obj.string = zeros + obj.pattern + toQuantifier(obj.count);
14142 tokens.push(obj);
14143 start = max + 1;
14144 prev = obj;
14145 }
14146 return tokens;
14147}
14148function filterPatterns(arr, comparison, prefix, intersection, options) {
14149 let result = [];
14150 for (let ele of arr) {
14151 let { string } = ele;
14152 // only push if _both_ are negative...
14153 if (!intersection && !contains(comparison, 'string', string)) {
14154 result.push(prefix + string);
14155 }
14156 // or _both_ are positive
14157 if (intersection && contains(comparison, 'string', string)) {
14158 result.push(prefix + string);
14159 }
14160 }
14161 return result;
14162}
14163/**
14164 * Zip strings
14165 */
14166function zip(a, b) {
14167 let arr = [];
14168 for (let i = 0; i < a.length; i++)
14169 arr.push([a[i], b[i]]);
14170 return arr;
14171}
14172function compare(a, b) {
14173 return a > b ? 1 : b > a ? -1 : 0;
14174}
14175function contains(arr, key, val) {
14176 return arr.some(ele => ele[key] === val);
14177}
14178function countNines(min, len) {
14179 return Number(String(min).slice(0, -len) + '9'.repeat(len));
14180}
14181function countZeros(integer, zeros) {
14182 return integer - (integer % Math.pow(10, zeros));
14183}
14184function toQuantifier(digits) {
14185 let [start = 0, stop = ''] = digits;
14186 if (stop || start > 1) {
14187 return `{${start + (stop ? ',' + stop : '')}}`;
14188 }
14189 return '';
14190}
14191function toCharacterClass(a, b, options) {
14192 return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
14193}
14194function hasPadding(str) {
14195 return /^-?(0+)\d/.test(str);
14196}
14197function padZeros(value, tok, options) {
14198 if (!tok.isPadded) {
14199 return value;
14200 }
14201 let diff = Math.abs(tok.maxLen - String(value).length);
14202 let relax = options.relaxZeros !== false;
14203 switch (diff) {
14204 case 0:
14205 return '';
14206 case 1:
14207 return relax ? '0?' : '0';
14208 case 2:
14209 return relax ? '0{0,2}' : '00';
14210 default: {
14211 return relax ? `0{0,${diff}}` : `0{${diff}}`;
14212 }
14213 }
14214}
14215/**
14216 * Cache
14217 */
14218toRegexRange.cache = {};
14219toRegexRange.clearCache = () => (toRegexRange.cache = {});
14220/**
14221 * Expose `toRegexRange`
14222 */
14223var toRegexRange_1 = toRegexRange;
14224
14225const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
14226const transform$1 = toNumber => {
14227 return value => toNumber === true ? Number(value) : String(value);
14228};
14229const isValidValue = value => {
14230 return typeof value === 'number' || (typeof value === 'string' && value !== '');
14231};
14232const isNumber$1 = num => Number.isInteger(+num);
14233const zeros = input => {
14234 let value = `${input}`;
14235 let index = -1;
14236 if (value[0] === '-')
14237 value = value.slice(1);
14238 if (value === '0')
14239 return false;
14240 while (value[++index] === '0')
14241 ;
14242 return index > 0;
14243};
14244const stringify$1 = (start, end, options) => {
14245 if (typeof start === 'string' || typeof end === 'string') {
14246 return true;
14247 }
14248 return options.stringify === true;
14249};
14250const pad = (input, maxLength, toNumber) => {
14251 if (maxLength > 0) {
14252 let dash = input[0] === '-' ? '-' : '';
14253 if (dash)
14254 input = input.slice(1);
14255 input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
14256 }
14257 if (toNumber === false) {
14258 return String(input);
14259 }
14260 return input;
14261};
14262const toMaxLen = (input, maxLength) => {
14263 let negative = input[0] === '-' ? '-' : '';
14264 if (negative) {
14265 input = input.slice(1);
14266 maxLength--;
14267 }
14268 while (input.length < maxLength)
14269 input = '0' + input;
14270 return negative ? ('-' + input) : input;
14271};
14272const toSequence = (parts, options) => {
14273 parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
14274 parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
14275 let prefix = options.capture ? '' : '?:';
14276 let positives = '';
14277 let negatives = '';
14278 let result;
14279 if (parts.positives.length) {
14280 positives = parts.positives.join('|');
14281 }
14282 if (parts.negatives.length) {
14283 negatives = `-(${prefix}${parts.negatives.join('|')})`;
14284 }
14285 if (positives && negatives) {
14286 result = `${positives}|${negatives}`;
14287 }
14288 else {
14289 result = positives || negatives;
14290 }
14291 if (options.wrap) {
14292 return `(${prefix}${result})`;
14293 }
14294 return result;
14295};
14296const toRange = (a, b, isNumbers, options) => {
14297 if (isNumbers) {
14298 return toRegexRange_1(a, b, Object.assign({ wrap: false }, options));
14299 }
14300 let start = String.fromCharCode(a);
14301 if (a === b)
14302 return start;
14303 let stop = String.fromCharCode(b);
14304 return `[${start}-${stop}]`;
14305};
14306const toRegex = (start, end, options) => {
14307 if (Array.isArray(start)) {
14308 let wrap = options.wrap === true;
14309 let prefix = options.capture ? '' : '?:';
14310 return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
14311 }
14312 return toRegexRange_1(start, end, options);
14313};
14314const rangeError = (...args) => {
14315 return new RangeError('Invalid range arguments: ' + util.inspect(...args));
14316};
14317const invalidRange = (start, end, options) => {
14318 if (options.strictRanges === true)
14319 throw rangeError([start, end]);
14320 return [];
14321};
14322const invalidStep = (step, options) => {
14323 if (options.strictRanges === true) {
14324 throw new TypeError(`Expected step "${step}" to be a number`);
14325 }
14326 return [];
14327};
14328const fillNumbers = (start, end, step = 1, options = {}) => {
14329 let a = Number(start);
14330 let b = Number(end);
14331 if (!Number.isInteger(a) || !Number.isInteger(b)) {
14332 if (options.strictRanges === true)
14333 throw rangeError([start, end]);
14334 return [];
14335 }
14336 // fix negative zero
14337 if (a === 0)
14338 a = 0;
14339 if (b === 0)
14340 b = 0;
14341 let descending = a > b;
14342 let startString = String(start);
14343 let endString = String(end);
14344 let stepString = String(step);
14345 step = Math.max(Math.abs(step), 1);
14346 let padded = zeros(startString) || zeros(endString) || zeros(stepString);
14347 let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
14348 let toNumber = padded === false && stringify$1(start, end, options) === false;
14349 let format = options.transform || transform$1(toNumber);
14350 if (options.toRegex && step === 1) {
14351 return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
14352 }
14353 let parts = { negatives: [], positives: [] };
14354 let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
14355 let range = [];
14356 let index = 0;
14357 while (descending ? a >= b : a <= b) {
14358 if (options.toRegex === true && step > 1) {
14359 push(a);
14360 }
14361 else {
14362 range.push(pad(format(a, index), maxLen, toNumber));
14363 }
14364 a = descending ? a - step : a + step;
14365 index++;
14366 }
14367 if (options.toRegex === true) {
14368 return step > 1
14369 ? toSequence(parts, options)
14370 : toRegex(range, null, Object.assign({ wrap: false }, options));
14371 }
14372 return range;
14373};
14374const fillLetters = (start, end, step = 1, options = {}) => {
14375 if ((!isNumber$1(start) && start.length > 1) || (!isNumber$1(end) && end.length > 1)) {
14376 return invalidRange(start, end, options);
14377 }
14378 let format = options.transform || (val => String.fromCharCode(val));
14379 let a = `${start}`.charCodeAt(0);
14380 let b = `${end}`.charCodeAt(0);
14381 let descending = a > b;
14382 let min = Math.min(a, b);
14383 let max = Math.max(a, b);
14384 if (options.toRegex && step === 1) {
14385 return toRange(min, max, false, options);
14386 }
14387 let range = [];
14388 let index = 0;
14389 while (descending ? a >= b : a <= b) {
14390 range.push(format(a, index));
14391 a = descending ? a - step : a + step;
14392 index++;
14393 }
14394 if (options.toRegex === true) {
14395 return toRegex(range, null, { wrap: false, options });
14396 }
14397 return range;
14398};
14399const fill = (start, end, step, options = {}) => {
14400 if (end == null && isValidValue(start)) {
14401 return [start];
14402 }
14403 if (!isValidValue(start) || !isValidValue(end)) {
14404 return invalidRange(start, end, options);
14405 }
14406 if (typeof step === 'function') {
14407 return fill(start, end, 1, { transform: step });
14408 }
14409 if (isObject$1(step)) {
14410 return fill(start, end, 0, step);
14411 }
14412 let opts = Object.assign({}, options);
14413 if (opts.capture === true)
14414 opts.wrap = true;
14415 step = step || opts.step || 1;
14416 if (!isNumber$1(step)) {
14417 if (step != null && !isObject$1(step))
14418 return invalidStep(step, opts);
14419 return fill(start, end, 1, step);
14420 }
14421 if (isNumber$1(start) && isNumber$1(end)) {
14422 return fillNumbers(start, end, step, opts);
14423 }
14424 return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
14425};
14426var fillRange = fill;
14427
14428const compile = (ast, options = {}) => {
14429 let walk = (node, parent = {}) => {
14430 let invalidBlock = utils$1.isInvalidBrace(parent);
14431 let invalidNode = node.invalid === true && options.escapeInvalid === true;
14432 let invalid = invalidBlock === true || invalidNode === true;
14433 let prefix = options.escapeInvalid === true ? '\\' : '';
14434 let output = '';
14435 if (node.isOpen === true) {
14436 return prefix + node.value;
14437 }
14438 if (node.isClose === true) {
14439 return prefix + node.value;
14440 }
14441 if (node.type === 'open') {
14442 return invalid ? (prefix + node.value) : '(';
14443 }
14444 if (node.type === 'close') {
14445 return invalid ? (prefix + node.value) : ')';
14446 }
14447 if (node.type === 'comma') {
14448 return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
14449 }
14450 if (node.value) {
14451 return node.value;
14452 }
14453 if (node.nodes && node.ranges > 0) {
14454 let args = utils$1.reduce(node.nodes);
14455 let range = fillRange(...args, Object.assign(Object.assign({}, options), { wrap: false, toRegex: true }));
14456 if (range.length !== 0) {
14457 return args.length > 1 && range.length > 1 ? `(${range})` : range;
14458 }
14459 }
14460 if (node.nodes) {
14461 for (let child of node.nodes) {
14462 output += walk(child, node);
14463 }
14464 }
14465 return output;
14466 };
14467 return walk(ast);
14468};
14469var compile_1 = compile;
14470
14471const append = (queue = '', stash = '', enclose = false) => {
14472 let result = [];
14473 queue = [].concat(queue);
14474 stash = [].concat(stash);
14475 if (!stash.length)
14476 return queue;
14477 if (!queue.length) {
14478 return enclose ? utils$1.flatten(stash).map(ele => `{${ele}}`) : stash;
14479 }
14480 for (let item of queue) {
14481 if (Array.isArray(item)) {
14482 for (let value of item) {
14483 result.push(append(value, stash, enclose));
14484 }
14485 }
14486 else {
14487 for (let ele of stash) {
14488 if (enclose === true && typeof ele === 'string')
14489 ele = `{${ele}}`;
14490 result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
14491 }
14492 }
14493 }
14494 return utils$1.flatten(result);
14495};
14496const expand = (ast, options = {}) => {
14497 let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
14498 let walk = (node, parent = {}) => {
14499 node.queue = [];
14500 let p = parent;
14501 let q = parent.queue;
14502 while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
14503 p = p.parent;
14504 q = p.queue;
14505 }
14506 if (node.invalid || node.dollar) {
14507 q.push(append(q.pop(), stringify(node, options)));
14508 return;
14509 }
14510 if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
14511 q.push(append(q.pop(), ['{}']));
14512 return;
14513 }
14514 if (node.nodes && node.ranges > 0) {
14515 let args = utils$1.reduce(node.nodes);
14516 if (utils$1.exceedsLimit(...args, options.step, rangeLimit)) {
14517 throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
14518 }
14519 let range = fillRange(...args, options);
14520 if (range.length === 0) {
14521 range = stringify(node, options);
14522 }
14523 q.push(append(q.pop(), range));
14524 node.nodes = [];
14525 return;
14526 }
14527 let enclose = utils$1.encloseBrace(node);
14528 let queue = node.queue;
14529 let block = node;
14530 while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
14531 block = block.parent;
14532 queue = block.queue;
14533 }
14534 for (let i = 0; i < node.nodes.length; i++) {
14535 let child = node.nodes[i];
14536 if (child.type === 'comma' && node.type === 'brace') {
14537 if (i === 1)
14538 queue.push('');
14539 queue.push('');
14540 continue;
14541 }
14542 if (child.type === 'close') {
14543 q.push(append(q.pop(), queue, enclose));
14544 continue;
14545 }
14546 if (child.value && child.type !== 'open') {
14547 queue.push(append(queue.pop(), child.value));
14548 continue;
14549 }
14550 if (child.nodes) {
14551 walk(child, node);
14552 }
14553 }
14554 return queue;
14555 };
14556 return utils$1.flatten(walk(ast));
14557};
14558var expand_1 = expand;
14559
14560var constants = {
14561 MAX_LENGTH: 1024 * 64,
14562 // Digits
14563 CHAR_0: '0',
14564 CHAR_9: '9',
14565 // Alphabet chars.
14566 CHAR_UPPERCASE_A: 'A',
14567 CHAR_LOWERCASE_A: 'a',
14568 CHAR_UPPERCASE_Z: 'Z',
14569 CHAR_LOWERCASE_Z: 'z',
14570 CHAR_LEFT_PARENTHESES: '(',
14571 CHAR_RIGHT_PARENTHESES: ')',
14572 CHAR_ASTERISK: '*',
14573 // Non-alphabetic chars.
14574 CHAR_AMPERSAND: '&',
14575 CHAR_AT: '@',
14576 CHAR_BACKSLASH: '\\',
14577 CHAR_BACKTICK: '`',
14578 CHAR_CARRIAGE_RETURN: '\r',
14579 CHAR_CIRCUMFLEX_ACCENT: '^',
14580 CHAR_COLON: ':',
14581 CHAR_COMMA: ',',
14582 CHAR_DOLLAR: '$',
14583 CHAR_DOT: '.',
14584 CHAR_DOUBLE_QUOTE: '"',
14585 CHAR_EQUAL: '=',
14586 CHAR_EXCLAMATION_MARK: '!',
14587 CHAR_FORM_FEED: '\f',
14588 CHAR_FORWARD_SLASH: '/',
14589 CHAR_HASH: '#',
14590 CHAR_HYPHEN_MINUS: '-',
14591 CHAR_LEFT_ANGLE_BRACKET: '<',
14592 CHAR_LEFT_CURLY_BRACE: '{',
14593 CHAR_LEFT_SQUARE_BRACKET: '[',
14594 CHAR_LINE_FEED: '\n',
14595 CHAR_NO_BREAK_SPACE: '\u00A0',
14596 CHAR_PERCENT: '%',
14597 CHAR_PLUS: '+',
14598 CHAR_QUESTION_MARK: '?',
14599 CHAR_RIGHT_ANGLE_BRACKET: '>',
14600 CHAR_RIGHT_CURLY_BRACE: '}',
14601 CHAR_RIGHT_SQUARE_BRACKET: ']',
14602 CHAR_SEMICOLON: ';',
14603 CHAR_SINGLE_QUOTE: '\'',
14604 CHAR_SPACE: ' ',
14605 CHAR_TAB: '\t',
14606 CHAR_UNDERSCORE: '_',
14607 CHAR_VERTICAL_LINE: '|',
14608 CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
14609};
14610
14611/**
14612 * Constants
14613 */
14614const { 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;
14615/**
14616 * parse
14617 */
14618const parse = (input, options = {}) => {
14619 if (typeof input !== 'string') {
14620 throw new TypeError('Expected a string');
14621 }
14622 let opts = options || {};
14623 let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
14624 if (input.length > max) {
14625 throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
14626 }
14627 let ast = { type: 'root', input, nodes: [] };
14628 let stack = [ast];
14629 let block = ast;
14630 let prev = ast;
14631 let brackets = 0;
14632 let length = input.length;
14633 let index = 0;
14634 let depth = 0;
14635 let value;
14636 /**
14637 * Helpers
14638 */
14639 const advance = () => input[index++];
14640 const push = node => {
14641 if (node.type === 'text' && prev.type === 'dot') {
14642 prev.type = 'text';
14643 }
14644 if (prev && prev.type === 'text' && node.type === 'text') {
14645 prev.value += node.value;
14646 return;
14647 }
14648 block.nodes.push(node);
14649 node.parent = block;
14650 node.prev = prev;
14651 prev = node;
14652 return node;
14653 };
14654 push({ type: 'bos' });
14655 while (index < length) {
14656 block = stack[stack.length - 1];
14657 value = advance();
14658 /**
14659 * Invalid chars
14660 */
14661 if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
14662 continue;
14663 }
14664 /**
14665 * Escaped chars
14666 */
14667 if (value === CHAR_BACKSLASH) {
14668 push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
14669 continue;
14670 }
14671 /**
14672 * Right square bracket (literal): ']'
14673 */
14674 if (value === CHAR_RIGHT_SQUARE_BRACKET) {
14675 push({ type: 'text', value: '\\' + value });
14676 continue;
14677 }
14678 /**
14679 * Left square bracket: '['
14680 */
14681 if (value === CHAR_LEFT_SQUARE_BRACKET) {
14682 brackets++;
14683 let next;
14684 while (index < length && (next = advance())) {
14685 value += next;
14686 if (next === CHAR_LEFT_SQUARE_BRACKET) {
14687 brackets++;
14688 continue;
14689 }
14690 if (next === CHAR_BACKSLASH) {
14691 value += advance();
14692 continue;
14693 }
14694 if (next === CHAR_RIGHT_SQUARE_BRACKET) {
14695 brackets--;
14696 if (brackets === 0) {
14697 break;
14698 }
14699 }
14700 }
14701 push({ type: 'text', value });
14702 continue;
14703 }
14704 /**
14705 * Parentheses
14706 */
14707 if (value === CHAR_LEFT_PARENTHESES) {
14708 block = push({ type: 'paren', nodes: [] });
14709 stack.push(block);
14710 push({ type: 'text', value });
14711 continue;
14712 }
14713 if (value === CHAR_RIGHT_PARENTHESES) {
14714 if (block.type !== 'paren') {
14715 push({ type: 'text', value });
14716 continue;
14717 }
14718 block = stack.pop();
14719 push({ type: 'text', value });
14720 block = stack[stack.length - 1];
14721 continue;
14722 }
14723 /**
14724 * Quotes: '|"|`
14725 */
14726 if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
14727 let open = value;
14728 let next;
14729 if (options.keepQuotes !== true) {
14730 value = '';
14731 }
14732 while (index < length && (next = advance())) {
14733 if (next === CHAR_BACKSLASH) {
14734 value += next + advance();
14735 continue;
14736 }
14737 if (next === open) {
14738 if (options.keepQuotes === true)
14739 value += next;
14740 break;
14741 }
14742 value += next;
14743 }
14744 push({ type: 'text', value });
14745 continue;
14746 }
14747 /**
14748 * Left curly brace: '{'
14749 */
14750 if (value === CHAR_LEFT_CURLY_BRACE) {
14751 depth++;
14752 let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
14753 let brace = {
14754 type: 'brace',
14755 open: true,
14756 close: false,
14757 dollar,
14758 depth,
14759 commas: 0,
14760 ranges: 0,
14761 nodes: []
14762 };
14763 block = push(brace);
14764 stack.push(block);
14765 push({ type: 'open', value });
14766 continue;
14767 }
14768 /**
14769 * Right curly brace: '}'
14770 */
14771 if (value === CHAR_RIGHT_CURLY_BRACE) {
14772 if (block.type !== 'brace') {
14773 push({ type: 'text', value });
14774 continue;
14775 }
14776 let type = 'close';
14777 block = stack.pop();
14778 block.close = true;
14779 push({ type, value });
14780 depth--;
14781 block = stack[stack.length - 1];
14782 continue;
14783 }
14784 /**
14785 * Comma: ','
14786 */
14787 if (value === CHAR_COMMA && depth > 0) {
14788 if (block.ranges > 0) {
14789 block.ranges = 0;
14790 let open = block.nodes.shift();
14791 block.nodes = [open, { type: 'text', value: stringify(block) }];
14792 }
14793 push({ type: 'comma', value });
14794 block.commas++;
14795 continue;
14796 }
14797 /**
14798 * Dot: '.'
14799 */
14800 if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
14801 let siblings = block.nodes;
14802 if (depth === 0 || siblings.length === 0) {
14803 push({ type: 'text', value });
14804 continue;
14805 }
14806 if (prev.type === 'dot') {
14807 block.range = [];
14808 prev.value += value;
14809 prev.type = 'range';
14810 if (block.nodes.length !== 3 && block.nodes.length !== 5) {
14811 block.invalid = true;
14812 block.ranges = 0;
14813 prev.type = 'text';
14814 continue;
14815 }
14816 block.ranges++;
14817 block.args = [];
14818 continue;
14819 }
14820 if (prev.type === 'range') {
14821 siblings.pop();
14822 let before = siblings[siblings.length - 1];
14823 before.value += prev.value + value;
14824 prev = before;
14825 block.ranges--;
14826 continue;
14827 }
14828 push({ type: 'dot', value });
14829 continue;
14830 }
14831 /**
14832 * Text
14833 */
14834 push({ type: 'text', value });
14835 }
14836 // Mark imbalanced braces and brackets as invalid
14837 do {
14838 block = stack.pop();
14839 if (block.type !== 'root') {
14840 block.nodes.forEach(node => {
14841 if (!node.nodes) {
14842 if (node.type === 'open')
14843 node.isOpen = true;
14844 if (node.type === 'close')
14845 node.isClose = true;
14846 if (!node.nodes)
14847 node.type = 'text';
14848 node.invalid = true;
14849 }
14850 });
14851 // get the location of the block on parent.nodes (block's siblings)
14852 let parent = stack[stack.length - 1];
14853 let index = parent.nodes.indexOf(block);
14854 // replace the (invalid) block with it's nodes
14855 parent.nodes.splice(index, 1, ...block.nodes);
14856 }
14857 } while (stack.length > 0);
14858 push({ type: 'eos' });
14859 return ast;
14860};
14861var parse_1 = parse;
14862
14863/**
14864 * Expand the given pattern or create a regex-compatible string.
14865 *
14866 * ```js
14867 * const braces = require('braces');
14868 * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
14869 * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
14870 * ```
14871 * @param {String} `str`
14872 * @param {Object} `options`
14873 * @return {String}
14874 * @api public
14875 */
14876const braces = (input, options = {}) => {
14877 let output = [];
14878 if (Array.isArray(input)) {
14879 for (let pattern of input) {
14880 let result = braces.create(pattern, options);
14881 if (Array.isArray(result)) {
14882 output.push(...result);
14883 }
14884 else {
14885 output.push(result);
14886 }
14887 }
14888 }
14889 else {
14890 output = [].concat(braces.create(input, options));
14891 }
14892 if (options && options.expand === true && options.nodupes === true) {
14893 output = [...new Set(output)];
14894 }
14895 return output;
14896};
14897/**
14898 * Parse the given `str` with the given `options`.
14899 *
14900 * ```js
14901 * // braces.parse(pattern, [, options]);
14902 * const ast = braces.parse('a/{b,c}/d');
14903 * console.log(ast);
14904 * ```
14905 * @param {String} pattern Brace pattern to parse
14906 * @param {Object} options
14907 * @return {Object} Returns an AST
14908 * @api public
14909 */
14910braces.parse = (input, options = {}) => parse_1(input, options);
14911/**
14912 * Creates a braces string from an AST, or an AST node.
14913 *
14914 * ```js
14915 * const braces = require('braces');
14916 * let ast = braces.parse('foo/{a,b}/bar');
14917 * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
14918 * ```
14919 * @param {String} `input` Brace pattern or AST.
14920 * @param {Object} `options`
14921 * @return {Array} Returns an array of expanded values.
14922 * @api public
14923 */
14924braces.stringify = (input, options = {}) => {
14925 if (typeof input === 'string') {
14926 return stringify(braces.parse(input, options), options);
14927 }
14928 return stringify(input, options);
14929};
14930/**
14931 * Compiles a brace pattern into a regex-compatible, optimized string.
14932 * This method is called by the main [braces](#braces) function by default.
14933 *
14934 * ```js
14935 * const braces = require('braces');
14936 * console.log(braces.compile('a/{b,c}/d'));
14937 * //=> ['a/(b|c)/d']
14938 * ```
14939 * @param {String} `input` Brace pattern or AST.
14940 * @param {Object} `options`
14941 * @return {Array} Returns an array of expanded values.
14942 * @api public
14943 */
14944braces.compile = (input, options = {}) => {
14945 if (typeof input === 'string') {
14946 input = braces.parse(input, options);
14947 }
14948 return compile_1(input, options);
14949};
14950/**
14951 * Expands a brace pattern into an array. This method is called by the
14952 * main [braces](#braces) function when `options.expand` is true. Before
14953 * using this method it's recommended that you read the [performance notes](#performance))
14954 * and advantages of using [.compile](#compile) instead.
14955 *
14956 * ```js
14957 * const braces = require('braces');
14958 * console.log(braces.expand('a/{b,c}/d'));
14959 * //=> ['a/b/d', 'a/c/d'];
14960 * ```
14961 * @param {String} `pattern` Brace pattern
14962 * @param {Object} `options`
14963 * @return {Array} Returns an array of expanded values.
14964 * @api public
14965 */
14966braces.expand = (input, options = {}) => {
14967 if (typeof input === 'string') {
14968 input = braces.parse(input, options);
14969 }
14970 let result = expand_1(input, options);
14971 // filter out empty strings if specified
14972 if (options.noempty === true) {
14973 result = result.filter(Boolean);
14974 }
14975 // filter out duplicates if specified
14976 if (options.nodupes === true) {
14977 result = [...new Set(result)];
14978 }
14979 return result;
14980};
14981/**
14982 * Processes a brace pattern and returns either an expanded array
14983 * (if `options.expand` is true), a highly optimized regex-compatible string.
14984 * This method is called by the main [braces](#braces) function.
14985 *
14986 * ```js
14987 * const braces = require('braces');
14988 * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
14989 * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
14990 * ```
14991 * @param {String} `pattern` Brace pattern
14992 * @param {Object} `options`
14993 * @return {Array} Returns an array of expanded values.
14994 * @api public
14995 */
14996braces.create = (input, options = {}) => {
14997 if (input === '' || input.length < 3) {
14998 return [input];
14999 }
15000 return options.expand !== true
15001 ? braces.compile(input, options)
15002 : braces.expand(input, options);
15003};
15004/**
15005 * Expose "braces"
15006 */
15007var braces_1 = braces;
15008
15009const WIN_SLASH = '\\\\/';
15010const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
15011/**
15012 * Posix glob regex
15013 */
15014const DOT_LITERAL = '\\.';
15015const PLUS_LITERAL = '\\+';
15016const QMARK_LITERAL = '\\?';
15017const SLASH_LITERAL = '\\/';
15018const ONE_CHAR = '(?=.)';
15019const QMARK = '[^/]';
15020const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
15021const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
15022const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
15023const NO_DOT = `(?!${DOT_LITERAL})`;
15024const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
15025const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
15026const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
15027const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
15028const STAR = `${QMARK}*?`;
15029const POSIX_CHARS = {
15030 DOT_LITERAL,
15031 PLUS_LITERAL,
15032 QMARK_LITERAL,
15033 SLASH_LITERAL,
15034 ONE_CHAR,
15035 QMARK,
15036 END_ANCHOR,
15037 DOTS_SLASH,
15038 NO_DOT,
15039 NO_DOTS,
15040 NO_DOT_SLASH,
15041 NO_DOTS_SLASH,
15042 QMARK_NO_DOT,
15043 STAR,
15044 START_ANCHOR
15045};
15046/**
15047 * Windows glob regex
15048 */
15049const WINDOWS_CHARS = Object.assign(Object.assign({}, POSIX_CHARS), { SLASH_LITERAL: `[${WIN_SLASH}]`, QMARK: WIN_NO_SLASH, STAR: `${WIN_NO_SLASH}*?`, DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, NO_DOT: `(?!${DOT_LITERAL})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH}]`, START_ANCHOR: `(?:^|[${WIN_SLASH}])`, END_ANCHOR: `(?:[${WIN_SLASH}]|$)` });
15050/**
15051 * POSIX Bracket Regex
15052 */
15053const POSIX_REGEX_SOURCE = {
15054 alnum: 'a-zA-Z0-9',
15055 alpha: 'a-zA-Z',
15056 ascii: '\\x00-\\x7F',
15057 blank: ' \\t',
15058 cntrl: '\\x00-\\x1F\\x7F',
15059 digit: '0-9',
15060 graph: '\\x21-\\x7E',
15061 lower: 'a-z',
15062 print: '\\x20-\\x7E ',
15063 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
15064 space: ' \\t\\r\\n\\v\\f',
15065 upper: 'A-Z',
15066 word: 'A-Za-z0-9_',
15067 xdigit: 'A-Fa-f0-9'
15068};
15069var constants$1 = {
15070 MAX_LENGTH: 1024 * 64,
15071 POSIX_REGEX_SOURCE,
15072 // regular expressions
15073 REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
15074 REGEX_NON_SPECIAL_CHAR: /^[^@![\].,$*+?^{}()|\\/]+/,
15075 REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
15076 REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
15077 REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
15078 REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
15079 // Replace globs with equivalent patterns to reduce parsing time.
15080 REPLACEMENTS: {
15081 '***': '*',
15082 '**/**': '**',
15083 '**/**/**': '**'
15084 },
15085 // Digits
15086 CHAR_0: 48,
15087 CHAR_9: 57,
15088 // Alphabet chars.
15089 CHAR_UPPERCASE_A: 65,
15090 CHAR_LOWERCASE_A: 97,
15091 CHAR_UPPERCASE_Z: 90,
15092 CHAR_LOWERCASE_Z: 122,
15093 CHAR_LEFT_PARENTHESES: 40,
15094 CHAR_RIGHT_PARENTHESES: 41,
15095 CHAR_ASTERISK: 42,
15096 // Non-alphabetic chars.
15097 CHAR_AMPERSAND: 38,
15098 CHAR_AT: 64,
15099 CHAR_BACKWARD_SLASH: 92,
15100 CHAR_CARRIAGE_RETURN: 13,
15101 CHAR_CIRCUMFLEX_ACCENT: 94,
15102 CHAR_COLON: 58,
15103 CHAR_COMMA: 44,
15104 CHAR_DOT: 46,
15105 CHAR_DOUBLE_QUOTE: 34,
15106 CHAR_EQUAL: 61,
15107 CHAR_EXCLAMATION_MARK: 33,
15108 CHAR_FORM_FEED: 12,
15109 CHAR_FORWARD_SLASH: 47,
15110 CHAR_GRAVE_ACCENT: 96,
15111 CHAR_HASH: 35,
15112 CHAR_HYPHEN_MINUS: 45,
15113 CHAR_LEFT_ANGLE_BRACKET: 60,
15114 CHAR_LEFT_CURLY_BRACE: 123,
15115 CHAR_LEFT_SQUARE_BRACKET: 91,
15116 CHAR_LINE_FEED: 10,
15117 CHAR_NO_BREAK_SPACE: 160,
15118 CHAR_PERCENT: 37,
15119 CHAR_PLUS: 43,
15120 CHAR_QUESTION_MARK: 63,
15121 CHAR_RIGHT_ANGLE_BRACKET: 62,
15122 CHAR_RIGHT_CURLY_BRACE: 125,
15123 CHAR_RIGHT_SQUARE_BRACKET: 93,
15124 CHAR_SEMICOLON: 59,
15125 CHAR_SINGLE_QUOTE: 39,
15126 CHAR_SPACE: 32,
15127 CHAR_TAB: 9,
15128 CHAR_UNDERSCORE: 95,
15129 CHAR_VERTICAL_LINE: 124,
15130 CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
15131 SEP: path.sep,
15132 /**
15133 * Create EXTGLOB_CHARS
15134 */
15135 extglobChars(chars) {
15136 return {
15137 '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
15138 '?': { type: 'qmark', open: '(?:', close: ')?' },
15139 '+': { type: 'plus', open: '(?:', close: ')+' },
15140 '*': { type: 'star', open: '(?:', close: ')*' },
15141 '@': { type: 'at', open: '(?:', close: ')' }
15142 };
15143 },
15144 /**
15145 * Create GLOB_CHARS
15146 */
15147 globChars(win32) {
15148 return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
15149 }
15150};
15151
15152var utils$2 = createCommonjsModule(function (module, exports) {
15153 const win32 = process.platform === 'win32';
15154 const { REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL, REGEX_REMOVE_BACKSLASH } = constants$1;
15155 exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
15156 exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
15157 exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
15158 exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
15159 exports.toPosixSlashes = str => str.replace(/\\/g, '/');
15160 exports.removeBackslashes = str => {
15161 return str.replace(REGEX_REMOVE_BACKSLASH, match => {
15162 return match === '\\' ? '' : match;
15163 });
15164 };
15165 exports.supportsLookbehinds = () => {
15166 let segs = process.version.slice(1).split('.');
15167 if (segs.length === 3 && +segs[0] >= 9 || (+segs[0] === 8 && +segs[1] >= 10)) {
15168 return true;
15169 }
15170 return false;
15171 };
15172 exports.isWindows = options => {
15173 if (options && typeof options.windows === 'boolean') {
15174 return options.windows;
15175 }
15176 return win32 === true || path.sep === '\\';
15177 };
15178 exports.escapeLast = (input, char, lastIdx) => {
15179 let idx = input.lastIndexOf(char, lastIdx);
15180 if (idx === -1)
15181 return input;
15182 if (input[idx - 1] === '\\')
15183 return exports.escapeLast(input, char, idx - 1);
15184 return input.slice(0, idx) + '\\' + input.slice(idx);
15185 };
15186});
15187
15188const { 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;
15189const isPathSeparator = code => {
15190 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
15191};
15192/**
15193 * Quickly scans a glob pattern and returns an object with a handful of
15194 * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
15195 * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
15196 *
15197 * ```js
15198 * const pm = require('picomatch');
15199 * console.log(pm.scan('foo/bar/*.js'));
15200 * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
15201 * ```
15202 * @param {String} `str`
15203 * @param {Object} `options`
15204 * @return {Object} Returns an object with tokens and regex source string.
15205 * @api public
15206 */
15207var scan = (input, options) => {
15208 let opts = options || {};
15209 let length = input.length - 1;
15210 let index = -1;
15211 let start = 0;
15212 let lastIndex = 0;
15213 let isGlob = false;
15214 let backslashes = false;
15215 let negated = false;
15216 let braces = 0;
15217 let prev;
15218 let code;
15219 let braceEscaped = false;
15220 let eos = () => index >= length;
15221 let advance = () => {
15222 prev = code;
15223 return input.charCodeAt(++index);
15224 };
15225 while (index < length) {
15226 code = advance();
15227 let next;
15228 if (code === CHAR_BACKWARD_SLASH) {
15229 backslashes = true;
15230 next = advance();
15231 if (next === CHAR_LEFT_CURLY_BRACE$1) {
15232 braceEscaped = true;
15233 }
15234 continue;
15235 }
15236 if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
15237 braces++;
15238 while (!eos() && (next = advance())) {
15239 if (next === CHAR_BACKWARD_SLASH) {
15240 backslashes = true;
15241 next = advance();
15242 continue;
15243 }
15244 if (next === CHAR_LEFT_CURLY_BRACE$1) {
15245 braces++;
15246 continue;
15247 }
15248 if (!braceEscaped && next === CHAR_DOT$1 && (next = advance()) === CHAR_DOT$1) {
15249 isGlob = true;
15250 break;
15251 }
15252 if (!braceEscaped && next === CHAR_COMMA$1) {
15253 isGlob = true;
15254 break;
15255 }
15256 if (next === CHAR_RIGHT_CURLY_BRACE$1) {
15257 braces--;
15258 if (braces === 0) {
15259 braceEscaped = false;
15260 break;
15261 }
15262 }
15263 }
15264 }
15265 if (code === CHAR_FORWARD_SLASH) {
15266 if (prev === CHAR_DOT$1 && index === (start + 1)) {
15267 start += 2;
15268 continue;
15269 }
15270 lastIndex = index + 1;
15271 continue;
15272 }
15273 if (code === CHAR_ASTERISK) {
15274 isGlob = true;
15275 break;
15276 }
15277 if (code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK) {
15278 isGlob = true;
15279 break;
15280 }
15281 if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
15282 while (!eos() && (next = advance())) {
15283 if (next === CHAR_BACKWARD_SLASH) {
15284 backslashes = true;
15285 next = advance();
15286 continue;
15287 }
15288 if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
15289 isGlob = true;
15290 break;
15291 }
15292 }
15293 }
15294 let isExtglobChar = code === CHAR_PLUS
15295 || code === CHAR_AT
15296 || code === CHAR_EXCLAMATION_MARK;
15297 if (isExtglobChar && input.charCodeAt(index + 1) === CHAR_LEFT_PARENTHESES$1) {
15298 isGlob = true;
15299 break;
15300 }
15301 if (code === CHAR_EXCLAMATION_MARK && index === start) {
15302 negated = true;
15303 start++;
15304 continue;
15305 }
15306 if (code === CHAR_LEFT_PARENTHESES$1) {
15307 while (!eos() && (next = advance())) {
15308 if (next === CHAR_BACKWARD_SLASH) {
15309 backslashes = true;
15310 next = advance();
15311 continue;
15312 }
15313 if (next === CHAR_RIGHT_PARENTHESES$1) {
15314 isGlob = true;
15315 break;
15316 }
15317 }
15318 }
15319 if (isGlob) {
15320 break;
15321 }
15322 }
15323 let prefix = '';
15324 let orig = input;
15325 let base = input;
15326 let glob = '';
15327 if (start > 0) {
15328 prefix = input.slice(0, start);
15329 input = input.slice(start);
15330 lastIndex -= start;
15331 }
15332 if (base && isGlob === true && lastIndex > 0) {
15333 base = input.slice(0, lastIndex);
15334 glob = input.slice(lastIndex);
15335 }
15336 else if (isGlob === true) {
15337 base = '';
15338 glob = input;
15339 }
15340 else {
15341 base = input;
15342 }
15343 if (base && base !== '' && base !== '/' && base !== input) {
15344 if (isPathSeparator(base.charCodeAt(base.length - 1))) {
15345 base = base.slice(0, -1);
15346 }
15347 }
15348 if (opts.unescape === true) {
15349 if (glob)
15350 glob = utils$2.removeBackslashes(glob);
15351 if (base && backslashes === true) {
15352 base = utils$2.removeBackslashes(base);
15353 }
15354 }
15355 return { prefix, input: orig, base, glob, negated, isGlob };
15356};
15357
15358/**
15359 * Constants
15360 */
15361const { MAX_LENGTH: MAX_LENGTH$1, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, REGEX_NON_SPECIAL_CHAR, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$1;
15362/**
15363 * Helpers
15364 */
15365const expandRange = (args, options) => {
15366 if (typeof options.expandRange === 'function') {
15367 return options.expandRange(...args, options);
15368 }
15369 args.sort();
15370 let value = `[${args.join('-')}]`;
15371 return value;
15372};
15373const negate = state => {
15374 let count = 1;
15375 while (state.peek() === '!' && (state.peek(2) !== '(' || state.peek(3) === '?')) {
15376 state.advance();
15377 state.start++;
15378 count++;
15379 }
15380 if (count % 2 === 0) {
15381 return false;
15382 }
15383 state.negated = true;
15384 state.start++;
15385 return true;
15386};
15387/**
15388 * Create the message for a syntax error
15389 */
15390const syntaxError = (type, char) => {
15391 return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
15392};
15393/**
15394 * Parse the given input string.
15395 * @param {String} input
15396 * @param {Object} options
15397 * @return {Object}
15398 */
15399const parse$1 = (input, options) => {
15400 if (typeof input !== 'string') {
15401 throw new TypeError('Expected a string');
15402 }
15403 input = REPLACEMENTS[input] || input;
15404 let opts = Object.assign({}, options);
15405 let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
15406 let len = input.length;
15407 if (len > max) {
15408 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
15409 }
15410 let bos = { type: 'bos', value: '', output: opts.prepend || '' };
15411 let tokens = [bos];
15412 let capture = opts.capture ? '' : '?:';
15413 let win32 = utils$2.isWindows(options);
15414 // create constants based on platform, for windows or posix
15415 const PLATFORM_CHARS = constants$1.globChars(win32);
15416 const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
15417 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;
15418 const globstar = (opts) => {
15419 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
15420 };
15421 let nodot = opts.dot ? '' : NO_DOT;
15422 let star = opts.bash === true ? globstar(opts) : STAR;
15423 let qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
15424 if (opts.capture) {
15425 star = `(${star})`;
15426 }
15427 // minimatch options support
15428 if (typeof opts.noext === 'boolean') {
15429 opts.noextglob = opts.noext;
15430 }
15431 let state = {
15432 index: -1,
15433 start: 0,
15434 consumed: '',
15435 output: '',
15436 backtrack: false,
15437 brackets: 0,
15438 braces: 0,
15439 parens: 0,
15440 quotes: 0,
15441 tokens
15442 };
15443 let extglobs = [];
15444 let stack = [];
15445 let prev = bos;
15446 let value;
15447 /**
15448 * Tokenizing helpers
15449 */
15450 const eos = () => state.index === len - 1;
15451 const peek = state.peek = (n = 1) => input[state.index + n];
15452 const advance = state.advance = () => input[++state.index];
15453 const append = token => {
15454 state.output += token.output != null ? token.output : token.value;
15455 state.consumed += token.value || '';
15456 };
15457 const increment = type => {
15458 state[type]++;
15459 stack.push(type);
15460 };
15461 const decrement = type => {
15462 state[type]--;
15463 stack.pop();
15464 };
15465 /**
15466 * Push tokens onto the tokens array. This helper speeds up
15467 * tokenizing by 1) helping us avoid backtracking as much as possible,
15468 * and 2) helping us avoid creating extra tokens when consecutive
15469 * characters are plain text. This improves performance and simplifies
15470 * lookbehinds.
15471 */
15472 const push = tok => {
15473 if (prev.type === 'globstar') {
15474 let isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
15475 let isExtglob = extglobs.length && (tok.type === 'pipe' || tok.type === 'paren');
15476 if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
15477 state.output = state.output.slice(0, -prev.output.length);
15478 prev.type = 'star';
15479 prev.value = '*';
15480 prev.output = star;
15481 state.output += prev.output;
15482 }
15483 }
15484 if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
15485 extglobs[extglobs.length - 1].inner += tok.value;
15486 }
15487 if (tok.value || tok.output)
15488 append(tok);
15489 if (prev && prev.type === 'text' && tok.type === 'text') {
15490 prev.value += tok.value;
15491 return;
15492 }
15493 tok.prev = prev;
15494 tokens.push(tok);
15495 prev = tok;
15496 };
15497 const extglobOpen = (type, value) => {
15498 let token = Object.assign(Object.assign({}, EXTGLOB_CHARS[value]), { conditions: 1, inner: '' });
15499 token.prev = prev;
15500 token.parens = state.parens;
15501 token.output = state.output;
15502 let output = (opts.capture ? '(' : '') + token.open;
15503 push({ type, value, output: state.output ? '' : ONE_CHAR });
15504 push({ type: 'paren', extglob: true, value: advance(), output });
15505 increment('parens');
15506 extglobs.push(token);
15507 };
15508 const extglobClose = token => {
15509 let output = token.close + (opts.capture ? ')' : '');
15510 if (token.type === 'negate') {
15511 let extglobStar = star;
15512 if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
15513 extglobStar = globstar(opts);
15514 }
15515 if (extglobStar !== star || eos() || /^\)+$/.test(input.slice(state.index + 1))) {
15516 output = token.close = ')$))' + extglobStar;
15517 }
15518 if (token.prev.type === 'bos' && eos()) {
15519 state.negatedExtglob = true;
15520 }
15521 }
15522 push({ type: 'paren', extglob: true, value, output });
15523 decrement('parens');
15524 };
15525 if (opts.fastpaths !== false && !/(^[*!]|[/{[()\]}"])/.test(input)) {
15526 let backslashes = false;
15527 let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
15528 if (first === '\\') {
15529 backslashes = true;
15530 return m;
15531 }
15532 if (first === '?') {
15533 if (esc) {
15534 return esc + first + (rest ? QMARK.repeat(rest.length) : '');
15535 }
15536 if (index === 0) {
15537 return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
15538 }
15539 return QMARK.repeat(chars.length);
15540 }
15541 if (first === '.') {
15542 return DOT_LITERAL.repeat(chars.length);
15543 }
15544 if (first === '*') {
15545 if (esc) {
15546 return esc + first + (rest ? star : '');
15547 }
15548 return star;
15549 }
15550 return esc ? m : '\\' + m;
15551 });
15552 if (backslashes === true) {
15553 if (opts.unescape === true) {
15554 output = output.replace(/\\/g, '');
15555 }
15556 else {
15557 output = output.replace(/\\+/g, m => {
15558 return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
15559 });
15560 }
15561 }
15562 state.output = output;
15563 return state;
15564 }
15565 /**
15566 * Tokenize input until we reach end-of-string
15567 */
15568 while (!eos()) {
15569 value = advance();
15570 if (value === '\u0000') {
15571 continue;
15572 }
15573 /**
15574 * Escaped characters
15575 */
15576 if (value === '\\') {
15577 let next = peek();
15578 if (next === '/' && opts.bash !== true) {
15579 continue;
15580 }
15581 if (next === '.' || next === ';') {
15582 continue;
15583 }
15584 if (!next) {
15585 value += '\\';
15586 push({ type: 'text', value });
15587 continue;
15588 }
15589 // collapse slashes to reduce potential for exploits
15590 let match = /^\\+/.exec(input.slice(state.index + 1));
15591 let slashes = 0;
15592 if (match && match[0].length > 2) {
15593 slashes = match[0].length;
15594 state.index += slashes;
15595 if (slashes % 2 !== 0) {
15596 value += '\\';
15597 }
15598 }
15599 if (opts.unescape === true) {
15600 value = advance() || '';
15601 }
15602 else {
15603 value += advance() || '';
15604 }
15605 if (state.brackets === 0) {
15606 push({ type: 'text', value });
15607 continue;
15608 }
15609 }
15610 /**
15611 * If we're inside a regex character class, continue
15612 * until we reach the closing bracket.
15613 */
15614 if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
15615 if (opts.posix !== false && value === ':') {
15616 let inner = prev.value.slice(1);
15617 if (inner.includes('[')) {
15618 prev.posix = true;
15619 if (inner.includes(':')) {
15620 let idx = prev.value.lastIndexOf('[');
15621 let pre = prev.value.slice(0, idx);
15622 let rest = prev.value.slice(idx + 2);
15623 let posix = POSIX_REGEX_SOURCE$1[rest];
15624 if (posix) {
15625 prev.value = pre + posix;
15626 state.backtrack = true;
15627 advance();
15628 if (!bos.output && tokens.indexOf(prev) === 1) {
15629 bos.output = ONE_CHAR;
15630 }
15631 continue;
15632 }
15633 }
15634 }
15635 }
15636 if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
15637 value = '\\' + value;
15638 }
15639 if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
15640 value = '\\' + value;
15641 }
15642 if (opts.posix === true && value === '!' && prev.value === '[') {
15643 value = '^';
15644 }
15645 prev.value += value;
15646 append({ value });
15647 continue;
15648 }
15649 /**
15650 * If we're inside a quoted string, continue
15651 * until we reach the closing double quote.
15652 */
15653 if (state.quotes === 1 && value !== '"') {
15654 value = utils$2.escapeRegex(value);
15655 prev.value += value;
15656 append({ value });
15657 continue;
15658 }
15659 /**
15660 * Double quotes
15661 */
15662 if (value === '"') {
15663 state.quotes = state.quotes === 1 ? 0 : 1;
15664 if (opts.keepQuotes === true) {
15665 push({ type: 'text', value });
15666 }
15667 continue;
15668 }
15669 /**
15670 * Parentheses
15671 */
15672 if (value === '(') {
15673 push({ type: 'paren', value });
15674 increment('parens');
15675 continue;
15676 }
15677 if (value === ')') {
15678 if (state.parens === 0 && opts.strictBrackets === true) {
15679 throw new SyntaxError(syntaxError('opening', '('));
15680 }
15681 let extglob = extglobs[extglobs.length - 1];
15682 if (extglob && state.parens === extglob.parens + 1) {
15683 extglobClose(extglobs.pop());
15684 continue;
15685 }
15686 push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
15687 decrement('parens');
15688 continue;
15689 }
15690 /**
15691 * Brackets
15692 */
15693 if (value === '[') {
15694 if (opts.nobracket === true || !input.slice(state.index + 1).includes(']')) {
15695 if (opts.nobracket !== true && opts.strictBrackets === true) {
15696 throw new SyntaxError(syntaxError('closing', ']'));
15697 }
15698 value = '\\' + value;
15699 }
15700 else {
15701 increment('brackets');
15702 }
15703 push({ type: 'bracket', value });
15704 continue;
15705 }
15706 if (value === ']') {
15707 if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
15708 push({ type: 'text', value, output: '\\' + value });
15709 continue;
15710 }
15711 if (state.brackets === 0) {
15712 if (opts.strictBrackets === true) {
15713 throw new SyntaxError(syntaxError('opening', '['));
15714 }
15715 push({ type: 'text', value, output: '\\' + value });
15716 continue;
15717 }
15718 decrement('brackets');
15719 let prevValue = prev.value.slice(1);
15720 if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
15721 value = '/' + value;
15722 }
15723 prev.value += value;
15724 append({ value });
15725 // when literal brackets are explicitly disabled
15726 // assume we should match with a regex character class
15727 if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) {
15728 continue;
15729 }
15730 let escaped = utils$2.escapeRegex(prev.value);
15731 state.output = state.output.slice(0, -prev.value.length);
15732 // when literal brackets are explicitly enabled
15733 // assume we should escape the brackets to match literal characters
15734 if (opts.literalBrackets === true) {
15735 state.output += escaped;
15736 prev.value = escaped;
15737 continue;
15738 }
15739 // when the user specifies nothing, try to match both
15740 prev.value = `(${capture}${escaped}|${prev.value})`;
15741 state.output += prev.value;
15742 continue;
15743 }
15744 /**
15745 * Braces
15746 */
15747 if (value === '{' && opts.nobrace !== true) {
15748 push({ type: 'brace', value, output: '(' });
15749 increment('braces');
15750 continue;
15751 }
15752 if (value === '}') {
15753 if (opts.nobrace === true || state.braces === 0) {
15754 push({ type: 'text', value, output: '\\' + value });
15755 continue;
15756 }
15757 let output = ')';
15758 if (state.dots === true) {
15759 let arr = tokens.slice();
15760 let range = [];
15761 for (let i = arr.length - 1; i >= 0; i--) {
15762 tokens.pop();
15763 if (arr[i].type === 'brace') {
15764 break;
15765 }
15766 if (arr[i].type !== 'dots') {
15767 range.unshift(arr[i].value);
15768 }
15769 }
15770 output = expandRange(range, opts);
15771 state.backtrack = true;
15772 }
15773 push({ type: 'brace', value, output });
15774 decrement('braces');
15775 continue;
15776 }
15777 /**
15778 * Pipes
15779 */
15780 if (value === '|') {
15781 if (extglobs.length > 0) {
15782 extglobs[extglobs.length - 1].conditions++;
15783 }
15784 push({ type: 'text', value });
15785 continue;
15786 }
15787 /**
15788 * Commas
15789 */
15790 if (value === ',') {
15791 let output = value;
15792 if (state.braces > 0 && stack[stack.length - 1] === 'braces') {
15793 output = '|';
15794 }
15795 push({ type: 'comma', value, output });
15796 continue;
15797 }
15798 /**
15799 * Slashes
15800 */
15801 if (value === '/') {
15802 // if the beginning of the glob is "./", advance the start
15803 // to the current index, and don't add the "./" characters
15804 // to the state. This greatly simplifies lookbehinds when
15805 // checking for BOS characters like "!" and "." (not "./")
15806 if (prev.type === 'dot' && state.index === 1) {
15807 state.start = state.index + 1;
15808 state.consumed = '';
15809 state.output = '';
15810 tokens.pop();
15811 prev = bos; // reset "prev" to the first token
15812 continue;
15813 }
15814 push({ type: 'slash', value, output: SLASH_LITERAL });
15815 continue;
15816 }
15817 /**
15818 * Dots
15819 */
15820 if (value === '.') {
15821 if (state.braces > 0 && prev.type === 'dot') {
15822 if (prev.value === '.')
15823 prev.output = DOT_LITERAL;
15824 prev.type = 'dots';
15825 prev.output += value;
15826 prev.value += value;
15827 state.dots = true;
15828 continue;
15829 }
15830 push({ type: 'dot', value, output: DOT_LITERAL });
15831 continue;
15832 }
15833 /**
15834 * Question marks
15835 */
15836 if (value === '?') {
15837 if (prev && prev.type === 'paren') {
15838 let next = peek();
15839 let output = value;
15840 if (next === '<' && !utils$2.supportsLookbehinds()) {
15841 throw new Error('Node.js v10 or higher is required for regex lookbehinds');
15842 }
15843 if (prev.value === '(' && !/[!=<:]/.test(next) || (next === '<' && !/[!=]/.test(peek(2)))) {
15844 output = '\\' + value;
15845 }
15846 push({ type: 'text', value, output });
15847 continue;
15848 }
15849 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
15850 extglobOpen('qmark', value);
15851 continue;
15852 }
15853 if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
15854 push({ type: 'qmark', value, output: QMARK_NO_DOT });
15855 continue;
15856 }
15857 push({ type: 'qmark', value, output: QMARK });
15858 continue;
15859 }
15860 /**
15861 * Exclamation
15862 */
15863 if (value === '!') {
15864 if (opts.noextglob !== true && peek() === '(') {
15865 if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
15866 extglobOpen('negate', value);
15867 continue;
15868 }
15869 }
15870 if (opts.nonegate !== true && state.index === 0) {
15871 negate(state);
15872 continue;
15873 }
15874 }
15875 /**
15876 * Plus
15877 */
15878 if (value === '+') {
15879 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
15880 extglobOpen('plus', value);
15881 continue;
15882 }
15883 if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) {
15884 let output = prev.extglob === true ? '\\' + value : value;
15885 push({ type: 'plus', value, output });
15886 continue;
15887 }
15888 // use regex behavior inside parens
15889 if (state.parens > 0 && opts.regex !== false) {
15890 push({ type: 'plus', value });
15891 continue;
15892 }
15893 push({ type: 'plus', value: PLUS_LITERAL });
15894 continue;
15895 }
15896 /**
15897 * Plain text
15898 */
15899 if (value === '@') {
15900 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
15901 push({ type: 'at', value, output: '' });
15902 continue;
15903 }
15904 push({ type: 'text', value });
15905 continue;
15906 }
15907 /**
15908 * Plain text
15909 */
15910 if (value !== '*') {
15911 if (value === '$' || value === '^') {
15912 value = '\\' + value;
15913 }
15914 let match = REGEX_NON_SPECIAL_CHAR.exec(input.slice(state.index + 1));
15915 if (match) {
15916 value += match[0];
15917 state.index += match[0].length;
15918 }
15919 push({ type: 'text', value });
15920 continue;
15921 }
15922 /**
15923 * Stars
15924 */
15925 if (prev && (prev.type === 'globstar' || prev.star === true)) {
15926 prev.type = 'star';
15927 prev.star = true;
15928 prev.value += value;
15929 prev.output = star;
15930 state.backtrack = true;
15931 state.consumed += value;
15932 continue;
15933 }
15934 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
15935 extglobOpen('star', value);
15936 continue;
15937 }
15938 if (prev.type === 'star') {
15939 if (opts.noglobstar === true) {
15940 state.consumed += value;
15941 continue;
15942 }
15943 let prior = prev.prev;
15944 let before = prior.prev;
15945 let isStart = prior.type === 'slash' || prior.type === 'bos';
15946 let afterStar = before && (before.type === 'star' || before.type === 'globstar');
15947 if (opts.bash === true && (!isStart || (!eos() && peek() !== '/'))) {
15948 push({ type: 'star', value, output: '' });
15949 continue;
15950 }
15951 let isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
15952 let isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
15953 if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
15954 push({ type: 'star', value, output: '' });
15955 continue;
15956 }
15957 // strip consecutive `/**/`
15958 while (input.slice(state.index + 1, state.index + 4) === '/**') {
15959 let after = input[state.index + 4];
15960 if (after && after !== '/') {
15961 break;
15962 }
15963 state.consumed += '/**';
15964 state.index += 3;
15965 }
15966 if (prior.type === 'bos' && eos()) {
15967 prev.type = 'globstar';
15968 prev.value += value;
15969 prev.output = globstar(opts);
15970 state.output = prev.output;
15971 state.consumed += value;
15972 continue;
15973 }
15974 if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
15975 state.output = state.output.slice(0, -(prior.output + prev.output).length);
15976 prior.output = '(?:' + prior.output;
15977 prev.type = 'globstar';
15978 prev.output = globstar(opts) + '|$)';
15979 prev.value += value;
15980 state.output += prior.output + prev.output;
15981 state.consumed += value;
15982 continue;
15983 }
15984 let next = peek();
15985 if (prior.type === 'slash' && prior.prev.type !== 'bos' && next === '/') {
15986 let end = peek(2) !== void 0 ? '|$' : '';
15987 state.output = state.output.slice(0, -(prior.output + prev.output).length);
15988 prior.output = '(?:' + prior.output;
15989 prev.type = 'globstar';
15990 prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
15991 prev.value += value;
15992 state.output += prior.output + prev.output;
15993 state.consumed += value + advance();
15994 push({ type: 'slash', value, output: '' });
15995 continue;
15996 }
15997 if (prior.type === 'bos' && next === '/') {
15998 prev.type = 'globstar';
15999 prev.value += value;
16000 prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
16001 state.output = prev.output;
16002 state.consumed += value + advance();
16003 push({ type: 'slash', value, output: '' });
16004 continue;
16005 }
16006 // remove single star from output
16007 state.output = state.output.slice(0, -prev.output.length);
16008 // reset previous token to globstar
16009 prev.type = 'globstar';
16010 prev.output = globstar(opts);
16011 prev.value += value;
16012 // reset output with globstar
16013 state.output += prev.output;
16014 state.consumed += value;
16015 continue;
16016 }
16017 let token = { type: 'star', value, output: star };
16018 if (opts.bash === true) {
16019 token.output = '.*?';
16020 if (prev.type === 'bos' || prev.type === 'slash') {
16021 token.output = nodot + token.output;
16022 }
16023 push(token);
16024 continue;
16025 }
16026 if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
16027 token.output = value;
16028 push(token);
16029 continue;
16030 }
16031 if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
16032 if (prev.type === 'dot') {
16033 state.output += NO_DOT_SLASH;
16034 prev.output += NO_DOT_SLASH;
16035 }
16036 else if (opts.dot === true) {
16037 state.output += NO_DOTS_SLASH;
16038 prev.output += NO_DOTS_SLASH;
16039 }
16040 else {
16041 state.output += nodot;
16042 prev.output += nodot;
16043 }
16044 if (peek() !== '*') {
16045 state.output += ONE_CHAR;
16046 prev.output += ONE_CHAR;
16047 }
16048 }
16049 push(token);
16050 }
16051 while (state.brackets > 0) {
16052 if (opts.strictBrackets === true)
16053 throw new SyntaxError(syntaxError('closing', ']'));
16054 state.output = utils$2.escapeLast(state.output, '[');
16055 decrement('brackets');
16056 }
16057 while (state.parens > 0) {
16058 if (opts.strictBrackets === true)
16059 throw new SyntaxError(syntaxError('closing', ')'));
16060 state.output = utils$2.escapeLast(state.output, '(');
16061 decrement('parens');
16062 }
16063 while (state.braces > 0) {
16064 if (opts.strictBrackets === true)
16065 throw new SyntaxError(syntaxError('closing', '}'));
16066 state.output = utils$2.escapeLast(state.output, '{');
16067 decrement('braces');
16068 }
16069 if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
16070 push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
16071 }
16072 // rebuild the output if we had to backtrack at any point
16073 if (state.backtrack === true) {
16074 state.output = '';
16075 for (let token of state.tokens) {
16076 state.output += token.output != null ? token.output : token.value;
16077 if (token.suffix) {
16078 state.output += token.suffix;
16079 }
16080 }
16081 }
16082 return state;
16083};
16084/**
16085 * Fast paths for creating regular expressions for common glob patterns.
16086 * This can significantly speed up processing and has very little downside
16087 * impact when none of the fast paths match.
16088 */
16089parse$1.fastpaths = (input, options) => {
16090 let opts = Object.assign({}, options);
16091 let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
16092 let len = input.length;
16093 if (len > max) {
16094 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
16095 }
16096 input = REPLACEMENTS[input] || input;
16097 let win32 = utils$2.isWindows(options);
16098 // create constants based on platform, for windows or posix
16099 const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants$1.globChars(win32);
16100 let capture = opts.capture ? '' : '?:';
16101 let star = opts.bash === true ? '.*?' : STAR;
16102 let nodot = opts.dot ? NO_DOTS : NO_DOT;
16103 let slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
16104 if (opts.capture) {
16105 star = `(${star})`;
16106 }
16107 const globstar = (opts) => {
16108 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
16109 };
16110 const create = str => {
16111 switch (str) {
16112 case '*':
16113 return `${nodot}${ONE_CHAR}${star}`;
16114 case '.*':
16115 return `${DOT_LITERAL}${ONE_CHAR}${star}`;
16116 case '*.*':
16117 return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
16118 case '*/*':
16119 return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
16120 case '**':
16121 return nodot + globstar(opts);
16122 case '**/*':
16123 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
16124 case '**/*.*':
16125 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
16126 case '**/.*':
16127 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
16128 default: {
16129 let match = /^(.*?)\.(\w+)$/.exec(str);
16130 if (!match)
16131 return;
16132 let source = create(match[1]);
16133 if (!source)
16134 return;
16135 return source + DOT_LITERAL + match[2];
16136 }
16137 }
16138 };
16139 let output = create(input);
16140 if (output && opts.strictSlashes !== true) {
16141 output += `${SLASH_LITERAL}?`;
16142 }
16143 return output;
16144};
16145var parse_1$1 = parse$1;
16146
16147/**
16148 * Creates a matcher function from one or more glob patterns. The
16149 * returned function takes a string to match as its first argument,
16150 * and returns true if the string is a match. The returned matcher
16151 * function also takes a boolean as the second argument that, when true,
16152 * returns an object with additional information.
16153 *
16154 * ```js
16155 * const picomatch = require('picomatch');
16156 * // picomatch(glob[, options]);
16157 *
16158 * const isMatch = picomatch('*.!(*a)');
16159 * console.log(isMatch('a.a')); //=> false
16160 * console.log(isMatch('a.b')); //=> true
16161 * ```
16162 * @name picomatch
16163 * @param {String|Array} `globs` One or more glob patterns.
16164 * @param {Object=} `options`
16165 * @return {Function=} Returns a matcher function.
16166 * @api public
16167 */
16168const picomatch = (glob, options, returnState = false) => {
16169 if (Array.isArray(glob)) {
16170 let fns = glob.map(input => picomatch(input, options, returnState));
16171 return str => {
16172 for (let isMatch of fns) {
16173 let state = isMatch(str);
16174 if (state)
16175 return state;
16176 }
16177 return false;
16178 };
16179 }
16180 if (typeof glob !== 'string' || glob === '') {
16181 throw new TypeError('Expected pattern to be a non-empty string');
16182 }
16183 let opts = options || {};
16184 let posix = utils$2.isWindows(options);
16185 let regex = picomatch.makeRe(glob, options, false, true);
16186 let state = regex.state;
16187 delete regex.state;
16188 let isIgnored = () => false;
16189 if (opts.ignore) {
16190 let ignoreOpts = Object.assign(Object.assign({}, options), { ignore: null, onMatch: null, onResult: null });
16191 isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
16192 }
16193 const matcher = (input, returnObject = false) => {
16194 let { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
16195 let result = { glob, state, regex, posix, input, output, match, isMatch };
16196 if (typeof opts.onResult === 'function') {
16197 opts.onResult(result);
16198 }
16199 if (isMatch === false) {
16200 result.isMatch = false;
16201 return returnObject ? result : false;
16202 }
16203 if (isIgnored(input)) {
16204 if (typeof opts.onIgnore === 'function') {
16205 opts.onIgnore(result);
16206 }
16207 result.isMatch = false;
16208 return returnObject ? result : false;
16209 }
16210 if (typeof opts.onMatch === 'function') {
16211 opts.onMatch(result);
16212 }
16213 return returnObject ? result : true;
16214 };
16215 if (returnState) {
16216 matcher.state = state;
16217 }
16218 return matcher;
16219};
16220/**
16221 * Test `input` with the given `regex`. This is used by the main
16222 * `picomatch()` function to test the input string.
16223 *
16224 * ```js
16225 * const picomatch = require('picomatch');
16226 * // picomatch.test(input, regex[, options]);
16227 *
16228 * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
16229 * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
16230 * ```
16231 * @param {String} `input` String to test.
16232 * @param {RegExp} `regex`
16233 * @return {Object} Returns an object with matching info.
16234 * @api public
16235 */
16236picomatch.test = (input, regex, options, { glob, posix } = {}) => {
16237 if (typeof input !== 'string') {
16238 throw new TypeError('Expected input to be a string');
16239 }
16240 if (input === '') {
16241 return { isMatch: false, output: '' };
16242 }
16243 let opts = options || {};
16244 let format = opts.format || (posix ? utils$2.toPosixSlashes : null);
16245 let match = input === glob;
16246 let output = (match && format) ? format(input) : input;
16247 if (match === false) {
16248 output = format ? format(input) : input;
16249 match = output === glob;
16250 }
16251 if (match === false || opts.capture === true) {
16252 if (opts.matchBase === true || opts.basename === true) {
16253 match = picomatch.matchBase(input, regex, options, posix);
16254 }
16255 else {
16256 match = regex.exec(output);
16257 }
16258 }
16259 return { isMatch: !!match, match, output };
16260};
16261/**
16262 * Match the basename of a filepath.
16263 *
16264 * ```js
16265 * const picomatch = require('picomatch');
16266 * // picomatch.matchBase(input, glob[, options]);
16267 * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
16268 * ```
16269 * @param {String} `input` String to test.
16270 * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
16271 * @return {Boolean}
16272 * @api public
16273 */
16274picomatch.matchBase = (input, glob, options, posix = utils$2.isWindows(options)) => {
16275 let regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
16276 return regex.test(path.basename(input));
16277};
16278/**
16279 * Returns true if **any** of the given glob `patterns` match the specified `string`.
16280 *
16281 * ```js
16282 * const picomatch = require('picomatch');
16283 * // picomatch.isMatch(string, patterns[, options]);
16284 *
16285 * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
16286 * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
16287 * ```
16288 * @param {String|Array} str The string to test.
16289 * @param {String|Array} patterns One or more glob patterns to use for matching.
16290 * @param {Object} [options] See available [options](#options).
16291 * @return {Boolean} Returns true if any patterns match `str`
16292 * @api public
16293 */
16294picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
16295/**
16296 * Parse a glob pattern to create the source string for a regular
16297 * expression.
16298 *
16299 * ```js
16300 * const picomatch = require('picomatch');
16301 * const result = picomatch.parse(glob[, options]);
16302 * ```
16303 * @param {String} `glob`
16304 * @param {Object} `options`
16305 * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
16306 * @api public
16307 */
16308picomatch.parse = (glob, options) => parse_1$1(glob, options);
16309/**
16310 * Scan a glob pattern to separate the pattern into segments.
16311 *
16312 * ```js
16313 * const picomatch = require('picomatch');
16314 * // picomatch.scan(input[, options]);
16315 *
16316 * const result = picomatch.scan('!./foo/*.js');
16317 * console.log(result);
16318 * // { prefix: '!./',
16319 * // input: '!./foo/*.js',
16320 * // base: 'foo',
16321 * // glob: '*.js',
16322 * // negated: true,
16323 * // isGlob: true }
16324 * ```
16325 * @param {String} `input` Glob pattern to scan.
16326 * @param {Object} `options`
16327 * @return {Object} Returns an object with
16328 * @api public
16329 */
16330picomatch.scan = (input, options) => scan(input, options);
16331/**
16332 * Create a regular expression from a glob pattern.
16333 *
16334 * ```js
16335 * const picomatch = require('picomatch');
16336 * // picomatch.makeRe(input[, options]);
16337 *
16338 * console.log(picomatch.makeRe('*.js'));
16339 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
16340 * ```
16341 * @param {String} `input` A glob pattern to convert to regex.
16342 * @param {Object} `options`
16343 * @return {RegExp} Returns a regex created from the given pattern.
16344 * @api public
16345 */
16346picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
16347 if (!input || typeof input !== 'string') {
16348 throw new TypeError('Expected a non-empty string');
16349 }
16350 let opts = options || {};
16351 let prepend = opts.contains ? '' : '^';
16352 let append = opts.contains ? '' : '$';
16353 let state = { negated: false, fastpaths: true };
16354 let prefix = '';
16355 let output;
16356 if (input.startsWith('./')) {
16357 input = input.slice(2);
16358 prefix = state.prefix = './';
16359 }
16360 if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
16361 output = parse_1$1.fastpaths(input, options);
16362 }
16363 if (output === void 0) {
16364 state = picomatch.parse(input, options);
16365 state.prefix = prefix + (state.prefix || '');
16366 output = state.output;
16367 }
16368 if (returnOutput === true) {
16369 return output;
16370 }
16371 let source = `${prepend}(?:${output})${append}`;
16372 if (state && state.negated === true) {
16373 source = `^(?!${source}).*$`;
16374 }
16375 let regex = picomatch.toRegex(source, options);
16376 if (returnState === true) {
16377 regex.state = state;
16378 }
16379 return regex;
16380};
16381/**
16382 * Create a regular expression from the given regex source string.
16383 *
16384 * ```js
16385 * const picomatch = require('picomatch');
16386 * // picomatch.toRegex(source[, options]);
16387 *
16388 * const { output } = picomatch.parse('*.js');
16389 * console.log(picomatch.toRegex(output));
16390 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
16391 * ```
16392 * @param {String} `source` Regular expression source string.
16393 * @param {Object} `options`
16394 * @return {RegExp}
16395 * @api public
16396 */
16397picomatch.toRegex = (source, options) => {
16398 try {
16399 let opts = options || {};
16400 return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
16401 }
16402 catch (err) {
16403 if (options && options.debug === true)
16404 throw err;
16405 return /$^/;
16406 }
16407};
16408/**
16409 * Picomatch constants.
16410 * @return {Object}
16411 */
16412picomatch.constants = constants$1;
16413/**
16414 * Expose "picomatch"
16415 */
16416var picomatch_1 = picomatch;
16417
16418var picomatch$1 = picomatch_1;
16419
16420const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');
16421/**
16422 * Returns an array of strings that match one or more glob patterns.
16423 *
16424 * ```js
16425 * const mm = require('micromatch');
16426 * // mm(list, patterns[, options]);
16427 *
16428 * console.log(mm(['a.js', 'a.txt'], ['*.js']));
16429 * //=> [ 'a.js' ]
16430 * ```
16431 * @param {String|Array<string>} list List of strings to match.
16432 * @param {String|Array<string>} patterns One or more glob patterns to use for matching.
16433 * @param {Object} options See available [options](#options)
16434 * @return {Array} Returns an array of matches
16435 * @summary false
16436 * @api public
16437 */
16438const micromatch = (list, patterns, options) => {
16439 patterns = [].concat(patterns);
16440 list = [].concat(list);
16441 let omit = new Set();
16442 let keep = new Set();
16443 let items = new Set();
16444 let negatives = 0;
16445 let onResult = state => {
16446 items.add(state.output);
16447 if (options && options.onResult) {
16448 options.onResult(state);
16449 }
16450 };
16451 for (let i = 0; i < patterns.length; i++) {
16452 let isMatch = picomatch$1(String(patterns[i]), Object.assign(Object.assign({}, options), { onResult }), true);
16453 let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
16454 if (negated)
16455 negatives++;
16456 for (let item of list) {
16457 let matched = isMatch(item, true);
16458 let match = negated ? !matched.isMatch : matched.isMatch;
16459 if (!match)
16460 continue;
16461 if (negated) {
16462 omit.add(matched.output);
16463 }
16464 else {
16465 omit.delete(matched.output);
16466 keep.add(matched.output);
16467 }
16468 }
16469 }
16470 let result = negatives === patterns.length ? [...items] : [...keep];
16471 let matches = result.filter(item => !omit.has(item));
16472 if (options && matches.length === 0) {
16473 if (options.failglob === true) {
16474 throw new Error(`No matches found for "${patterns.join(', ')}"`);
16475 }
16476 if (options.nonull === true || options.nullglob === true) {
16477 return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
16478 }
16479 }
16480 return matches;
16481};
16482/**
16483 * Backwards compatibility
16484 */
16485micromatch.match = micromatch;
16486/**
16487 * Returns a matcher function from the given glob `pattern` and `options`.
16488 * The returned function takes a string to match as its only argument and returns
16489 * true if the string is a match.
16490 *
16491 * ```js
16492 * const mm = require('micromatch');
16493 * // mm.matcher(pattern[, options]);
16494 *
16495 * const isMatch = mm.matcher('*.!(*a)');
16496 * console.log(isMatch('a.a')); //=> false
16497 * console.log(isMatch('a.b')); //=> true
16498 * ```
16499 * @param {String} `pattern` Glob pattern
16500 * @param {Object} `options`
16501 * @return {Function} Returns a matcher function.
16502 * @api public
16503 */
16504micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);
16505/**
16506 * Returns true if **any** of the given glob `patterns` match the specified `string`.
16507 *
16508 * ```js
16509 * const mm = require('micromatch');
16510 * // mm.isMatch(string, patterns[, options]);
16511 *
16512 * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
16513 * console.log(mm.isMatch('a.a', 'b.*')); //=> false
16514 * ```
16515 * @param {String} str The string to test.
16516 * @param {String|Array} patterns One or more glob patterns to use for matching.
16517 * @param {Object} [options] See available [options](#options).
16518 * @return {Boolean} Returns true if any patterns match `str`
16519 * @api public
16520 */
16521micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
16522/**
16523 * Backwards compatibility
16524 */
16525micromatch.any = micromatch.isMatch;
16526/**
16527 * Returns a list of strings that _**do not match any**_ of the given `patterns`.
16528 *
16529 * ```js
16530 * const mm = require('micromatch');
16531 * // mm.not(list, patterns[, options]);
16532 *
16533 * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
16534 * //=> ['b.b', 'c.c']
16535 * ```
16536 * @param {Array} `list` Array of strings to match.
16537 * @param {String|Array} `patterns` One or more glob pattern to use for matching.
16538 * @param {Object} `options` See available [options](#options) for changing how matches are performed
16539 * @return {Array} Returns an array of strings that **do not match** the given patterns.
16540 * @api public
16541 */
16542micromatch.not = (list, patterns, options = {}) => {
16543 patterns = [].concat(patterns).map(String);
16544 let result = new Set();
16545 let items = [];
16546 let onResult = state => {
16547 if (options.onResult)
16548 options.onResult(state);
16549 items.push(state.output);
16550 };
16551 let matches = micromatch(list, patterns, Object.assign(Object.assign({}, options), { onResult }));
16552 for (let item of items) {
16553 if (!matches.includes(item)) {
16554 result.add(item);
16555 }
16556 }
16557 return [...result];
16558};
16559/**
16560 * Returns true if the given `string` contains the given pattern. Similar
16561 * to [.isMatch](#isMatch) but the pattern can match any part of the string.
16562 *
16563 * ```js
16564 * var mm = require('micromatch');
16565 * // mm.contains(string, pattern[, options]);
16566 *
16567 * console.log(mm.contains('aa/bb/cc', '*b'));
16568 * //=> true
16569 * console.log(mm.contains('aa/bb/cc', '*d'));
16570 * //=> false
16571 * ```
16572 * @param {String} `str` The string to match.
16573 * @param {String|Array} `patterns` Glob pattern to use for matching.
16574 * @param {Object} `options` See available [options](#options) for changing how matches are performed
16575 * @return {Boolean} Returns true if the patter matches any part of `str`.
16576 * @api public
16577 */
16578micromatch.contains = (str, pattern, options) => {
16579 if (typeof str !== 'string') {
16580 throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
16581 }
16582 if (Array.isArray(pattern)) {
16583 return pattern.some(p => micromatch.contains(str, p, options));
16584 }
16585 if (typeof pattern === 'string') {
16586 if (isEmptyString(str) || isEmptyString(pattern)) {
16587 return false;
16588 }
16589 if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
16590 return true;
16591 }
16592 }
16593 return micromatch.isMatch(str, pattern, Object.assign(Object.assign({}, options), { contains: true }));
16594};
16595/**
16596 * Filter the keys of the given object with the given `glob` pattern
16597 * and `options`. Does not attempt to match nested keys. If you need this feature,
16598 * use [glob-object][] instead.
16599 *
16600 * ```js
16601 * const mm = require('micromatch');
16602 * // mm.matchKeys(object, patterns[, options]);
16603 *
16604 * const obj = { aa: 'a', ab: 'b', ac: 'c' };
16605 * console.log(mm.matchKeys(obj, '*b'));
16606 * //=> { ab: 'b' }
16607 * ```
16608 * @param {Object} `object` The object with keys to filter.
16609 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
16610 * @param {Object} `options` See available [options](#options) for changing how matches are performed
16611 * @return {Object} Returns an object with only keys that match the given patterns.
16612 * @api public
16613 */
16614micromatch.matchKeys = (obj, patterns, options) => {
16615 if (!utils$2.isObject(obj)) {
16616 throw new TypeError('Expected the first argument to be an object');
16617 }
16618 let keys = micromatch(Object.keys(obj), patterns, options);
16619 let res = {};
16620 for (let key of keys)
16621 res[key] = obj[key];
16622 return res;
16623};
16624/**
16625 * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
16626 *
16627 * ```js
16628 * const mm = require('micromatch');
16629 * // mm.some(list, patterns[, options]);
16630 *
16631 * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
16632 * // true
16633 * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
16634 * // false
16635 * ```
16636 * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
16637 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
16638 * @param {Object} `options` See available [options](#options) for changing how matches are performed
16639 * @return {Boolean} Returns true if any patterns match `str`
16640 * @api public
16641 */
16642micromatch.some = (list, patterns, options) => {
16643 let items = [].concat(list);
16644 for (let pattern of [].concat(patterns)) {
16645 let isMatch = picomatch$1(String(pattern), options);
16646 if (items.some(item => isMatch(item))) {
16647 return true;
16648 }
16649 }
16650 return false;
16651};
16652/**
16653 * Returns true if every string in the given `list` matches
16654 * any of the given glob `patterns`.
16655 *
16656 * ```js
16657 * const mm = require('micromatch');
16658 * // mm.every(list, patterns[, options]);
16659 *
16660 * console.log(mm.every('foo.js', ['foo.js']));
16661 * // true
16662 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
16663 * // true
16664 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
16665 * // false
16666 * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
16667 * // false
16668 * ```
16669 * @param {String|Array} `list` The string or array of strings to test.
16670 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
16671 * @param {Object} `options` See available [options](#options) for changing how matches are performed
16672 * @return {Boolean} Returns true if any patterns match `str`
16673 * @api public
16674 */
16675micromatch.every = (list, patterns, options) => {
16676 let items = [].concat(list);
16677 for (let pattern of [].concat(patterns)) {
16678 let isMatch = picomatch$1(String(pattern), options);
16679 if (!items.every(item => isMatch(item))) {
16680 return false;
16681 }
16682 }
16683 return true;
16684};
16685/**
16686 * Returns true if **all** of the given `patterns` match
16687 * the specified string.
16688 *
16689 * ```js
16690 * const mm = require('micromatch');
16691 * // mm.all(string, patterns[, options]);
16692 *
16693 * console.log(mm.all('foo.js', ['foo.js']));
16694 * // true
16695 *
16696 * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
16697 * // false
16698 *
16699 * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
16700 * // true
16701 *
16702 * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
16703 * // true
16704 * ```
16705 * @param {String|Array} `str` The string to test.
16706 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
16707 * @param {Object} `options` See available [options](#options) for changing how matches are performed
16708 * @return {Boolean} Returns true if any patterns match `str`
16709 * @api public
16710 */
16711micromatch.all = (str, patterns, options) => {
16712 if (typeof str !== 'string') {
16713 throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
16714 }
16715 return [].concat(patterns).every(p => picomatch$1(p, options)(str));
16716};
16717/**
16718 * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
16719 *
16720 * ```js
16721 * const mm = require('micromatch');
16722 * // mm.capture(pattern, string[, options]);
16723 *
16724 * console.log(mm.capture('test/*.js', 'test/foo.js'));
16725 * //=> ['foo']
16726 * console.log(mm.capture('test/*.js', 'foo/bar.css'));
16727 * //=> null
16728 * ```
16729 * @param {String} `glob` Glob pattern to use for matching.
16730 * @param {String} `input` String to match
16731 * @param {Object} `options` See available [options](#options) for changing how matches are performed
16732 * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
16733 * @api public
16734 */
16735micromatch.capture = (glob, input, options) => {
16736 let posix = utils$2.isWindows(options);
16737 let regex = picomatch$1.makeRe(String(glob), Object.assign(Object.assign({}, options), { capture: true }));
16738 let match = regex.exec(posix ? utils$2.toPosixSlashes(input) : input);
16739 if (match) {
16740 return match.slice(1).map(v => v === void 0 ? '' : v);
16741 }
16742};
16743/**
16744 * Create a regular expression from the given glob `pattern`.
16745 *
16746 * ```js
16747 * const mm = require('micromatch');
16748 * // mm.makeRe(pattern[, options]);
16749 *
16750 * console.log(mm.makeRe('*.js'));
16751 * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
16752 * ```
16753 * @param {String} `pattern` A glob pattern to convert to regex.
16754 * @param {Object} `options`
16755 * @return {RegExp} Returns a regex created from the given pattern.
16756 * @api public
16757 */
16758micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);
16759/**
16760 * Scan a glob pattern to separate the pattern into segments. Used
16761 * by the [split](#split) method.
16762 *
16763 * ```js
16764 * const mm = require('micromatch');
16765 * const state = mm.scan(pattern[, options]);
16766 * ```
16767 * @param {String} `pattern`
16768 * @param {Object} `options`
16769 * @return {Object} Returns an object with
16770 * @api public
16771 */
16772micromatch.scan = (...args) => picomatch$1.scan(...args);
16773/**
16774 * Parse a glob pattern to create the source string for a regular
16775 * expression.
16776 *
16777 * ```js
16778 * const mm = require('micromatch');
16779 * const state = mm(pattern[, options]);
16780 * ```
16781 * @param {String} `glob`
16782 * @param {Object} `options`
16783 * @return {Object} Returns an object with useful properties and output to be used as regex source string.
16784 * @api public
16785 */
16786micromatch.parse = (patterns, options) => {
16787 let res = [];
16788 for (let pattern of [].concat(patterns || [])) {
16789 for (let str of braces_1(String(pattern), options)) {
16790 res.push(picomatch$1.parse(str, options));
16791 }
16792 }
16793 return res;
16794};
16795/**
16796 * Process the given brace `pattern`.
16797 *
16798 * ```js
16799 * const { braces } = require('micromatch');
16800 * console.log(braces('foo/{a,b,c}/bar'));
16801 * //=> [ 'foo/(a|b|c)/bar' ]
16802 *
16803 * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
16804 * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
16805 * ```
16806 * @param {String} `pattern` String with brace pattern to process.
16807 * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
16808 * @return {Array}
16809 * @api public
16810 */
16811micromatch.braces = (pattern, options) => {
16812 if (typeof pattern !== 'string')
16813 throw new TypeError('Expected a string');
16814 if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
16815 return [pattern];
16816 }
16817 return braces_1(pattern, options);
16818};
16819/**
16820 * Expand braces
16821 */
16822micromatch.braceExpand = (pattern, options) => {
16823 if (typeof pattern !== 'string')
16824 throw new TypeError('Expected a string');
16825 return micromatch.braces(pattern, Object.assign(Object.assign({}, options), { expand: true }));
16826};
16827/**
16828 * Expose micromatch
16829 */
16830var micromatch_1 = micromatch;
16831
16832function ensureArray$1(thing) {
16833 if (Array.isArray(thing))
16834 return thing;
16835 if (thing == undefined)
16836 return [];
16837 return [thing];
16838}
16839
16840function getMatcherString(id, resolutionBase) {
16841 if (resolutionBase === false) {
16842 return id;
16843 }
16844 return resolve(...(typeof resolutionBase === 'string' ? [resolutionBase, id] : [id]));
16845}
16846const createFilter = function createFilter(include, exclude, options) {
16847 const resolutionBase = options && options.resolve;
16848 const getMatcher = (id) => {
16849 return id instanceof RegExp
16850 ? id
16851 : {
16852 test: micromatch_1.matcher(getMatcherString(id, resolutionBase)
16853 .split(sep)
16854 .join('/'), { dot: true })
16855 };
16856 };
16857 const includeMatchers = ensureArray$1(include).map(getMatcher);
16858 const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
16859 return function (id) {
16860 if (typeof id !== 'string')
16861 return false;
16862 if (/\0/.test(id))
16863 return false;
16864 id = id.split(sep).join('/');
16865 for (let i = 0; i < excludeMatchers.length; ++i) {
16866 const matcher = excludeMatchers[i];
16867 if (matcher.test(id))
16868 return false;
16869 }
16870 for (let i = 0; i < includeMatchers.length; ++i) {
16871 const matcher = includeMatchers[i];
16872 if (matcher.test(id))
16873 return true;
16874 }
16875 return !includeMatchers.length;
16876 };
16877};
16878
16879var modules = {};
16880var getModule = function (dir) {
16881 var rootPath = dir ? path.resolve(dir) : process.cwd();
16882 var rootName = path.join(rootPath, '@root');
16883 var root = modules[rootName];
16884 if (!root) {
16885 root = new module(rootName);
16886 root.filename = rootName;
16887 root.paths = module._nodeModulePaths(rootPath);
16888 modules[rootName] = root;
16889 }
16890 return root;
16891};
16892var requireRelative = function (requested, relativeTo) {
16893 var root = getModule(relativeTo);
16894 return root.require(requested);
16895};
16896requireRelative.resolve = function (requested, relativeTo) {
16897 var root = getModule(relativeTo);
16898 return module._resolveFilename(requested, root);
16899};
16900var requireRelative_1 = requireRelative;
16901
16902let chokidar;
16903try {
16904 chokidar = requireRelative_1('chokidar', process.cwd());
16905}
16906catch (err) {
16907 chokidar = null;
16908}
16909var chokidar$1 = chokidar;
16910
16911const opts = { encoding: 'utf-8', persistent: true };
16912const watchers = new Map();
16913function addTask(id, task, chokidarOptions, chokidarOptionsHash, isTransformDependency) {
16914 if (!watchers.has(chokidarOptionsHash))
16915 watchers.set(chokidarOptionsHash, new Map());
16916 const group = watchers.get(chokidarOptionsHash);
16917 const watcher = group.get(id) || new FileWatcher(id, chokidarOptions, group);
16918 if (!watcher.fsWatcher) {
16919 if (isTransformDependency)
16920 throw new Error(`Transform dependency ${id} does not exist.`);
16921 }
16922 else {
16923 watcher.addTask(task, isTransformDependency);
16924 }
16925}
16926function deleteTask(id, target, chokidarOptionsHash) {
16927 const group = watchers.get(chokidarOptionsHash);
16928 const watcher = group.get(id);
16929 if (watcher)
16930 watcher.deleteTask(target, group);
16931}
16932class FileWatcher {
16933 constructor(id, chokidarOptions, group) {
16934 this.id = id;
16935 this.tasks = new Set();
16936 this.transformDependencyTasks = new Set();
16937 let modifiedTime;
16938 try {
16939 const stats = statSync(id);
16940 modifiedTime = +stats.mtime;
16941 }
16942 catch (err) {
16943 if (err.code === 'ENOENT') {
16944 // can't watch files that don't exist (e.g. injected
16945 // by plugins somehow)
16946 return;
16947 }
16948 throw err;
16949 }
16950 const handleWatchEvent = (event) => {
16951 if (event === 'rename' || event === 'unlink') {
16952 this.close();
16953 group.delete(id);
16954 this.trigger(id);
16955 return;
16956 }
16957 else {
16958 let stats;
16959 try {
16960 stats = statSync(id);
16961 }
16962 catch (err) {
16963 if (err.code === 'ENOENT') {
16964 modifiedTime = -1;
16965 this.trigger(id);
16966 return;
16967 }
16968 throw err;
16969 }
16970 // debounce
16971 if (+stats.mtime - modifiedTime > 15)
16972 this.trigger(id);
16973 }
16974 };
16975 this.fsWatcher = chokidarOptions
16976 ? chokidar$1.watch(id, chokidarOptions).on('all', handleWatchEvent)
16977 : watch$1(id, opts, handleWatchEvent);
16978 group.set(id, this);
16979 }
16980 addTask(task, isTransformDependency) {
16981 if (isTransformDependency)
16982 this.transformDependencyTasks.add(task);
16983 else
16984 this.tasks.add(task);
16985 }
16986 close() {
16987 if (this.fsWatcher)
16988 this.fsWatcher.close();
16989 }
16990 deleteTask(task, group) {
16991 let deleted = this.tasks.delete(task);
16992 deleted = this.transformDependencyTasks.delete(task) || deleted;
16993 if (deleted && this.tasks.size === 0 && this.transformDependencyTasks.size === 0) {
16994 group.delete(this.id);
16995 this.close();
16996 }
16997 }
16998 trigger(id) {
16999 this.tasks.forEach(task => {
17000 task.invalidate(id, false);
17001 });
17002 this.transformDependencyTasks.forEach(task => {
17003 task.invalidate(id, true);
17004 });
17005 }
17006}
17007
17008const DELAY = 200;
17009class Watcher {
17010 constructor(configs) {
17011 this.buildTimeout = null;
17012 this.invalidatedIds = new Set();
17013 this.rerun = false;
17014 this.emitter = new (class extends EventEmitter {
17015 constructor(close) {
17016 super();
17017 this.close = close;
17018 // Allows more than 10 bundles to be watched without
17019 // showing the `MaxListenersExceededWarning` to the user.
17020 this.setMaxListeners(Infinity);
17021 }
17022 })(this.close.bind(this));
17023 this.tasks = (Array.isArray(configs) ? configs : configs ? [configs] : []).map(config => new Task(this, config));
17024 this.running = true;
17025 process.nextTick(() => this.run());
17026 }
17027 close() {
17028 if (this.buildTimeout)
17029 clearTimeout(this.buildTimeout);
17030 for (const task of this.tasks) {
17031 task.close();
17032 }
17033 this.emitter.removeAllListeners();
17034 }
17035 emit(event, value) {
17036 this.emitter.emit(event, value);
17037 }
17038 invalidate(id) {
17039 if (id) {
17040 this.invalidatedIds.add(id);
17041 }
17042 if (this.running) {
17043 this.rerun = true;
17044 return;
17045 }
17046 if (this.buildTimeout)
17047 clearTimeout(this.buildTimeout);
17048 this.buildTimeout = setTimeout(() => {
17049 this.buildTimeout = null;
17050 for (const id of this.invalidatedIds) {
17051 this.emit('change', id);
17052 }
17053 this.invalidatedIds.clear();
17054 this.emit('restart');
17055 this.run();
17056 }, DELAY);
17057 }
17058 run() {
17059 this.running = true;
17060 this.emit('event', {
17061 code: 'START'
17062 });
17063 let taskPromise = Promise.resolve();
17064 for (const task of this.tasks)
17065 taskPromise = taskPromise.then(() => task.run());
17066 return taskPromise
17067 .then(() => {
17068 this.running = false;
17069 this.emit('event', {
17070 code: 'END'
17071 });
17072 })
17073 .catch(error => {
17074 this.running = false;
17075 this.emit('event', {
17076 code: 'ERROR',
17077 error
17078 });
17079 })
17080 .then(() => {
17081 if (this.rerun) {
17082 this.rerun = false;
17083 this.invalidate();
17084 }
17085 });
17086 }
17087}
17088class Task {
17089 constructor(watcher, config) {
17090 this.cache = { modules: [] };
17091 this.watchFiles = [];
17092 this.invalidated = true;
17093 this.watcher = watcher;
17094 this.closed = false;
17095 this.watched = new Set();
17096 const { inputOptions, outputOptions } = mergeOptions({
17097 config
17098 });
17099 this.inputOptions = inputOptions;
17100 this.outputs = outputOptions;
17101 this.outputFiles = this.outputs.map(output => {
17102 if (output.file || output.dir)
17103 return path.resolve(output.file || output.dir);
17104 return undefined;
17105 });
17106 const watchOptions = inputOptions.watch || {};
17107 if ('useChokidar' in watchOptions)
17108 watchOptions.chokidar = watchOptions.useChokidar;
17109 let chokidarOptions = 'chokidar' in watchOptions ? watchOptions.chokidar : !!chokidar$1;
17110 if (chokidarOptions) {
17111 chokidarOptions = Object.assign(Object.assign({}, (chokidarOptions === true ? {} : chokidarOptions)), { disableGlobbing: true, ignoreInitial: true });
17112 }
17113 if (chokidarOptions && !chokidar$1) {
17114 throw new Error(`watch.chokidar was provided, but chokidar could not be found. Have you installed it?`);
17115 }
17116 this.chokidarOptions = chokidarOptions;
17117 this.chokidarOptionsHash = JSON.stringify(chokidarOptions);
17118 this.filter = createFilter(watchOptions.include, watchOptions.exclude);
17119 }
17120 close() {
17121 this.closed = true;
17122 for (const id of this.watched) {
17123 deleteTask(id, this, this.chokidarOptionsHash);
17124 }
17125 }
17126 invalidate(id, isTransformDependency) {
17127 this.invalidated = true;
17128 if (isTransformDependency) {
17129 for (const module of this.cache.modules) {
17130 if (module.transformDependencies.indexOf(id) === -1)
17131 continue;
17132 // effective invalidation
17133 module.originalCode = null;
17134 }
17135 }
17136 this.watcher.invalidate(id);
17137 }
17138 run() {
17139 if (!this.invalidated)
17140 return;
17141 this.invalidated = false;
17142 const options = Object.assign(Object.assign({}, this.inputOptions), { cache: this.cache });
17143 const start = Date.now();
17144 this.watcher.emit('event', {
17145 code: 'BUNDLE_START',
17146 input: this.inputOptions.input,
17147 output: this.outputFiles
17148 });
17149 setWatcher(this.watcher.emitter);
17150 return rollup(options)
17151 .then(result => {
17152 if (this.closed)
17153 return undefined;
17154 this.updateWatchedFiles(result);
17155 return Promise.all(this.outputs.map(output => result.write(output))).then(() => result);
17156 })
17157 .then((result) => {
17158 this.watcher.emit('event', {
17159 code: 'BUNDLE_END',
17160 duration: Date.now() - start,
17161 input: this.inputOptions.input,
17162 output: this.outputFiles,
17163 result
17164 });
17165 })
17166 .catch((error) => {
17167 if (this.closed)
17168 return;
17169 if (Array.isArray(error.watchFiles)) {
17170 for (const id of error.watchFiles) {
17171 this.watchFile(id);
17172 }
17173 }
17174 throw error;
17175 });
17176 }
17177 updateWatchedFiles(result) {
17178 const previouslyWatched = this.watched;
17179 this.watched = new Set();
17180 this.watchFiles = result.watchFiles;
17181 this.cache = result.cache;
17182 for (const id of this.watchFiles) {
17183 this.watchFile(id);
17184 }
17185 for (const module of this.cache.modules) {
17186 for (const depId of module.transformDependencies) {
17187 this.watchFile(depId, true);
17188 }
17189 }
17190 for (const id of previouslyWatched) {
17191 if (!this.watched.has(id))
17192 deleteTask(id, this, this.chokidarOptionsHash);
17193 }
17194 }
17195 watchFile(id, isTransformDependency = false) {
17196 if (!this.filter(id))
17197 return;
17198 this.watched.add(id);
17199 if (this.outputFiles.some(file => file === id)) {
17200 throw new Error('Cannot import the generated bundle');
17201 }
17202 // this is necessary to ensure that any 'renamed' files
17203 // continue to be watched following an error
17204 addTask(id, this, this.chokidarOptions, this.chokidarOptionsHash, isTransformDependency);
17205 }
17206}
17207function watch(configs) {
17208 return new Watcher(configs).emitter;
17209}
17210
17211export { version as VERSION, rollup, watch };