UNPKG

142 kBJavaScriptView Raw
1import { Parser } from 'acorn';
2import acornJsx from 'acorn-jsx';
3import acornDynamicImport from 'acorn-dynamic-import';
4import MagicString from 'magic-string';
5import rewritePattern from 'regexpu-core';
6
7// used for debugging, without the noise created by
8// circular references
9function toJSON(node) {
10 var obj = {};
11
12 Object.keys(node).forEach(function (key) {
13 if (
14 key === 'parent' ||
15 key === 'program' ||
16 key === 'keys' ||
17 key === '__wrapped'
18 )
19 { return; }
20
21 if (Array.isArray(node[key])) {
22 obj[key] = node[key].map(toJSON);
23 } else if (node[key] && node[key].toJSON) {
24 obj[key] = node[key].toJSON();
25 } else {
26 obj[key] = node[key];
27 }
28 });
29
30 return obj;
31}
32
33var Node = function Node () {};
34
35Node.prototype.ancestor = function ancestor (level) {
36 var node = this;
37 while (level--) {
38 node = node.parent;
39 if (!node) { return null; }
40 }
41
42 return node;
43};
44
45Node.prototype.contains = function contains (node) {
46 while (node) {
47 if (node === this) { return true; }
48 node = node.parent;
49 }
50
51 return false;
52};
53
54Node.prototype.findLexicalBoundary = function findLexicalBoundary () {
55 return this.parent.findLexicalBoundary();
56};
57
58Node.prototype.findNearest = function findNearest (type) {
59 if (typeof type === 'string') { type = new RegExp(("^" + type + "$")); }
60 if (type.test(this.type)) { return this; }
61 return this.parent.findNearest(type);
62};
63
64Node.prototype.unparenthesizedParent = function unparenthesizedParent () {
65 var node = this.parent;
66 while (node && node.type === 'ParenthesizedExpression') {
67 node = node.parent;
68 }
69 return node;
70};
71
72Node.prototype.unparenthesize = function unparenthesize () {
73 var node = this;
74 while (node.type === 'ParenthesizedExpression') {
75 node = node.expression;
76 }
77 return node;
78};
79
80Node.prototype.findScope = function findScope (functionScope) {
81 return this.parent.findScope(functionScope);
82};
83
84Node.prototype.getIndentation = function getIndentation () {
85 return this.parent.getIndentation();
86};
87
88Node.prototype.initialise = function initialise (transforms) {
89 for (var i = 0, list = this.keys; i < list.length; i += 1) {
90 var key = list[i];
91
92 var value = this[key];
93
94 if (Array.isArray(value)) {
95 value.forEach(function (node) { return node && node.initialise(transforms); });
96 } else if (value && typeof value === 'object') {
97 value.initialise(transforms);
98 }
99 }
100};
101
102Node.prototype.toJSON = function toJSON$1 () {
103 return toJSON(this);
104};
105
106Node.prototype.toString = function toString () {
107 return this.program.magicString.original.slice(this.start, this.end);
108};
109
110Node.prototype.transpile = function transpile (code, transforms) {
111 for (var i = 0, list = this.keys; i < list.length; i += 1) {
112 var key = list[i];
113
114 var value = this[key];
115
116 if (Array.isArray(value)) {
117 value.forEach(function (node) { return node && node.transpile(code, transforms); });
118 } else if (value && typeof value === 'object') {
119 value.transpile(code, transforms);
120 }
121 }
122};
123
124function extractNames(node) {
125 var names = [];
126 extractors[node.type](names, node);
127 return names;
128}
129
130var extractors = {
131 Identifier: function Identifier(names, node) {
132 names.push(node);
133 },
134
135 ObjectPattern: function ObjectPattern(names, node) {
136 for (var i = 0, list = node.properties; i < list.length; i += 1) {
137 var prop = list[i];
138
139 extractors[prop.type](names, prop);
140 }
141 },
142
143 Property: function Property(names, node) {
144 extractors[node.value.type](names, node.value);
145 },
146
147 ArrayPattern: function ArrayPattern(names, node) {
148 for (var i = 0, list = node.elements; i < list.length; i += 1) {
149 var element = list[i];
150
151 if (element) { extractors[element.type](names, element); }
152 }
153 },
154
155 RestElement: function RestElement(names, node) {
156 extractors[node.argument.type](names, node.argument);
157 },
158
159 AssignmentPattern: function AssignmentPattern(names, node) {
160 extractors[node.left.type](names, node.left);
161 }
162};
163
164var reserved = Object.create(null);
165'do if in for let new try var case else enum eval null this true void with await break catch class const false super throw while yield delete export import public return static switch typeof default extends finally package private continue debugger function arguments interface protected implements instanceof'
166 .split(' ')
167 .forEach(function (word) { return (reserved[word] = true); });
168
169function Scope(options) {
170 options = options || {};
171
172 this.parent = options.parent;
173 this.isBlockScope = !!options.block;
174 this.createDeclarationCallback = options.declare;
175
176 var scope = this;
177 while (scope.isBlockScope) { scope = scope.parent; }
178 this.functionScope = scope;
179
180 this.identifiers = [];
181 this.declarations = Object.create(null);
182 this.references = Object.create(null);
183 this.blockScopedDeclarations = this.isBlockScope ? null : Object.create(null);
184 this.aliases = Object.create(null);
185}
186
187Scope.prototype = {
188 addDeclaration: function addDeclaration(node, kind) {
189 for (var i = 0, list = extractNames(node); i < list.length; i += 1) {
190 var identifier = list[i];
191
192 var name = identifier.name;
193
194 var declaration = { name: name, node: identifier, kind: kind, instances: [] };
195 this.declarations[name] = declaration;
196
197 if (this.isBlockScope) {
198 if (!this.functionScope.blockScopedDeclarations[name])
199 { this.functionScope.blockScopedDeclarations[name] = []; }
200 this.functionScope.blockScopedDeclarations[name].push(declaration);
201 }
202 }
203 },
204
205 addReference: function addReference(identifier) {
206 if (this.consolidated) {
207 this.consolidateReference(identifier);
208 } else {
209 this.identifiers.push(identifier);
210 }
211 },
212
213 consolidate: function consolidate() {
214 for (var i = 0; i < this.identifiers.length; i += 1) {
215 // we might push to the array during consolidation, so don't cache length
216 var identifier = this.identifiers[i];
217 this.consolidateReference(identifier);
218 }
219
220 this.consolidated = true; // TODO understand why this is necessary... seems bad
221 },
222
223 consolidateReference: function consolidateReference(identifier) {
224 var declaration = this.declarations[identifier.name];
225 if (declaration) {
226 declaration.instances.push(identifier);
227 } else {
228 this.references[identifier.name] = true;
229 if (this.parent) { this.parent.addReference(identifier); }
230 }
231 },
232
233 contains: function contains(name) {
234 return (
235 this.declarations[name] ||
236 (this.parent ? this.parent.contains(name) : false)
237 );
238 },
239
240 createIdentifier: function createIdentifier(base) {
241 if (typeof base === 'number') { base = base.toString(); }
242
243 base = base
244 .replace(/\s/g, '')
245 .replace(/\[([^\]]+)\]/g, '_$1')
246 .replace(/[^a-zA-Z0-9_$]/g, '_')
247 .replace(/_{2,}/, '_');
248
249 var name = base;
250 var counter = 1;
251
252 while (
253 this.declarations[name] ||
254 this.references[name] ||
255 this.aliases[name] ||
256 name in reserved
257 ) {
258 name = base + "$" + (counter++);
259 }
260
261 this.aliases[name] = true;
262 return name;
263 },
264
265 createDeclaration: function createDeclaration(base) {
266 var id = this.createIdentifier(base);
267 this.createDeclarationCallback(id);
268 return id;
269 },
270
271 findDeclaration: function findDeclaration(name) {
272 return (
273 this.declarations[name] ||
274 (this.parent && this.parent.findDeclaration(name))
275 );
276 },
277
278 // Sometimes, block scope declarations change name during transpilation
279 resolveName: function resolveName(name) {
280 var declaration = this.findDeclaration(name);
281 return declaration ? declaration.name : name;
282 }
283};
284
285function locate(source, index) {
286 var lines = source.split('\n');
287 var len = lines.length;
288
289 var lineStart = 0;
290 var i;
291
292 for (i = 0; i < len; i += 1) {
293 var line = lines[i];
294 var lineEnd = lineStart + line.length + 1; // +1 for newline
295
296 if (lineEnd > index) {
297 return { line: i + 1, column: index - lineStart, char: i };
298 }
299
300 lineStart = lineEnd;
301 }
302
303 throw new Error('Could not determine location of character');
304}
305
306function pad(num, len) {
307 var result = String(num);
308 return result + repeat(' ', len - result.length);
309}
310
311function repeat(str, times) {
312 var result = '';
313 while (times--) { result += str; }
314 return result;
315}
316
317function getSnippet(source, loc, length) {
318 if ( length === void 0 ) length = 1;
319
320 var first = Math.max(loc.line - 5, 0);
321 var last = loc.line;
322
323 var numDigits = String(last).length;
324
325 var lines = source.split('\n').slice(first, last);
326
327 var lastLine = lines[lines.length - 1];
328 var offset = lastLine.slice(0, loc.column).replace(/\t/g, ' ').length;
329
330 var snippet = lines
331 .map(function (line, i) { return ((pad(i + first + 1, numDigits)) + " : " + (line.replace(/\t/g, ' '))); })
332 .join('\n');
333
334 snippet += '\n' + repeat(' ', numDigits + 3 + offset) + repeat('^', length);
335
336 return snippet;
337}
338
339var CompileError = /*@__PURE__*/(function (Error) {
340 function CompileError(message, node) {
341 Error.call(this, message);
342
343 this.name = 'CompileError';
344 if (!node) {
345 return;
346 }
347
348 var source = node.program.magicString.original;
349 var loc = locate(source, node.start);
350
351 this.message = message + " (" + (loc.line) + ":" + (loc.column) + ")";
352
353 this.stack = new Error().stack.replace(
354 new RegExp((".+new " + (this.name) + ".+\\n"), 'm'),
355 ''
356 );
357
358 this.loc = loc;
359 this.snippet = getSnippet(source, loc, node.end - node.start);
360 }
361
362 if ( Error ) CompileError.__proto__ = Error;
363 CompileError.prototype = Object.create( Error && Error.prototype );
364 CompileError.prototype.constructor = CompileError;
365
366 CompileError.prototype.toString = function toString () {
367 return ((this.name) + ": " + (this.message) + "\n" + (this.snippet));
368 };
369
370 CompileError.missingTransform = function missingTransform (feature, transformKey, node, dangerousKey) {
371 if ( dangerousKey === void 0 ) dangerousKey = null;
372
373 var maybeDangerous = dangerousKey ? (", or `transforms: { " + dangerousKey + ": true }` if you know what you're doing") : '';
374 throw new CompileError(("Transforming " + feature + " is not " + (dangerousKey ? "fully supported" : "implemented") + ". Use `transforms: { " + transformKey + ": false }` to skip transformation and disable this error" + maybeDangerous + "."), node);
375 };
376
377 return CompileError;
378}(Error));
379
380function findIndex(array, fn) {
381 for (var i = 0; i < array.length; i += 1) {
382 if (fn(array[i], i)) { return i; }
383 }
384
385 return -1;
386}
387
388var handlers = {
389 Identifier: destructureIdentifier,
390 AssignmentPattern: destructureAssignmentPattern,
391 ArrayPattern: destructureArrayPattern,
392 ObjectPattern: destructureObjectPattern
393};
394
395function destructure(
396 code,
397 createIdentifier,
398 resolveName,
399 node,
400 ref,
401 inline,
402 statementGenerators
403) {
404 handlers[node.type](code, createIdentifier, resolveName, node, ref, inline, statementGenerators);
405}
406
407function destructureIdentifier(
408 code,
409 createIdentifier,
410 resolveName,
411 node,
412 ref,
413 inline,
414 statementGenerators
415) {
416 statementGenerators.push(function (start, prefix, suffix) {
417 code.overwrite(node.start, node.end, (inline ? prefix : (prefix + "var ")) + resolveName(node) + " = " + ref + suffix);
418 code.move(node.start, node.end, start);
419 });
420}
421
422function destructureMemberExpression(
423 code,
424 createIdentifier,
425 resolveName,
426 node,
427 ref,
428 inline,
429 statementGenerators
430) {
431 statementGenerators.push(function (start, prefix, suffix) {
432 code.prependRight(node.start, inline ? prefix : (prefix + "var "));
433 code.appendLeft(node.end, (" = " + ref + suffix));
434 code.move(node.start, node.end, start);
435 });
436}
437
438function destructureAssignmentPattern(
439 code,
440 createIdentifier,
441 resolveName,
442 node,
443 ref,
444 inline,
445 statementGenerators
446) {
447 var isIdentifier = node.left.type === 'Identifier';
448 var name = isIdentifier ? node.left.name : ref;
449
450 if (!inline) {
451 statementGenerators.push(function (start, prefix, suffix) {
452 code.prependRight(
453 node.left.end,
454 (prefix + "if ( " + name + " === void 0 ) " + name)
455 );
456 code.move(node.left.end, node.right.end, start);
457 code.appendLeft(node.right.end, suffix);
458 });
459 }
460
461 if (!isIdentifier) {
462 destructure(code, createIdentifier, resolveName, node.left, ref, inline, statementGenerators);
463 }
464}
465
466function destructureArrayPattern(
467 code,
468 createIdentifier,
469 resolveName,
470 node,
471 ref,
472 inline,
473 statementGenerators
474) {
475 var c = node.start;
476
477 node.elements.forEach(function (element, i) {
478 if (!element) { return; }
479
480 if (element.type === 'RestElement') {
481 handleProperty(
482 code,
483 createIdentifier,
484 resolveName,
485 c,
486 element.argument,
487 (ref + ".slice(" + i + ")"),
488 inline,
489 statementGenerators
490 );
491 } else {
492 handleProperty(
493 code,
494 createIdentifier,
495 resolveName,
496 c,
497 element,
498 (ref + "[" + i + "]"),
499 inline,
500 statementGenerators
501 );
502 }
503 c = element.end;
504 });
505
506 code.remove(c, node.end);
507}
508
509function destructureObjectPattern(
510 code,
511 createIdentifier,
512 resolveName,
513 node,
514 ref,
515 inline,
516 statementGenerators
517) {
518 var this$1 = this;
519
520 var c = node.start;
521
522 var nonRestKeys = [];
523 node.properties.forEach(function (prop) {
524 var value;
525 var content;
526 if (prop.type === 'Property') {
527 content = prop.value;
528 if (!prop.computed && prop.key.type === 'Identifier') {
529 value = ref + "." + (prop.key.name);
530 nonRestKeys.push(("\"" + (prop.key.name) + "\""));
531 } else if (!prop.computed && prop.key.type === 'Literal') {
532 value = ref + "[" + (prop.key.raw) + "]";
533 nonRestKeys.push(JSON.stringify(String(prop.key.value)));
534 } else {
535 var expr = code.slice(prop.key.start, prop.key.end);
536 value = ref + "[" + expr + "]";
537 nonRestKeys.push(("String(" + expr + ")"));
538 }
539 } else if (prop.type === 'RestElement') {
540 content = prop.argument;
541 value = createIdentifier('rest');
542 statementGenerators.push(function (start, prefix, suffix) {
543 var helper = prop.program.getObjectWithoutPropertiesHelper(code);
544 code.overwrite(
545 prop.start,
546 (c = prop.argument.start),
547 (inline ? prefix : (prefix + "var ")) + value + " = " + helper + "( " + ref + ", [" + (nonRestKeys.join(', ')) + "] )" + suffix
548 );
549 code.move(prop.start, c, start);
550 });
551 } else {
552 throw new CompileError(
553 this$1,
554 ("Unexpected node of type " + (prop.type) + " in object pattern")
555 );
556 }
557 handleProperty(code, createIdentifier, resolveName, c, content, value, inline, statementGenerators);
558 c = prop.end;
559 });
560
561 code.remove(c, node.end);
562}
563
564function handleProperty(
565 code,
566 createIdentifier,
567 resolveName,
568 c,
569 node,
570 value,
571 inline,
572 statementGenerators
573) {
574 switch (node.type) {
575 case 'Identifier': {
576 code.remove(c, node.start);
577 destructureIdentifier(
578 code,
579 createIdentifier,
580 resolveName,
581 node,
582 value,
583 inline,
584 statementGenerators
585 );
586 break;
587 }
588
589 case 'MemberExpression':
590 code.remove(c, node.start);
591 destructureMemberExpression(
592 code,
593 createIdentifier,
594 resolveName,
595 node,
596 value,
597 true,
598 statementGenerators
599 );
600 break;
601
602 case 'AssignmentPattern': {
603 var name;
604
605 var isIdentifier = node.left.type === 'Identifier';
606
607 if (isIdentifier) {
608 name = resolveName(node.left);
609 } else {
610 name = createIdentifier(value);
611 }
612
613 statementGenerators.push(function (start, prefix, suffix) {
614 if (inline) {
615 code.prependRight(
616 node.right.start,
617 (name + " = " + value + ", " + name + " = " + name + " === void 0 ? ")
618 );
619 code.appendLeft(node.right.end, (" : " + name + suffix));
620 } else {
621 code.prependRight(
622 node.right.start,
623 (prefix + "var " + name + " = " + value + "; if ( " + name + " === void 0 ) " + name + " = ")
624 );
625 code.appendLeft(node.right.end, suffix);
626 }
627
628 code.move(node.right.start, node.right.end, start);
629 });
630
631 if (isIdentifier) {
632 code.remove(c, node.right.start);
633 } else {
634 code.remove(c, node.left.start);
635 code.remove(node.left.end, node.right.start);
636 handleProperty(
637 code,
638 createIdentifier,
639 resolveName,
640 c,
641 node.left,
642 name,
643 inline,
644 statementGenerators
645 );
646 }
647
648 break;
649 }
650
651 case 'ObjectPattern': {
652 code.remove(c, (c = node.start));
653
654 var ref = value;
655 if (node.properties.length > 1) {
656 ref = createIdentifier(value);
657
658 statementGenerators.push(function (start, prefix, suffix) {
659 // this feels a tiny bit hacky, but we can't do a
660 // straightforward appendLeft and keep correct order...
661 code.prependRight(node.start, (inline ? '' : (prefix + "var ")) + ref + " = ");
662 code.overwrite(node.start, (c = node.start + 1), value);
663 code.appendLeft(c, suffix);
664
665 code.overwrite(
666 node.start,
667 (c = node.start + 1),
668 (inline ? '' : (prefix + "var ")) + ref + " = " + value + suffix
669 );
670 code.move(node.start, c, start);
671 });
672 }
673
674 destructureObjectPattern(
675 code,
676 createIdentifier,
677 resolveName,
678 node,
679 ref,
680 inline,
681 statementGenerators
682 );
683
684 break;
685 }
686
687 case 'ArrayPattern': {
688 code.remove(c, (c = node.start));
689
690 if (node.elements.filter(Boolean).length > 1) {
691 var ref$1 = createIdentifier(value);
692
693 statementGenerators.push(function (start, prefix, suffix) {
694 code.prependRight(node.start, (inline ? '' : (prefix + "var ")) + ref$1 + " = ");
695 code.overwrite(node.start, (c = node.start + 1), value, {
696 contentOnly: true
697 });
698 code.appendLeft(c, suffix);
699
700 code.move(node.start, c, start);
701 });
702
703 node.elements.forEach(function (element, i) {
704 if (!element) { return; }
705
706 if (element.type === 'RestElement') {
707 handleProperty(
708 code,
709 createIdentifier,
710 resolveName,
711 c,
712 element.argument,
713 (ref$1 + ".slice(" + i + ")"),
714 inline,
715 statementGenerators
716 );
717 } else {
718 handleProperty(
719 code,
720 createIdentifier,
721 resolveName,
722 c,
723 element,
724 (ref$1 + "[" + i + "]"),
725 inline,
726 statementGenerators
727 );
728 }
729 c = element.end;
730 });
731 } else {
732 var index = findIndex(node.elements, Boolean);
733 var element = node.elements[index];
734 if (element.type === 'RestElement') {
735 handleProperty(
736 code,
737 createIdentifier,
738 resolveName,
739 c,
740 element.argument,
741 (value + ".slice(" + index + ")"),
742 inline,
743 statementGenerators
744 );
745 } else {
746 handleProperty(
747 code,
748 createIdentifier,
749 resolveName,
750 c,
751 element,
752 (value + "[" + index + "]"),
753 inline,
754 statementGenerators
755 );
756 }
757 c = element.end;
758 }
759
760 code.remove(c, node.end);
761 break;
762 }
763
764 default: {
765 throw new Error(("Unexpected node type in destructuring (" + (node.type) + ")"));
766 }
767 }
768}
769
770function isUseStrict(node) {
771 if (!node) { return false; }
772 if (node.type !== 'ExpressionStatement') { return false; }
773 if (node.expression.type !== 'Literal') { return false; }
774 return node.expression.value === 'use strict';
775}
776
777var BlockStatement = /*@__PURE__*/(function (Node) {
778 function BlockStatement () {
779 Node.apply(this, arguments);
780 }
781
782 if ( Node ) BlockStatement.__proto__ = Node;
783 BlockStatement.prototype = Object.create( Node && Node.prototype );
784 BlockStatement.prototype.constructor = BlockStatement;
785
786 BlockStatement.prototype.createScope = function createScope () {
787 var this$1 = this;
788
789 this.parentIsFunction = /Function/.test(this.parent.type);
790 this.isFunctionBlock = this.parentIsFunction || this.parent.type === 'Root';
791 this.scope = new Scope({
792 block: !this.isFunctionBlock,
793 parent: this.parent.findScope(false),
794 declare: function (id) { return this$1.createdDeclarations.push(id); }
795 });
796
797 if (this.parentIsFunction) {
798 this.parent.params.forEach(function (node) {
799 this$1.scope.addDeclaration(node, 'param');
800 });
801 }
802 };
803
804 BlockStatement.prototype.initialise = function initialise (transforms) {
805 this.thisAlias = null;
806 this.argumentsAlias = null;
807 this.defaultParameters = [];
808 this.createdDeclarations = [];
809
810 // normally the scope gets created here, during initialisation,
811 // but in some cases (e.g. `for` statements), we need to create
812 // the scope early, as it pertains to both the init block and
813 // the body of the statement
814 if (!this.scope) { this.createScope(); }
815
816 this.body.forEach(function (node) { return node.initialise(transforms); });
817
818 this.scope.consolidate();
819 };
820
821 BlockStatement.prototype.findLexicalBoundary = function findLexicalBoundary () {
822 if (this.type === 'Program') { return this; }
823 if (/^Function/.test(this.parent.type)) { return this; }
824
825 return this.parent.findLexicalBoundary();
826 };
827
828 BlockStatement.prototype.findScope = function findScope (functionScope) {
829 if (functionScope && !this.isFunctionBlock)
830 { return this.parent.findScope(functionScope); }
831 return this.scope;
832 };
833
834 BlockStatement.prototype.getArgumentsAlias = function getArgumentsAlias () {
835 if (!this.argumentsAlias) {
836 this.argumentsAlias = this.scope.createIdentifier('arguments');
837 }
838
839 return this.argumentsAlias;
840 };
841
842 BlockStatement.prototype.getArgumentsArrayAlias = function getArgumentsArrayAlias () {
843 if (!this.argumentsArrayAlias) {
844 this.argumentsArrayAlias = this.scope.createIdentifier('argsArray');
845 }
846
847 return this.argumentsArrayAlias;
848 };
849
850 BlockStatement.prototype.getThisAlias = function getThisAlias () {
851 if (!this.thisAlias) {
852 this.thisAlias = this.scope.createIdentifier('this');
853 }
854
855 return this.thisAlias;
856 };
857
858 BlockStatement.prototype.getIndentation = function getIndentation () {
859 if (this.indentation === undefined) {
860 var source = this.program.magicString.original;
861
862 var useOuter = this.synthetic || !this.body.length;
863 var c = useOuter ? this.start : this.body[0].start;
864
865 while (c && source[c] !== '\n') { c -= 1; }
866
867 this.indentation = '';
868
869 // eslint-disable-next-line no-constant-condition
870 while (true) {
871 c += 1;
872 var char = source[c];
873
874 if (char !== ' ' && char !== '\t') { break; }
875
876 this.indentation += char;
877 }
878
879 var indentString = this.program.magicString.getIndentString();
880
881 // account for dedented class constructors
882 var parent = this.parent;
883 while (parent) {
884 if (parent.kind === 'constructor' && !parent.parent.parent.superClass) {
885 this.indentation = this.indentation.replace(indentString, '');
886 }
887
888 parent = parent.parent;
889 }
890
891 if (useOuter) { this.indentation += indentString; }
892 }
893
894 return this.indentation;
895 };
896
897 BlockStatement.prototype.transpile = function transpile (code, transforms) {
898 var this$1 = this;
899
900 var indentation = this.getIndentation();
901
902 var introStatementGenerators = [];
903
904 if (this.argumentsAlias) {
905 introStatementGenerators.push(function (start, prefix, suffix) {
906 var assignment = prefix + "var " + (this$1.argumentsAlias) + " = arguments" + suffix;
907 code.appendLeft(start, assignment);
908 });
909 }
910
911 if (this.thisAlias) {
912 introStatementGenerators.push(function (start, prefix, suffix) {
913 var assignment = prefix + "var " + (this$1.thisAlias) + " = this" + suffix;
914 code.appendLeft(start, assignment);
915 });
916 }
917
918 if (this.argumentsArrayAlias) {
919 introStatementGenerators.push(function (start, prefix, suffix) {
920 var i = this$1.scope.createIdentifier('i');
921 var assignment = prefix + "var " + i + " = arguments.length, " + (this$1.argumentsArrayAlias) + " = Array(" + i + ");\n" + indentation + "while ( " + i + "-- ) " + (this$1.argumentsArrayAlias) + "[" + i + "] = arguments[" + i + "]" + suffix;
922 code.appendLeft(start, assignment);
923 });
924 }
925
926 if (/Function/.test(this.parent.type)) {
927 this.transpileParameters(
928 this.parent.params,
929 code,
930 transforms,
931 indentation,
932 introStatementGenerators
933 );
934 } else if ('CatchClause' === this.parent.type) {
935 this.transpileParameters(
936 [this.parent.param],
937 code,
938 transforms,
939 indentation,
940 introStatementGenerators
941 );
942 }
943
944 if (transforms.letConst && this.isFunctionBlock) {
945 this.transpileBlockScopedIdentifiers(code);
946 }
947
948 Node.prototype.transpile.call(this, code, transforms);
949
950 if (this.createdDeclarations.length) {
951 introStatementGenerators.push(function (start, prefix, suffix) {
952 var assignment = prefix + "var " + (this$1.createdDeclarations.join(', ')) + suffix;
953 code.appendLeft(start, assignment);
954 });
955 }
956
957 if (this.synthetic) {
958 if (this.parent.type === 'ArrowFunctionExpression') {
959 var expr = this.body[0];
960
961 if (introStatementGenerators.length) {
962 code
963 .appendLeft(this.start, "{")
964 .prependRight(this.end, ((this.parent.getIndentation()) + "}"));
965
966 code.prependRight(expr.start, ("\n" + indentation + "return "));
967 code.appendLeft(expr.end, ";\n");
968 } else if (transforms.arrow) {
969 code.prependRight(expr.start, "{ return ");
970 code.appendLeft(expr.end, "; }");
971 }
972 } else if (introStatementGenerators.length) {
973 code.prependRight(this.start, "{").appendLeft(this.end, "}");
974 }
975 }
976
977 var start;
978 if (isUseStrict(this.body[0])) {
979 start = this.body[0].end;
980 } else if (this.synthetic || this.parent.type === 'Root') {
981 start = this.start;
982 } else {
983 start = this.start + 1;
984 }
985
986 var prefix = "\n" + indentation;
987 var suffix = ';';
988 introStatementGenerators.forEach(function (fn, i) {
989 if (i === introStatementGenerators.length - 1) { suffix = ";\n"; }
990 fn(start, prefix, suffix);
991 });
992 };
993
994 BlockStatement.prototype.transpileParameters = function transpileParameters (params, code, transforms, indentation, introStatementGenerators) {
995 var this$1 = this;
996
997 params.forEach(function (param) {
998 if (
999 param.type === 'AssignmentPattern' &&
1000 param.left.type === 'Identifier'
1001 ) {
1002 if (transforms.defaultParameter) {
1003 introStatementGenerators.push(function (start, prefix, suffix) {
1004 var lhs = prefix + "if ( " + (param.left.name) + " === void 0 ) " + (param.left.name);
1005
1006 code
1007 .prependRight(param.left.end, lhs)
1008 .move(param.left.end, param.right.end, start)
1009 .appendLeft(param.right.end, suffix);
1010 });
1011 }
1012 } else if (param.type === 'RestElement') {
1013 if (transforms.spreadRest) {
1014 introStatementGenerators.push(function (start, prefix, suffix) {
1015 var penultimateParam = params[params.length - 2];
1016
1017 if (penultimateParam) {
1018 code.remove(
1019 penultimateParam ? penultimateParam.end : param.start,
1020 param.end
1021 );
1022 } else {
1023 var start$1 = param.start,
1024 end = param.end; // TODO https://gitlab.com/Rich-Harris/buble/issues/8
1025
1026 while (/\s/.test(code.original[start$1 - 1])) { start$1 -= 1; }
1027 while (/\s/.test(code.original[end])) { end += 1; }
1028
1029 code.remove(start$1, end);
1030 }
1031
1032 var name = param.argument.name;
1033 var len = this$1.scope.createIdentifier('len');
1034 var count = params.length - 1;
1035
1036 if (count) {
1037 code.prependRight(
1038 start,
1039 (prefix + "var " + name + " = [], " + len + " = arguments.length - " + count + ";\n" + indentation + "while ( " + len + "-- > 0 ) " + name + "[ " + len + " ] = arguments[ " + len + " + " + count + " ]" + suffix)
1040 );
1041 } else {
1042 code.prependRight(
1043 start,
1044 (prefix + "var " + name + " = [], " + len + " = arguments.length;\n" + indentation + "while ( " + len + "-- ) " + name + "[ " + len + " ] = arguments[ " + len + " ]" + suffix)
1045 );
1046 }
1047 });
1048 }
1049 } else if (param.type !== 'Identifier') {
1050 if (transforms.parameterDestructuring) {
1051 var ref = this$1.scope.createIdentifier('ref');
1052 destructure(
1053 code,
1054 function (id) { return this$1.scope.createIdentifier(id); },
1055 function (ref) {
1056 var name = ref.name;
1057
1058 return this$1.scope.resolveName(name);
1059 },
1060 param,
1061 ref,
1062 false,
1063 introStatementGenerators
1064 );
1065 code.prependRight(param.start, ref);
1066 }
1067 }
1068 });
1069 };
1070
1071 BlockStatement.prototype.transpileBlockScopedIdentifiers = function transpileBlockScopedIdentifiers (code) {
1072 var this$1 = this;
1073
1074 Object.keys(this.scope.blockScopedDeclarations).forEach(function (name) {
1075 var declarations = this$1.scope.blockScopedDeclarations[name];
1076
1077 for (var i$2 = 0, list$2 = declarations; i$2 < list$2.length; i$2 += 1) {
1078 var declaration = list$2[i$2];
1079
1080 var cont = false; // TODO implement proper continue...
1081
1082 if (declaration.kind === 'for.let') {
1083 // special case
1084 var forStatement = declaration.node.findNearest('ForStatement');
1085
1086 if (forStatement.shouldRewriteAsFunction) {
1087 var outerAlias = this$1.scope.createIdentifier(name);
1088 var innerAlias = forStatement.reassigned[name]
1089 ? this$1.scope.createIdentifier(name)
1090 : name;
1091
1092 declaration.name = outerAlias;
1093 code.overwrite(
1094 declaration.node.start,
1095 declaration.node.end,
1096 outerAlias,
1097 { storeName: true }
1098 );
1099
1100 forStatement.aliases[name] = {
1101 outer: outerAlias,
1102 inner: innerAlias
1103 };
1104
1105 for (var i = 0, list = declaration.instances; i < list.length; i += 1) {
1106 var identifier = list[i];
1107
1108 var alias = forStatement.body.contains(identifier)
1109 ? innerAlias
1110 : outerAlias;
1111
1112 if (name !== alias) {
1113 code.overwrite(identifier.start, identifier.end, alias, {
1114 storeName: true
1115 });
1116 }
1117 }
1118
1119 cont = true;
1120 }
1121 }
1122
1123 if (!cont) {
1124 var alias$1 = this$1.scope.createIdentifier(name);
1125
1126 if (name !== alias$1) {
1127 var declarationParent = declaration.node.parent;
1128 declaration.name = alias$1;
1129 code.overwrite(
1130 declaration.node.start,
1131 declaration.node.end,
1132 alias$1,
1133 { storeName: true }
1134 );
1135 if (declarationParent.type === 'Property' && declarationParent.shorthand) {
1136 declarationParent.shorthand = false;
1137 code.prependLeft(declaration.node.start, (name + ": "));
1138 }
1139
1140 for (var i$1 = 0, list$1 = declaration.instances; i$1 < list$1.length; i$1 += 1) {
1141 var identifier$1 = list$1[i$1];
1142
1143 identifier$1.rewritten = true;
1144 var identifierParent = identifier$1.parent;
1145 code.overwrite(identifier$1.start, identifier$1.end, alias$1, {
1146 storeName: true
1147 });
1148 if (identifierParent.type === 'Property' && identifierParent.shorthand) {
1149 identifierParent.shorthand = false;
1150 code.prependLeft(identifier$1.start, (name + ": "));
1151 }
1152 }
1153 }
1154 }
1155 }
1156 });
1157 };
1158
1159 return BlockStatement;
1160}(Node));
1161
1162function isArguments(node) {
1163 return node.type === 'Identifier' && node.name === 'arguments';
1164}
1165
1166function inlineSpreads(
1167 code,
1168 node,
1169 elements
1170) {
1171 var i = elements.length;
1172
1173 while (i--) {
1174 var element = elements[i];
1175 if (!element || element.type !== 'SpreadElement') {
1176 continue;
1177 }
1178 var argument = element.argument;
1179 if (argument.type !== 'ArrayExpression') {
1180 continue;
1181 }
1182 var subelements = argument.elements;
1183 if (subelements.some(function (subelement) { return subelement === null; })) {
1184 // Not even going to try inlining spread arrays with holes.
1185 // It's a lot of work (got to be VERY careful in comma counting for
1186 // ArrayExpression, and turn blanks into undefined for
1187 // CallExpression and NewExpression), and probably literally no one
1188 // would ever benefit from it.
1189 continue;
1190 }
1191 // We can inline it: drop the `...[` and `]` and sort out any commas.
1192 var isLast = i === elements.length - 1;
1193 if (subelements.length === 0) {
1194 code.remove(
1195 isLast && i !== 0
1196 ? elements[i - 1].end // Take the previous comma too
1197 : element.start,
1198 isLast
1199 ? node.end - 1 // Must remove trailing comma; element.end wouldn’t
1200 : elements[i + 1].start);
1201 } else {
1202 // Strip the `...[` and the `]` with a possible trailing comma before it,
1203 // leaving just the possible trailing comma after it.
1204 code.remove(element.start, subelements[0].start);
1205 code.remove(
1206 // Strip a possible trailing comma after the last element
1207 subelements[subelements.length - 1].end,
1208 // And also a possible trailing comma after the spread
1209 isLast
1210 ? node.end - 1
1211 : element.end
1212 );
1213 }
1214 elements.splice.apply(elements, [ i, 1 ].concat( subelements ));
1215 i += subelements.length;
1216 }
1217}
1218
1219// Returns false if it’s safe to simply append a method call to the node,
1220// e.g. `a` → `a.concat()`.
1221//
1222// Returns true if it may not be and so parentheses should be employed,
1223// e.g. `a ? b : c` → `a ? b : c.concat()` would be wrong.
1224//
1225// This test may be overcautious; if desired it can be refined over time.
1226function needsParentheses(node) {
1227 switch (node.type) {
1228 // Currently whitelisted are all relevant ES5 node types ('Literal' and
1229 // 'ObjectExpression' are skipped as irrelevant for array/call spread.)
1230 case 'ArrayExpression':
1231 case 'CallExpression':
1232 case 'Identifier':
1233 case 'ParenthesizedExpression':
1234 case 'ThisExpression':
1235 return false;
1236 default:
1237 return true;
1238 }
1239}
1240
1241function spread(
1242 code,
1243 elements,
1244 start,
1245 argumentsArrayAlias,
1246 isNew
1247) {
1248 var i = elements.length;
1249 var firstSpreadIndex = -1;
1250
1251 while (i--) {
1252 var element$1 = elements[i];
1253 if (element$1 && element$1.type === 'SpreadElement') {
1254 if (isArguments(element$1.argument)) {
1255 code.overwrite(
1256 element$1.argument.start,
1257 element$1.argument.end,
1258 argumentsArrayAlias
1259 );
1260 }
1261
1262 firstSpreadIndex = i;
1263 }
1264 }
1265
1266 if (firstSpreadIndex === -1) { return false; } // false indicates no spread elements
1267
1268 if (isNew) {
1269 for (i = 0; i < elements.length; i += 1) {
1270 var element$2 = elements[i];
1271 if (element$2.type === 'SpreadElement') {
1272 code.remove(element$2.start, element$2.argument.start);
1273 } else {
1274 code.prependRight(element$2.start, '[');
1275 code.prependRight(element$2.end, ']');
1276 }
1277 }
1278
1279 return true; // true indicates some spread elements
1280 }
1281
1282 var element = elements[firstSpreadIndex];
1283 var previousElement = elements[firstSpreadIndex - 1];
1284
1285 if (!previousElement) {
1286 // We may need to parenthesize it to handle ternaries like [...a ? b : c].
1287 var addClosingParen;
1288 if (start !== element.start) {
1289 if ((addClosingParen = needsParentheses(element.argument))) {
1290 code.overwrite(start, element.start, '( ');
1291 } else {
1292 code.remove(start, element.start);
1293 }
1294 } else if (element.parent.type === 'CallExpression') {
1295 // CallExpression inserts `( ` itself, we add the ).
1296 // (Yeah, CallExpression did the needsParentheses call already,
1297 // but we don’t have its result handy, so do it again. It’s cheap.)
1298 addClosingParen = needsParentheses(element.argument);
1299 } else {
1300 // Should be unreachable, but doing this is more robust.
1301 throw new CompileError(
1302 'Unsupported spread construct, please raise an issue at https://github.com/bublejs/buble/issues',
1303 element
1304 );
1305 }
1306 code.overwrite(element.end, elements[1].start,
1307 addClosingParen ? ' ).concat( ' : '.concat( ');
1308 } else {
1309 code.overwrite(previousElement.end, element.start, ' ].concat( ');
1310 }
1311
1312 for (i = firstSpreadIndex; i < elements.length; i += 1) {
1313 element = elements[i];
1314
1315 if (element) {
1316 if (element.type === 'SpreadElement') {
1317 code.remove(element.start, element.argument.start);
1318 } else {
1319 code.appendLeft(element.start, '[');
1320 code.appendLeft(element.end, ']');
1321 }
1322 }
1323 }
1324
1325 return true; // true indicates some spread elements
1326}
1327
1328var ArrayExpression = /*@__PURE__*/(function (Node) {
1329 function ArrayExpression () {
1330 Node.apply(this, arguments);
1331 }
1332
1333 if ( Node ) ArrayExpression.__proto__ = Node;
1334 ArrayExpression.prototype = Object.create( Node && Node.prototype );
1335 ArrayExpression.prototype.constructor = ArrayExpression;
1336
1337 ArrayExpression.prototype.initialise = function initialise (transforms) {
1338 if (transforms.spreadRest && this.elements.length) {
1339 var lexicalBoundary = this.findLexicalBoundary();
1340
1341 var i = this.elements.length;
1342 while (i--) {
1343 var element = this.elements[i];
1344 if (
1345 element &&
1346 element.type === 'SpreadElement' &&
1347 isArguments(element.argument)
1348 ) {
1349 this.argumentsArrayAlias = lexicalBoundary.getArgumentsArrayAlias();
1350 }
1351 }
1352 }
1353
1354 Node.prototype.initialise.call(this, transforms);
1355 };
1356
1357 ArrayExpression.prototype.transpile = function transpile (code, transforms) {
1358 Node.prototype.transpile.call(this, code, transforms);
1359
1360 if (transforms.spreadRest) {
1361 inlineSpreads(code, this, this.elements);
1362 // erase trailing comma after last array element if not an array hole
1363 if (this.elements.length) {
1364 var lastElement = this.elements[this.elements.length - 1];
1365 if (
1366 lastElement &&
1367 /\s*,/.test(code.original.slice(lastElement.end, this.end))
1368 ) {
1369 code.overwrite(lastElement.end, this.end - 1, ' ');
1370 }
1371 }
1372
1373 if (this.elements.length === 1) {
1374 var element = this.elements[0];
1375
1376 if (element && element.type === 'SpreadElement') {
1377 // special case – [ ...arguments ]
1378 if (isArguments(element.argument)) {
1379 code.overwrite(
1380 this.start,
1381 this.end,
1382 ("[].concat( " + (this.argumentsArrayAlias) + " )")
1383 ); // TODO if this is the only use of argsArray, don't bother concating
1384 } else {
1385 code.overwrite(this.start, element.argument.start, '[].concat( ');
1386 code.overwrite(element.end, this.end, ' )');
1387 }
1388 }
1389 } else {
1390 var hasSpreadElements = spread(
1391 code,
1392 this.elements,
1393 this.start,
1394 this.argumentsArrayAlias
1395 );
1396
1397 if (hasSpreadElements) {
1398 code.overwrite(this.end - 1, this.end, ')');
1399 }
1400 }
1401 }
1402 };
1403
1404 return ArrayExpression;
1405}(Node));
1406
1407function removeTrailingComma(code, c) {
1408 while (code.original[c] !== ')') {
1409 if (code.original[c] === ',') {
1410 code.remove(c, c + 1);
1411 return;
1412 }
1413
1414 if (code.original[c] === '/') {
1415 if (code.original[c + 1] === '/') {
1416 c = code.original.indexOf('\n', c);
1417 } else {
1418 c = code.original.indexOf('*/', c) + 1;
1419 }
1420 }
1421 c += 1;
1422 }
1423}
1424
1425var ArrowFunctionExpression = /*@__PURE__*/(function (Node) {
1426 function ArrowFunctionExpression () {
1427 Node.apply(this, arguments);
1428 }
1429
1430 if ( Node ) ArrowFunctionExpression.__proto__ = Node;
1431 ArrowFunctionExpression.prototype = Object.create( Node && Node.prototype );
1432 ArrowFunctionExpression.prototype.constructor = ArrowFunctionExpression;
1433
1434 ArrowFunctionExpression.prototype.initialise = function initialise (transforms) {
1435 if (this.async && transforms.asyncAwait) {
1436 CompileError.missingTransform("async arrow functions", "asyncAwait", this);
1437 }
1438 this.body.createScope();
1439 Node.prototype.initialise.call(this, transforms);
1440 };
1441
1442 ArrowFunctionExpression.prototype.transpile = function transpile (code, transforms) {
1443 var openParensPos = this.start;
1444 for (var end = (this.body || this.params[0]).start - 1; code.original[openParensPos] !== '(' && openParensPos < end;) {
1445 ++openParensPos;
1446 }
1447 if (code.original[openParensPos] !== '(') { openParensPos = -1; }
1448 var naked = openParensPos === -1;
1449
1450 if (transforms.arrow || this.needsArguments(transforms)) {
1451 // remove arrow
1452 var charIndex = this.body.start;
1453 while (code.original[charIndex] !== '=') {
1454 charIndex -= 1;
1455 }
1456 code.remove(charIndex, this.body.start);
1457
1458 Node.prototype.transpile.call(this, code, transforms);
1459
1460 // wrap naked parameter
1461 if (naked) {
1462 code.prependRight(this.params[0].start, '(');
1463 code.appendLeft(this.params[0].end, ')');
1464 }
1465
1466 // standalone expression statement
1467 var standalone = this.parent && this.parent.type === 'ExpressionStatement';
1468 var start, text = standalone ? '!' : '';
1469 if (this.async) { text += 'async '; }
1470 text += 'function';
1471 if (!standalone) { text += ' '; }
1472 if (naked) {
1473 start = this.params[0].start;
1474 } else {
1475 start = openParensPos;
1476 }
1477 // add function
1478 if (start > this.start) {
1479 code.overwrite(this.start, start, text);
1480 } else {
1481 code.prependRight(this.start, text);
1482 }
1483 } else {
1484 Node.prototype.transpile.call(this, code, transforms);
1485 }
1486
1487 if (transforms.trailingFunctionCommas && this.params.length && !naked) {
1488 removeTrailingComma(code, this.params[this.params.length - 1].end);
1489 }
1490 };
1491
1492 // Returns whether any transforms that will happen use `arguments`
1493 ArrowFunctionExpression.prototype.needsArguments = function needsArguments (transforms) {
1494 return (
1495 transforms.spreadRest &&
1496 this.params.filter(function (param) { return param.type === 'RestElement'; }).length > 0
1497 );
1498 };
1499
1500 return ArrowFunctionExpression;
1501}(Node));
1502
1503function checkConst(identifier, scope) {
1504 var declaration = scope.findDeclaration(identifier.name);
1505 if (declaration && declaration.kind === 'const') {
1506 throw new CompileError(((identifier.name) + " is read-only"), identifier);
1507 }
1508}
1509
1510var AssignmentExpression = /*@__PURE__*/(function (Node) {
1511 function AssignmentExpression () {
1512 Node.apply(this, arguments);
1513 }
1514
1515 if ( Node ) AssignmentExpression.__proto__ = Node;
1516 AssignmentExpression.prototype = Object.create( Node && Node.prototype );
1517 AssignmentExpression.prototype.constructor = AssignmentExpression;
1518
1519 AssignmentExpression.prototype.initialise = function initialise (transforms) {
1520 if (this.left.type === 'Identifier') {
1521 var declaration = this.findScope(false).findDeclaration(this.left.name);
1522 // special case – https://gitlab.com/Rich-Harris/buble/issues/11
1523 var statement = declaration && declaration.node.ancestor(3);
1524 if (
1525 statement &&
1526 statement.type === 'ForStatement' &&
1527 statement.body.contains(this)
1528 ) {
1529 statement.reassigned[this.left.name] = true;
1530 }
1531 }
1532
1533 Node.prototype.initialise.call(this, transforms);
1534 };
1535
1536 AssignmentExpression.prototype.transpile = function transpile (code, transforms) {
1537 if (this.left.type === 'Identifier') {
1538 // Do this check after everything has been initialized to find
1539 // shadowing declarations after this expression
1540 checkConst(this.left, this.findScope(false));
1541 }
1542
1543 if (this.operator === '**=' && transforms.exponentiation) {
1544 this.transpileExponentiation(code, transforms);
1545 } else if (/Pattern/.test(this.left.type) && transforms.destructuring) {
1546 this.transpileDestructuring(code);
1547 }
1548
1549 Node.prototype.transpile.call(this, code, transforms);
1550 };
1551
1552 AssignmentExpression.prototype.transpileDestructuring = function transpileDestructuring (code) {
1553 var this$1 = this;
1554
1555 var writeScope = this.findScope(true);
1556 var lookupScope = this.findScope(false);
1557 var assign = writeScope.createDeclaration('assign');
1558 code.appendRight(this.left.end, ("(" + assign));
1559
1560 code.appendLeft(this.right.end, ', ');
1561 var statementGenerators = [];
1562 destructure(
1563 code,
1564 function (id) { return writeScope.createDeclaration(id); },
1565 function (node) {
1566 var name = lookupScope.resolveName(node.name);
1567 checkConst(node, lookupScope);
1568 return name;
1569 },
1570 this.left,
1571 assign,
1572 true,
1573 statementGenerators
1574 );
1575
1576 var suffix = ', ';
1577 statementGenerators.forEach(function (fn, j) {
1578 if (j === statementGenerators.length - 1) {
1579 suffix = '';
1580 }
1581
1582 fn(this$1.end, '', suffix);
1583 });
1584
1585 if (this.unparenthesizedParent().type === 'ExpressionStatement') {
1586 // no rvalue needed for expression statement
1587 code.prependRight(this.end, ")");
1588 } else {
1589 // destructuring is part of an expression - need an rvalue
1590 code.appendRight(this.end, (", " + assign + ")"));
1591 }
1592 };
1593
1594 AssignmentExpression.prototype.transpileExponentiation = function transpileExponentiation (code) {
1595 var scope = this.findScope(false);
1596
1597 // first, the easy part – `**=` -> `=`
1598 var charIndex = this.left.end;
1599 while (code.original[charIndex] !== '*') { charIndex += 1; }
1600 code.remove(charIndex, charIndex + 2);
1601
1602 // how we do the next part depends on a number of factors – whether
1603 // this is a top-level statement, and whether we're updating a
1604 // simple or complex reference
1605 var base;
1606
1607 var left = this.left.unparenthesize();
1608
1609 if (left.type === 'Identifier') {
1610 base = scope.resolveName(left.name);
1611 } else if (left.type === 'MemberExpression') {
1612 var object;
1613 var needsObjectVar = false;
1614 var property;
1615 var needsPropertyVar = false;
1616
1617 var statement = this.findNearest(/(?:Statement|Declaration)$/);
1618 var i0 = statement.getIndentation();
1619
1620 if (left.property.type === 'Identifier') {
1621 property = left.computed
1622 ? scope.resolveName(left.property.name)
1623 : left.property.name;
1624 } else {
1625 property = scope.createDeclaration('property');
1626 needsPropertyVar = true;
1627 }
1628
1629 if (left.object.type === 'Identifier') {
1630 object = scope.resolveName(left.object.name);
1631 } else {
1632 object = scope.createDeclaration('object');
1633 needsObjectVar = true;
1634 }
1635
1636 if (left.start === statement.start) {
1637 if (needsObjectVar && needsPropertyVar) {
1638 code.prependRight(statement.start, (object + " = "));
1639 code.overwrite(
1640 left.object.end,
1641 left.property.start,
1642 (";\n" + i0 + property + " = ")
1643 );
1644 code.overwrite(
1645 left.property.end,
1646 left.end,
1647 (";\n" + i0 + object + "[" + property + "]")
1648 );
1649 } else if (needsObjectVar) {
1650 code.prependRight(statement.start, (object + " = "));
1651 code.appendLeft(left.object.end, (";\n" + i0));
1652 code.appendLeft(left.object.end, object);
1653 } else if (needsPropertyVar) {
1654 code.prependRight(left.property.start, (property + " = "));
1655 code.appendLeft(left.property.end, (";\n" + i0));
1656 code.move(left.property.start, left.property.end, this.start);
1657
1658 code.appendLeft(left.object.end, ("[" + property + "]"));
1659 code.remove(left.object.end, left.property.start);
1660 code.remove(left.property.end, left.end);
1661 }
1662 } else {
1663 if (needsObjectVar && needsPropertyVar) {
1664 code.prependRight(left.start, ("( " + object + " = "));
1665 code.overwrite(
1666 left.object.end,
1667 left.property.start,
1668 (", " + property + " = ")
1669 );
1670 code.overwrite(
1671 left.property.end,
1672 left.end,
1673 (", " + object + "[" + property + "]")
1674 );
1675 } else if (needsObjectVar) {
1676 code.prependRight(left.start, ("( " + object + " = "));
1677 code.appendLeft(left.object.end, (", " + object));
1678 } else if (needsPropertyVar) {
1679 code.prependRight(left.property.start, ("( " + property + " = "));
1680 code.appendLeft(left.property.end, ", ");
1681 code.move(left.property.start, left.property.end, left.start);
1682
1683 code.overwrite(left.object.end, left.property.start, ("[" + property + "]"));
1684 code.remove(left.property.end, left.end);
1685 }
1686
1687 if (needsPropertyVar) {
1688 code.appendLeft(this.end, " )");
1689 }
1690 }
1691
1692 base =
1693 object +
1694 (left.computed || needsPropertyVar ? ("[" + property + "]") : ("." + property));
1695 }
1696
1697 code.prependRight(this.right.start, ("Math.pow( " + base + ", "));
1698 code.appendLeft(this.right.end, " )");
1699 };
1700
1701 return AssignmentExpression;
1702}(Node));
1703
1704var AwaitExpression = /*@__PURE__*/(function (Node) {
1705 function AwaitExpression () {
1706 Node.apply(this, arguments);
1707 }
1708
1709 if ( Node ) AwaitExpression.__proto__ = Node;
1710 AwaitExpression.prototype = Object.create( Node && Node.prototype );
1711 AwaitExpression.prototype.constructor = AwaitExpression;
1712
1713 AwaitExpression.prototype.initialise = function initialise (transforms) {
1714 if (transforms.asyncAwait) {
1715 CompileError.missingTransform("await", "asyncAwait", this);
1716 }
1717 Node.prototype.initialise.call(this, transforms);
1718 };
1719
1720 return AwaitExpression;
1721}(Node));
1722
1723var BinaryExpression = /*@__PURE__*/(function (Node) {
1724 function BinaryExpression () {
1725 Node.apply(this, arguments);
1726 }
1727
1728 if ( Node ) BinaryExpression.__proto__ = Node;
1729 BinaryExpression.prototype = Object.create( Node && Node.prototype );
1730 BinaryExpression.prototype.constructor = BinaryExpression;
1731
1732 BinaryExpression.prototype.transpile = function transpile (code, transforms) {
1733 if (this.operator === '**' && transforms.exponentiation) {
1734 code.prependRight(this.start, "Math.pow( ");
1735 code.overwrite(this.left.end, this.right.start, ", ");
1736 code.appendLeft(this.end, " )");
1737 }
1738 Node.prototype.transpile.call(this, code, transforms);
1739 };
1740
1741 return BinaryExpression;
1742}(Node));
1743
1744var loopStatement = /(?:For(?:In|Of)?|While)Statement/;
1745
1746var BreakStatement = /*@__PURE__*/(function (Node) {
1747 function BreakStatement () {
1748 Node.apply(this, arguments);
1749 }
1750
1751 if ( Node ) BreakStatement.__proto__ = Node;
1752 BreakStatement.prototype = Object.create( Node && Node.prototype );
1753 BreakStatement.prototype.constructor = BreakStatement;
1754
1755 BreakStatement.prototype.initialise = function initialise () {
1756 var loop = this.findNearest(loopStatement);
1757 var switchCase = this.findNearest('SwitchCase');
1758
1759 if (loop && (!switchCase || loop.depth > switchCase.depth)) {
1760 loop.canBreak = true;
1761 this.loop = loop;
1762 }
1763 };
1764
1765 BreakStatement.prototype.transpile = function transpile (code) {
1766 if (this.loop && this.loop.shouldRewriteAsFunction) {
1767 if (this.label)
1768 { throw new CompileError(
1769 'Labels are not currently supported in a loop with locally-scoped variables',
1770 this
1771 ); }
1772 code.overwrite(this.start, this.start + 5, "return 'break'");
1773 }
1774 };
1775
1776 return BreakStatement;
1777}(Node));
1778
1779var CallExpression = /*@__PURE__*/(function (Node) {
1780 function CallExpression () {
1781 Node.apply(this, arguments);
1782 }
1783
1784 if ( Node ) CallExpression.__proto__ = Node;
1785 CallExpression.prototype = Object.create( Node && Node.prototype );
1786 CallExpression.prototype.constructor = CallExpression;
1787
1788 CallExpression.prototype.initialise = function initialise (transforms) {
1789 if (transforms.spreadRest && this.arguments.length > 1) {
1790 var lexicalBoundary = this.findLexicalBoundary();
1791
1792 var i = this.arguments.length;
1793 while (i--) {
1794 var arg = this.arguments[i];
1795 if (arg.type === 'SpreadElement' && isArguments(arg.argument)) {
1796 this.argumentsArrayAlias = lexicalBoundary.getArgumentsArrayAlias();
1797 }
1798 }
1799 }
1800
1801 Node.prototype.initialise.call(this, transforms);
1802 };
1803
1804 CallExpression.prototype.transpile = function transpile (code, transforms) {
1805 if (transforms.spreadRest && this.arguments.length) {
1806 inlineSpreads(code, this, this.arguments);
1807 // this.arguments.length may have changed, must retest.
1808 }
1809
1810 if (transforms.spreadRest && this.arguments.length) {
1811 var hasSpreadElements = false;
1812 var context;
1813
1814 var firstArgument = this.arguments[0];
1815
1816 if (this.arguments.length === 1) {
1817 if (firstArgument.type === 'SpreadElement') {
1818 code.remove(firstArgument.start, firstArgument.argument.start);
1819 hasSpreadElements = true;
1820 }
1821 } else {
1822 hasSpreadElements = spread(
1823 code,
1824 this.arguments,
1825 firstArgument.start,
1826 this.argumentsArrayAlias
1827 );
1828 }
1829
1830 if (hasSpreadElements) {
1831 // we need to handle super() and super.method() differently
1832 // due to its instance
1833 var _super = null;
1834 if (this.callee.type === 'Super') {
1835 _super = this.callee;
1836 } else if (
1837 this.callee.type === 'MemberExpression' &&
1838 this.callee.object.type === 'Super'
1839 ) {
1840 _super = this.callee.object;
1841 }
1842
1843 if (!_super && this.callee.type === 'MemberExpression') {
1844 if (this.callee.object.type === 'Identifier') {
1845 context = this.callee.object.name;
1846 } else {
1847 context = this.findScope(true).createDeclaration('ref');
1848 var callExpression = this.callee.object;
1849 code.prependRight(callExpression.start, ("(" + context + " = "));
1850 code.appendLeft(callExpression.end, ")");
1851 }
1852 } else {
1853 context = 'void 0';
1854 }
1855
1856 code.appendLeft(this.callee.end, '.apply');
1857
1858 if (_super) {
1859 _super.noCall = true; // bit hacky...
1860
1861 if (this.arguments.length > 1) {
1862 if (firstArgument.type === 'SpreadElement') {
1863 if (needsParentheses(firstArgument.argument)) {
1864 code.prependRight(firstArgument.start, "( ");
1865 }
1866 } else {
1867 code.prependRight(firstArgument.start, "[ ");
1868 }
1869
1870 code.appendLeft(
1871 this.arguments[this.arguments.length - 1].end,
1872 ' )'
1873 );
1874 }
1875 } else if (this.arguments.length === 1) {
1876 code.prependRight(firstArgument.start, (context + ", "));
1877 } else {
1878 if (firstArgument.type === 'SpreadElement') {
1879 if (needsParentheses(firstArgument.argument)) {
1880 code.appendLeft(firstArgument.start, (context + ", ( "));
1881 } else {
1882 code.appendLeft(firstArgument.start, (context + ", "));
1883 }
1884 } else {
1885 code.appendLeft(firstArgument.start, (context + ", [ "));
1886 }
1887
1888 code.appendLeft(this.arguments[this.arguments.length - 1].end, ' )');
1889 }
1890 }
1891 }
1892
1893 if (transforms.trailingFunctionCommas && this.arguments.length) {
1894 removeTrailingComma(code, this.arguments[this.arguments.length - 1].end);
1895 }
1896
1897 Node.prototype.transpile.call(this, code, transforms);
1898 };
1899
1900 return CallExpression;
1901}(Node));
1902
1903var CatchClause = /*@__PURE__*/(function (Node) {
1904 function CatchClause () {
1905 Node.apply(this, arguments);
1906 }
1907
1908 if ( Node ) CatchClause.__proto__ = Node;
1909 CatchClause.prototype = Object.create( Node && Node.prototype );
1910 CatchClause.prototype.constructor = CatchClause;
1911
1912 CatchClause.prototype.initialise = function initialise (transforms) {
1913 var this$1 = this;
1914
1915 this.createdDeclarations = [];
1916 this.scope = new Scope({
1917 block: true,
1918 parent: this.parent.findScope(false),
1919 declare: function (id) { return this$1.createdDeclarations.push(id); }
1920 });
1921
1922 this.scope.addDeclaration(this.param, 'catch');
1923
1924 Node.prototype.initialise.call(this, transforms);
1925 this.scope.consolidate();
1926 };
1927
1928 CatchClause.prototype.findScope = function findScope (functionScope) {
1929 return functionScope
1930 ? this.parent.findScope(functionScope)
1931 : this.scope;
1932 };
1933
1934 return CatchClause;
1935}(Node));
1936
1937// TODO this code is pretty wild, tidy it up
1938var ClassBody = /*@__PURE__*/(function (Node) {
1939 function ClassBody () {
1940 Node.apply(this, arguments);
1941 }
1942
1943 if ( Node ) ClassBody.__proto__ = Node;
1944 ClassBody.prototype = Object.create( Node && Node.prototype );
1945 ClassBody.prototype.constructor = ClassBody;
1946
1947 ClassBody.prototype.transpile = function transpile (code, transforms, inFunctionExpression, superName) {
1948 var this$1 = this;
1949
1950 if (transforms.classes) {
1951 var name = this.parent.name;
1952
1953 var indentStr = code.getIndentString();
1954 var i0 =
1955 this.getIndentation() + (inFunctionExpression ? indentStr : '');
1956 var i1 = i0 + indentStr;
1957
1958 var constructorIndex = findIndex(
1959 this.body,
1960 function (node) { return node.kind === 'constructor'; }
1961 );
1962 var constructor = this.body[constructorIndex];
1963
1964 var introBlock = '';
1965 var outroBlock = '';
1966
1967 if (this.body.length) {
1968 code.remove(this.start, this.body[0].start);
1969 code.remove(this.body[this.body.length - 1].end, this.end);
1970 } else {
1971 code.remove(this.start, this.end);
1972 }
1973
1974 if (constructor) {
1975 constructor.value.body.isConstructorBody = true;
1976
1977 var previousMethod = this.body[constructorIndex - 1];
1978 var nextMethod = this.body[constructorIndex + 1];
1979
1980 // ensure constructor is first
1981 if (constructorIndex > 0) {
1982 code.remove(previousMethod.end, constructor.start);
1983 code.move(
1984 constructor.start,
1985 nextMethod ? nextMethod.start : this.end - 1,
1986 this.body[0].start
1987 );
1988 }
1989
1990 if (!inFunctionExpression) { code.appendLeft(constructor.end, ';'); }
1991 }
1992
1993 var namedFunctions =
1994 this.program.options.namedFunctionExpressions !== false;
1995 var namedConstructor =
1996 namedFunctions ||
1997 this.parent.superClass ||
1998 this.parent.type !== 'ClassDeclaration';
1999 if (this.parent.superClass) {
2000 var inheritanceBlock = "if ( " + superName + " ) " + name + ".__proto__ = " + superName + ";\n" + i0 + name + ".prototype = Object.create( " + superName + " && " + superName + ".prototype );\n" + i0 + name + ".prototype.constructor = " + name + ";";
2001
2002 if (constructor) {
2003 introBlock += "\n\n" + i0 + inheritanceBlock;
2004 } else {
2005 var fn =
2006 "function " + name + " () {" +
2007 (superName
2008 ? ("\n" + i1 + superName + ".apply(this, arguments);\n" + i0 + "}")
2009 : "}") +
2010 (inFunctionExpression ? '' : ';') +
2011 (this.body.length ? ("\n\n" + i0) : '');
2012
2013 inheritanceBlock = fn + inheritanceBlock;
2014 introBlock += inheritanceBlock + "\n\n" + i0;
2015 }
2016 } else if (!constructor) {
2017 var fn$1 = 'function ' + (namedConstructor ? name + ' ' : '') + '() {}';
2018 if (this.parent.type === 'ClassDeclaration') { fn$1 += ';'; }
2019 if (this.body.length) { fn$1 += "\n\n" + i0; }
2020
2021 introBlock += fn$1;
2022 }
2023
2024 var scope = this.findScope(false);
2025
2026 var prototypeGettersAndSetters = [];
2027 var staticGettersAndSetters = [];
2028 var prototypeAccessors;
2029 var staticAccessors;
2030
2031 this.body.forEach(function (method, i) {
2032 if ((method.kind === 'get' || method.kind === 'set') && transforms.getterSetter) {
2033 CompileError.missingTransform("getters and setters", "getterSetter", method);
2034 }
2035
2036 if (method.kind === 'constructor') {
2037 var constructorName = namedConstructor ? ' ' + name : '';
2038 code.overwrite(
2039 method.key.start,
2040 method.key.end,
2041 ("function" + constructorName)
2042 );
2043 return;
2044 }
2045
2046 if (method.static) {
2047 var len = code.original[method.start + 6] == ' ' ? 7 : 6;
2048 code.remove(method.start, method.start + len);
2049 }
2050
2051 var isAccessor = method.kind !== 'method';
2052 var lhs;
2053
2054 var methodName = method.key.name;
2055 if (
2056 reserved[methodName] ||
2057 method.value.body.scope.references[methodName]
2058 ) {
2059 methodName = scope.createIdentifier(methodName);
2060 }
2061
2062 // when method name is a string or a number let's pretend it's a computed method
2063
2064 var fake_computed = false;
2065 if (!method.computed && method.key.type === 'Literal') {
2066 fake_computed = true;
2067 method.computed = true;
2068 }
2069
2070 if (isAccessor) {
2071 if (method.computed) {
2072 throw new Error(
2073 'Computed accessor properties are not currently supported'
2074 );
2075 }
2076
2077 code.remove(method.start, method.key.start);
2078
2079 if (method.static) {
2080 if (!~staticGettersAndSetters.indexOf(method.key.name))
2081 { staticGettersAndSetters.push(method.key.name); }
2082 if (!staticAccessors)
2083 { staticAccessors = scope.createIdentifier('staticAccessors'); }
2084
2085 lhs = "" + staticAccessors;
2086 } else {
2087 if (!~prototypeGettersAndSetters.indexOf(method.key.name))
2088 { prototypeGettersAndSetters.push(method.key.name); }
2089 if (!prototypeAccessors)
2090 { prototypeAccessors = scope.createIdentifier('prototypeAccessors'); }
2091
2092 lhs = "" + prototypeAccessors;
2093 }
2094 } else {
2095 lhs = method.static ? ("" + name) : (name + ".prototype");
2096 }
2097
2098 if (!method.computed) { lhs += '.'; }
2099
2100 var insertNewlines =
2101 (constructorIndex > 0 && i === constructorIndex + 1) ||
2102 (i === 0 && constructorIndex === this$1.body.length - 1);
2103
2104 if (insertNewlines) { lhs = "\n\n" + i0 + lhs; }
2105
2106 var c = method.key.end;
2107 if (method.computed) {
2108 if (fake_computed) {
2109 code.prependRight(method.key.start, '[');
2110 code.appendLeft(method.key.end, ']');
2111 } else {
2112 while (code.original[c] !== ']') { c += 1; }
2113 c += 1;
2114 }
2115 }
2116
2117 var funcName =
2118 method.computed || isAccessor || !namedFunctions
2119 ? ''
2120 : (methodName + " ");
2121 var rhs =
2122 (isAccessor ? ("." + (method.kind)) : '') +
2123 " = " + (method.value.async ? 'async ' : '') + "function" +
2124 (method.value.generator ? '* ' : ' ') +
2125 funcName;
2126 code.remove(c, method.value.start);
2127 code.prependRight(method.value.start, rhs);
2128 code.appendLeft(method.end, ';');
2129
2130 if (method.value.generator) { code.remove(method.start, method.key.start); }
2131
2132 var start = method.key.start;
2133 if (method.computed && !fake_computed) {
2134 while (code.original[start] != '[') {
2135 --start;
2136 }
2137 }
2138 if (method.start < start) {
2139 code.overwrite(method.start, start, lhs);
2140 } else {
2141 code.prependRight(method.start, lhs);
2142 }
2143 });
2144
2145 if (prototypeGettersAndSetters.length || staticGettersAndSetters.length) {
2146 var intro = [];
2147 var outro = [];
2148
2149 if (prototypeGettersAndSetters.length) {
2150 intro.push(
2151 ("var " + prototypeAccessors + " = { " + (prototypeGettersAndSetters
2152 .map(function (name) { return (name + ": { configurable: true }"); })
2153 .join(',')) + " };")
2154 );
2155 outro.push(
2156 ("Object.defineProperties( " + name + ".prototype, " + prototypeAccessors + " );")
2157 );
2158 }
2159
2160 if (staticGettersAndSetters.length) {
2161 intro.push(
2162 ("var " + staticAccessors + " = { " + (staticGettersAndSetters
2163 .map(function (name) { return (name + ": { configurable: true }"); })
2164 .join(',')) + " };")
2165 );
2166 outro.push(("Object.defineProperties( " + name + ", " + staticAccessors + " );"));
2167 }
2168
2169 if (constructor) { introBlock += "\n\n" + i0; }
2170 introBlock += intro.join(("\n" + i0));
2171 if (!constructor) { introBlock += "\n\n" + i0; }
2172
2173 outroBlock += "\n\n" + i0 + outro.join(("\n" + i0));
2174 }
2175
2176 if (constructor) {
2177 code.appendLeft(constructor.end, introBlock);
2178 } else {
2179 code.prependRight(this.start, introBlock);
2180 }
2181
2182 code.appendLeft(this.end, outroBlock);
2183 }
2184
2185 Node.prototype.transpile.call(this, code, transforms);
2186 };
2187
2188 return ClassBody;
2189}(Node));
2190
2191// TODO this function is slightly flawed – it works on the original string,
2192// not its current edited state.
2193// That's not a problem for the way that it's currently used, but it could
2194// be in future...
2195function deindent(node, code) {
2196 var start = node.start;
2197 var end = node.end;
2198
2199 var indentStr = code.getIndentString();
2200 var indentStrLen = indentStr.length;
2201 var indentStart = start - indentStrLen;
2202
2203 if (
2204 !node.program.indentExclusions[indentStart] &&
2205 code.original.slice(indentStart, start) === indentStr
2206 ) {
2207 code.remove(indentStart, start);
2208 }
2209
2210 var pattern = new RegExp(indentStr + '\\S', 'g');
2211 var slice = code.original.slice(start, end);
2212 var match;
2213
2214 while ((match = pattern.exec(slice))) {
2215 var removeStart = start + match.index;
2216 if (!node.program.indentExclusions[removeStart]) {
2217 code.remove(removeStart, removeStart + indentStrLen);
2218 }
2219 }
2220}
2221
2222var ClassDeclaration = /*@__PURE__*/(function (Node) {
2223 function ClassDeclaration () {
2224 Node.apply(this, arguments);
2225 }
2226
2227 if ( Node ) ClassDeclaration.__proto__ = Node;
2228 ClassDeclaration.prototype = Object.create( Node && Node.prototype );
2229 ClassDeclaration.prototype.constructor = ClassDeclaration;
2230
2231 ClassDeclaration.prototype.initialise = function initialise (transforms) {
2232 if (this.id) {
2233 this.name = this.id.name;
2234 this.findScope(true).addDeclaration(this.id, 'class');
2235 } else {
2236 this.name = this.findScope(true).createIdentifier("defaultExport");
2237 }
2238
2239 Node.prototype.initialise.call(this, transforms);
2240 };
2241
2242 ClassDeclaration.prototype.transpile = function transpile (code, transforms) {
2243 if (transforms.classes) {
2244 if (!this.superClass) { deindent(this.body, code); }
2245
2246 var superName =
2247 this.superClass && (this.superClass.name || 'superclass');
2248
2249 var i0 = this.getIndentation();
2250 var i1 = i0 + code.getIndentString();
2251
2252 // if this is an export default statement, we have to move the export to
2253 // after the declaration, because `export default var Foo = ...` is illegal
2254 var isExportDefaultDeclaration = this.parent.type === 'ExportDefaultDeclaration';
2255
2256 if (isExportDefaultDeclaration) {
2257 code.remove(this.parent.start, this.start);
2258 }
2259
2260 var c = this.start;
2261 if (this.id) {
2262 code.overwrite(c, this.id.start, 'var ');
2263 c = this.id.end;
2264 } else {
2265 code.prependLeft(c, ("var " + (this.name)));
2266 }
2267
2268 if (this.superClass) {
2269 if (this.superClass.end === this.body.start) {
2270 code.remove(c, this.superClass.start);
2271 code.appendLeft(c, (" = /*@__PURE__*/(function (" + superName + ") {\n" + i1));
2272 } else {
2273 code.overwrite(c, this.superClass.start, ' = ');
2274 code.overwrite(
2275 this.superClass.end,
2276 this.body.start,
2277 ("/*@__PURE__*/(function (" + superName + ") {\n" + i1)
2278 );
2279 }
2280 } else {
2281 if (c === this.body.start) {
2282 code.appendLeft(c, ' = ');
2283 } else {
2284 code.overwrite(c, this.body.start, ' = ');
2285 }
2286 }
2287
2288 this.body.transpile(code, transforms, !!this.superClass, superName);
2289
2290 var syntheticDefaultExport =
2291 isExportDefaultDeclaration
2292 ? ("\n\n" + i0 + "export default " + (this.name) + ";")
2293 : '';
2294 if (this.superClass) {
2295 code.appendLeft(this.end, ("\n\n" + i1 + "return " + (this.name) + ";\n" + i0 + "}("));
2296 code.move(this.superClass.start, this.superClass.end, this.end);
2297 code.prependRight(this.end, ("));" + syntheticDefaultExport));
2298 } else if (syntheticDefaultExport) {
2299 code.prependRight(this.end, syntheticDefaultExport);
2300 }
2301 } else {
2302 this.body.transpile(code, transforms, false, null);
2303 }
2304 };
2305
2306 return ClassDeclaration;
2307}(Node));
2308
2309var ClassExpression = /*@__PURE__*/(function (Node) {
2310 function ClassExpression () {
2311 Node.apply(this, arguments);
2312 }
2313
2314 if ( Node ) ClassExpression.__proto__ = Node;
2315 ClassExpression.prototype = Object.create( Node && Node.prototype );
2316 ClassExpression.prototype.constructor = ClassExpression;
2317
2318 ClassExpression.prototype.initialise = function initialise (transforms) {
2319 this.name = (this.id
2320 ? this.id.name
2321 : this.parent.type === 'VariableDeclarator'
2322 ? this.parent.id.name
2323 : this.parent.type !== 'AssignmentExpression'
2324 ? null
2325 : this.parent.left.type === 'Identifier'
2326 ? this.parent.left.name
2327 : this.parent.left.type === 'MemberExpression'
2328 ? this.parent.left.property.name
2329 : null) || this.findScope(true).createIdentifier('anonymous');
2330
2331 Node.prototype.initialise.call(this, transforms);
2332 };
2333
2334 ClassExpression.prototype.transpile = function transpile (code, transforms) {
2335 if (transforms.classes) {
2336 var superName = this.superClass && (this.superClass.name || 'superclass');
2337 if (superName === this.name) {
2338 superName = this.findScope(true).createIdentifier(this.name);
2339 }
2340
2341 var i0 = this.getIndentation();
2342 var i1 = i0 + code.getIndentString();
2343
2344 if (this.superClass) {
2345 code.remove(this.start, this.superClass.start);
2346 code.remove(this.superClass.end, this.body.start);
2347 code.appendRight(this.start, ("/*@__PURE__*/(function (" + superName + ") {\n" + i1));
2348 } else {
2349 code.overwrite(this.start, this.body.start, ("/*@__PURE__*/(function () {\n" + i1));
2350 }
2351
2352 this.body.transpile(code, transforms, true, superName);
2353
2354 var superClass = '';
2355 if (this.superClass) {
2356 superClass = code.slice(this.superClass.start, this.superClass.end);
2357 code.remove(this.superClass.start, this.superClass.end);
2358 }
2359 code.appendLeft(this.end, ("\n\n" + i1 + "return " + (this.name) + ";\n" + i0 + "}(" + superClass + "))"));
2360 } else {
2361 this.body.transpile(code, transforms, false);
2362 }
2363 };
2364
2365 return ClassExpression;
2366}(Node));
2367
2368var ContinueStatement = /*@__PURE__*/(function (Node) {
2369 function ContinueStatement () {
2370 Node.apply(this, arguments);
2371 }
2372
2373 if ( Node ) ContinueStatement.__proto__ = Node;
2374 ContinueStatement.prototype = Object.create( Node && Node.prototype );
2375 ContinueStatement.prototype.constructor = ContinueStatement;
2376
2377 ContinueStatement.prototype.transpile = function transpile (code) {
2378 var loop = this.findNearest(loopStatement);
2379 if (loop.shouldRewriteAsFunction) {
2380 if (this.label)
2381 { throw new CompileError(
2382 'Labels are not currently supported in a loop with locally-scoped variables',
2383 this
2384 ); }
2385 code.overwrite(this.start, this.start + 8, 'return');
2386 }
2387 };
2388
2389 return ContinueStatement;
2390}(Node));
2391
2392var ExportDefaultDeclaration = /*@__PURE__*/(function (Node) {
2393 function ExportDefaultDeclaration () {
2394 Node.apply(this, arguments);
2395 }
2396
2397 if ( Node ) ExportDefaultDeclaration.__proto__ = Node;
2398 ExportDefaultDeclaration.prototype = Object.create( Node && Node.prototype );
2399 ExportDefaultDeclaration.prototype.constructor = ExportDefaultDeclaration;
2400
2401 ExportDefaultDeclaration.prototype.initialise = function initialise (transforms) {
2402 if (transforms.moduleExport)
2403 { CompileError.missingTransform("export", "moduleExport", this); }
2404 Node.prototype.initialise.call(this, transforms);
2405 };
2406
2407 return ExportDefaultDeclaration;
2408}(Node));
2409
2410var ExportNamedDeclaration = /*@__PURE__*/(function (Node) {
2411 function ExportNamedDeclaration () {
2412 Node.apply(this, arguments);
2413 }
2414
2415 if ( Node ) ExportNamedDeclaration.__proto__ = Node;
2416 ExportNamedDeclaration.prototype = Object.create( Node && Node.prototype );
2417 ExportNamedDeclaration.prototype.constructor = ExportNamedDeclaration;
2418
2419 ExportNamedDeclaration.prototype.initialise = function initialise (transforms) {
2420 if (transforms.moduleExport)
2421 { CompileError.missingTransform("export", "moduleExport", this); }
2422 Node.prototype.initialise.call(this, transforms);
2423 };
2424
2425 return ExportNamedDeclaration;
2426}(Node));
2427
2428var LoopStatement = /*@__PURE__*/(function (Node) {
2429 function LoopStatement () {
2430 Node.apply(this, arguments);
2431 }
2432
2433 if ( Node ) LoopStatement.__proto__ = Node;
2434 LoopStatement.prototype = Object.create( Node && Node.prototype );
2435 LoopStatement.prototype.constructor = LoopStatement;
2436
2437 LoopStatement.prototype.findScope = function findScope (functionScope) {
2438 return functionScope || !this.createdScope
2439 ? this.parent.findScope(functionScope)
2440 : this.body.scope;
2441 };
2442
2443 LoopStatement.prototype.initialise = function initialise (transforms) {
2444 this.body.createScope();
2445 this.createdScope = true;
2446
2447 // this is populated as and when reassignments occur
2448 this.reassigned = Object.create(null);
2449 this.aliases = Object.create(null);
2450
2451 this.thisRefs = [];
2452
2453 Node.prototype.initialise.call(this, transforms);
2454 if (this.scope) {
2455 this.scope.consolidate();
2456 }
2457
2458 var declarations = Object.assign({}, this.body.scope.declarations);
2459 if (this.scope) {
2460 Object.assign(declarations, this.scope.declarations);
2461 }
2462
2463 if (transforms.letConst) {
2464 // see if any block-scoped declarations are referenced
2465 // inside function expressions
2466 var names = Object.keys(declarations);
2467
2468 var i = names.length;
2469 while (i--) {
2470 var name = names[i];
2471 var declaration = declarations[name];
2472
2473 var j = declaration.instances.length;
2474 while (j--) {
2475 var instance = declaration.instances[j];
2476 var nearestFunctionExpression = instance.findNearest(/Function/);
2477
2478 if (
2479 nearestFunctionExpression &&
2480 nearestFunctionExpression.depth > this.depth
2481 ) {
2482 this.shouldRewriteAsFunction = true;
2483 for (var i$1 = 0, list = this.thisRefs; i$1 < list.length; i$1 += 1) {
2484 var node = list[i$1];
2485
2486 node.alias = node.alias || node.findLexicalBoundary().getThisAlias();
2487 }
2488 break;
2489 }
2490 }
2491
2492 if (this.shouldRewriteAsFunction) { break; }
2493 }
2494 }
2495 };
2496
2497 LoopStatement.prototype.transpile = function transpile (code, transforms) {
2498 var needsBlock =
2499 this.type != 'ForOfStatement' &&
2500 (this.body.type !== 'BlockStatement' ||
2501 (this.body.type === 'BlockStatement' && this.body.synthetic));
2502
2503 if (this.shouldRewriteAsFunction) {
2504 var i0 = this.getIndentation();
2505 var i1 = i0 + code.getIndentString();
2506
2507 var argString = this.args ? (" " + (this.args.join(', ')) + " ") : '';
2508 var paramString = this.params ? (" " + (this.params.join(', ')) + " ") : '';
2509
2510 var functionScope = this.findScope(true);
2511 var loop = functionScope.createIdentifier('loop');
2512
2513 var before =
2514 "var " + loop + " = function (" + paramString + ") " +
2515 (this.body.synthetic ? ("{\n" + i0 + (code.getIndentString())) : '');
2516 var after = (this.body.synthetic ? ("\n" + i0 + "}") : '') + ";\n\n" + i0;
2517
2518 code.prependRight(this.body.start, before);
2519 code.appendLeft(this.body.end, after);
2520 code.move(this.start, this.body.start, this.body.end);
2521
2522 if (this.canBreak || this.canReturn) {
2523 var returned = functionScope.createIdentifier('returned');
2524
2525 var insert = "{\n" + i1 + "var " + returned + " = " + loop + "(" + argString + ");\n";
2526 if (this.canBreak)
2527 { insert += "\n" + i1 + "if ( " + returned + " === 'break' ) break;"; }
2528 if (this.canReturn)
2529 { insert += "\n" + i1 + "if ( " + returned + " ) return " + returned + ".v;"; }
2530 insert += "\n" + i0 + "}";
2531
2532 code.prependRight(this.body.end, insert);
2533 } else {
2534 var callExpression = loop + "(" + argString + ");";
2535
2536 if (this.type === 'DoWhileStatement') {
2537 code.overwrite(
2538 this.start,
2539 this.body.start,
2540 ("do {\n" + i1 + callExpression + "\n" + i0 + "}")
2541 );
2542 } else {
2543 code.prependRight(this.body.end, callExpression);
2544 }
2545 }
2546 } else if (needsBlock) {
2547 code.appendLeft(this.body.start, '{ ');
2548 code.prependRight(this.body.end, ' }');
2549 }
2550
2551 Node.prototype.transpile.call(this, code, transforms);
2552 };
2553
2554 return LoopStatement;
2555}(Node));
2556
2557var ForStatement = /*@__PURE__*/(function (LoopStatement) {
2558 function ForStatement () {
2559 LoopStatement.apply(this, arguments);
2560 }
2561
2562 if ( LoopStatement ) ForStatement.__proto__ = LoopStatement;
2563 ForStatement.prototype = Object.create( LoopStatement && LoopStatement.prototype );
2564 ForStatement.prototype.constructor = ForStatement;
2565
2566 ForStatement.prototype.initialise = function initialise (transforms) {
2567 var this$1 = this;
2568
2569 this.createdDeclarations = [];
2570
2571 this.scope = new Scope({
2572 block: true,
2573 parent: this.parent.findScope(false),
2574 declare: function (id) { return this$1.createdDeclarations.push(id); }
2575 });
2576
2577 LoopStatement.prototype.initialise.call(this, transforms);
2578 };
2579
2580 ForStatement.prototype.findScope = function findScope (functionScope) {
2581 return functionScope
2582 ? this.parent.findScope(functionScope)
2583 : this.scope;
2584 };
2585
2586 ForStatement.prototype.transpile = function transpile (code, transforms) {
2587 var this$1 = this;
2588
2589 var i1 = this.getIndentation() + code.getIndentString();
2590
2591 if (this.shouldRewriteAsFunction) {
2592 // which variables are declared in the init statement?
2593 var names = this.init && this.init.type === 'VariableDeclaration'
2594 ? this.init.declarations.map(function (declarator) { return extractNames(declarator.id); })
2595 : [];
2596
2597 var aliases = this.aliases;
2598
2599 this.args = names.map(
2600 function (name) { return (name in this$1.aliases ? this$1.aliases[name].outer : name); }
2601 );
2602 this.params = names.map(
2603 function (name) { return (name in this$1.aliases ? this$1.aliases[name].inner : name); }
2604 );
2605
2606 var updates = Object.keys(this.reassigned).map(
2607 function (name) { return ((aliases[name].outer) + " = " + (aliases[name].inner) + ";"); }
2608 );
2609
2610 if (updates.length) {
2611 if (this.body.synthetic) {
2612 code.appendLeft(this.body.body[0].end, ("; " + (updates.join(" "))));
2613 } else {
2614 var lastStatement = this.body.body[this.body.body.length - 1];
2615 code.appendLeft(
2616 lastStatement.end,
2617 ("\n\n" + i1 + (updates.join(("\n" + i1))))
2618 );
2619 }
2620 }
2621 }
2622
2623 LoopStatement.prototype.transpile.call(this, code, transforms);
2624 };
2625
2626 return ForStatement;
2627}(LoopStatement));
2628
2629var ForInStatement = /*@__PURE__*/(function (LoopStatement) {
2630 function ForInStatement () {
2631 LoopStatement.apply(this, arguments);
2632 }
2633
2634 if ( LoopStatement ) ForInStatement.__proto__ = LoopStatement;
2635 ForInStatement.prototype = Object.create( LoopStatement && LoopStatement.prototype );
2636 ForInStatement.prototype.constructor = ForInStatement;
2637
2638 ForInStatement.prototype.initialise = function initialise (transforms) {
2639 var this$1 = this;
2640
2641 this.createdDeclarations = [];
2642
2643 this.scope = new Scope({
2644 block: true,
2645 parent: this.parent.findScope(false),
2646 declare: function (id) { return this$1.createdDeclarations.push(id); }
2647 });
2648
2649 LoopStatement.prototype.initialise.call(this, transforms);
2650 };
2651
2652 ForInStatement.prototype.findScope = function findScope (functionScope) {
2653 return functionScope
2654 ? this.parent.findScope(functionScope)
2655 : this.scope;
2656 };
2657
2658 ForInStatement.prototype.transpile = function transpile (code, transforms) {
2659 var this$1 = this;
2660
2661 var hasDeclaration = this.left.type === 'VariableDeclaration';
2662
2663 if (this.shouldRewriteAsFunction) {
2664 // which variables are declared in the init statement?
2665 var names = hasDeclaration
2666 ? this.left.declarations.map(function (declarator) { return extractNames(declarator.id); })
2667 : [];
2668
2669 this.args = names.map(
2670 function (name) { return (name in this$1.aliases ? this$1.aliases[name].outer : name); }
2671 );
2672 this.params = names.map(
2673 function (name) { return (name in this$1.aliases ? this$1.aliases[name].inner : name); }
2674 );
2675 }
2676
2677 LoopStatement.prototype.transpile.call(this, code, transforms);
2678
2679 var maybePattern = hasDeclaration ? this.left.declarations[0].id : this.left;
2680 if (maybePattern.type !== 'Identifier' && maybePattern.type !== 'MemberExpression') {
2681 this.destructurePattern(code, maybePattern, hasDeclaration);
2682 }
2683 };
2684
2685 ForInStatement.prototype.destructurePattern = function destructurePattern (code, pattern, isDeclaration) {
2686 var scope = this.findScope(true);
2687 var i0 = this.getIndentation();
2688 var i1 = i0 + code.getIndentString();
2689
2690 var ref = scope.createIdentifier('ref');
2691
2692 var bodyStart = this.body.body.length ? this.body.body[0].start : this.body.start + 1;
2693
2694 code.move(pattern.start, pattern.end, bodyStart);
2695
2696 code.prependRight(pattern.end, isDeclaration ? ref : ("var " + ref));
2697
2698 var statementGenerators = [];
2699 destructure(
2700 code,
2701 function (id) { return scope.createIdentifier(id); },
2702 function (ref) {
2703 var name = ref.name;
2704
2705 return scope.resolveName(name);
2706 },
2707 pattern,
2708 ref,
2709 false,
2710 statementGenerators
2711 );
2712
2713 var suffix = ";\n" + i1;
2714 statementGenerators.forEach(function (fn, i) {
2715 if (i === statementGenerators.length - 1) {
2716 suffix = ";\n\n" + i1;
2717 }
2718
2719 fn(bodyStart, '', suffix);
2720 });
2721 };
2722
2723 return ForInStatement;
2724}(LoopStatement));
2725
2726var ForOfStatement = /*@__PURE__*/(function (LoopStatement) {
2727 function ForOfStatement () {
2728 LoopStatement.apply(this, arguments);
2729 }
2730
2731 if ( LoopStatement ) ForOfStatement.__proto__ = LoopStatement;
2732 ForOfStatement.prototype = Object.create( LoopStatement && LoopStatement.prototype );
2733 ForOfStatement.prototype.constructor = ForOfStatement;
2734
2735 ForOfStatement.prototype.initialise = function initialise (transforms) {
2736 var this$1 = this;
2737
2738 if (transforms.forOf && !transforms.dangerousForOf)
2739 { CompileError.missingTransform("for-of statements", "forOf", this, "dangerousForOf"); }
2740 if (this.await && transforms.asyncAwait)
2741 { CompileError.missingTransform("for-await-of statements", "asyncAwait", this); }
2742
2743 this.createdDeclarations = [];
2744
2745 this.scope = new Scope({
2746 block: true,
2747 parent: this.parent.findScope(false),
2748 declare: function (id) { return this$1.createdDeclarations.push(id); }
2749 });
2750
2751 LoopStatement.prototype.initialise.call(this, transforms);
2752 };
2753
2754 ForOfStatement.prototype.findScope = function findScope (functionScope) {
2755 return functionScope
2756 ? this.parent.findScope(functionScope)
2757 : this.scope;
2758 };
2759
2760 ForOfStatement.prototype.transpile = function transpile (code, transforms) {
2761 LoopStatement.prototype.transpile.call(this, code, transforms);
2762 if (!transforms.dangerousForOf) { return; }
2763
2764 // edge case (#80)
2765 if (!this.body.body[0]) {
2766 if (
2767 this.left.type === 'VariableDeclaration' &&
2768 this.left.kind === 'var'
2769 ) {
2770 code.remove(this.start, this.left.start);
2771 code.appendLeft(this.left.end, ';');
2772 code.remove(this.left.end, this.end);
2773 } else {
2774 code.remove(this.start, this.end);
2775 }
2776
2777 return;
2778 }
2779
2780 var scope = this.findScope(true);
2781 var i0 = this.getIndentation();
2782 var i1 = i0 + code.getIndentString();
2783
2784 var key = scope.createIdentifier('i');
2785 var list = scope.createIdentifier('list');
2786
2787 if (this.body.synthetic) {
2788 code.prependRight(this.left.start, ("{\n" + i1));
2789 code.appendLeft(this.body.body[0].end, ("\n" + i0 + "}"));
2790 }
2791
2792 var bodyStart = this.body.body[0].start;
2793
2794 code.remove(this.left.end, this.right.start);
2795 code.move(this.left.start, this.left.end, bodyStart);
2796
2797 code.prependRight(this.right.start, ("var " + key + " = 0, " + list + " = "));
2798 code.appendLeft(this.right.end, ("; " + key + " < " + list + ".length; " + key + " += 1"));
2799
2800 var isDeclaration = this.left.type === 'VariableDeclaration';
2801 var maybeDestructuring = isDeclaration ? this.left.declarations[0].id : this.left;
2802 if (maybeDestructuring.type !== 'Identifier') {
2803 var statementGenerators = [];
2804 var ref = scope.createIdentifier('ref');
2805 destructure(
2806 code,
2807 function (id) { return scope.createIdentifier(id); },
2808 function (ref) {
2809 var name = ref.name;
2810
2811 return scope.resolveName(name);
2812 },
2813 maybeDestructuring,
2814 ref,
2815 !isDeclaration,
2816 statementGenerators
2817 );
2818
2819 var suffix = ";\n" + i1;
2820 statementGenerators.forEach(function (fn, i) {
2821 if (i === statementGenerators.length - 1) {
2822 suffix = ";\n\n" + i1;
2823 }
2824
2825 fn(bodyStart, '', suffix);
2826 });
2827
2828 if (isDeclaration) {
2829 code.appendLeft(this.left.start + this.left.kind.length + 1, ref);
2830 code.appendLeft(this.left.end, (" = " + list + "[" + key + "];\n" + i1));
2831 } else {
2832 code.appendLeft(this.left.end, ("var " + ref + " = " + list + "[" + key + "];\n" + i1));
2833 }
2834 } else {
2835 code.appendLeft(this.left.end, (" = " + list + "[" + key + "];\n\n" + i1));
2836 }
2837 };
2838
2839 return ForOfStatement;
2840}(LoopStatement));
2841
2842var FunctionDeclaration = /*@__PURE__*/(function (Node) {
2843 function FunctionDeclaration () {
2844 Node.apply(this, arguments);
2845 }
2846
2847 if ( Node ) FunctionDeclaration.__proto__ = Node;
2848 FunctionDeclaration.prototype = Object.create( Node && Node.prototype );
2849 FunctionDeclaration.prototype.constructor = FunctionDeclaration;
2850
2851 FunctionDeclaration.prototype.initialise = function initialise (transforms) {
2852 if (this.generator && transforms.generator) {
2853 CompileError.missingTransform("generators", "generator", this);
2854 }
2855 if (this.async && transforms.asyncAwait) {
2856 CompileError.missingTransform("async functions", "asyncAwait", this);
2857 }
2858
2859 this.body.createScope();
2860
2861 if (this.id) {
2862 this.findScope(true).addDeclaration(this.id, 'function');
2863 }
2864 Node.prototype.initialise.call(this, transforms);
2865 };
2866
2867 FunctionDeclaration.prototype.transpile = function transpile (code, transforms) {
2868 Node.prototype.transpile.call(this, code, transforms);
2869 if (transforms.trailingFunctionCommas && this.params.length) {
2870 removeTrailingComma(code, this.params[this.params.length - 1].end);
2871 }
2872 };
2873
2874 return FunctionDeclaration;
2875}(Node));
2876
2877var FunctionExpression = /*@__PURE__*/(function (Node) {
2878 function FunctionExpression () {
2879 Node.apply(this, arguments);
2880 }
2881
2882 if ( Node ) FunctionExpression.__proto__ = Node;
2883 FunctionExpression.prototype = Object.create( Node && Node.prototype );
2884 FunctionExpression.prototype.constructor = FunctionExpression;
2885
2886 FunctionExpression.prototype.initialise = function initialise (transforms) {
2887 if (this.generator && transforms.generator) {
2888 CompileError.missingTransform("generators", "generator", this);
2889 }
2890 if (this.async && transforms.asyncAwait) {
2891 CompileError.missingTransform("async functions", "asyncAwait", this);
2892 }
2893
2894 this.body.createScope();
2895
2896 if (this.id) {
2897 // function expression IDs belong to the child scope...
2898 this.body.scope.addDeclaration(this.id, 'function');
2899 }
2900
2901 Node.prototype.initialise.call(this, transforms);
2902
2903 var parent = this.parent;
2904 var methodName;
2905
2906 if (
2907 transforms.conciseMethodProperty &&
2908 parent.type === 'Property' &&
2909 parent.kind === 'init' &&
2910 parent.method &&
2911 parent.key.type === 'Identifier'
2912 ) {
2913 // object literal concise method
2914 methodName = parent.key.name;
2915 } else if (
2916 transforms.classes &&
2917 parent.type === 'MethodDefinition' &&
2918 parent.kind === 'method' &&
2919 parent.key.type === 'Identifier'
2920 ) {
2921 // method definition in a class
2922 methodName = parent.key.name;
2923 } else if (this.id && this.id.type === 'Identifier') {
2924 // naked function expression
2925 methodName = this.id.alias || this.id.name;
2926 }
2927
2928 if (methodName) {
2929 for (var i$1 = 0, list$1 = this.params; i$1 < list$1.length; i$1 += 1) {
2930 var param = list$1[i$1];
2931
2932 if (param.type === 'Identifier' && methodName === param.name) {
2933 // workaround for Safari 9/WebKit bug:
2934 // https://gitlab.com/Rich-Harris/buble/issues/154
2935 // change parameter name when same as method name
2936
2937 var scope = this.body.scope;
2938 var declaration = scope.declarations[methodName];
2939
2940 var alias = scope.createIdentifier(methodName);
2941 param.alias = alias;
2942
2943 for (var i = 0, list = declaration.instances; i < list.length; i += 1) {
2944 var identifier = list[i];
2945
2946 identifier.alias = alias;
2947 }
2948
2949 break;
2950 }
2951 }
2952 }
2953 };
2954
2955 FunctionExpression.prototype.transpile = function transpile (code, transforms) {
2956 Node.prototype.transpile.call(this, code, transforms);
2957 if (transforms.trailingFunctionCommas && this.params.length) {
2958 removeTrailingComma(code, this.params[this.params.length - 1].end);
2959 }
2960 };
2961
2962 return FunctionExpression;
2963}(Node));
2964
2965function isReference(node, parent) {
2966 if (node.type === 'MemberExpression') {
2967 return !node.computed && isReference(node.object, node);
2968 }
2969
2970 if (node.type === 'Identifier') {
2971 // the only time we could have an identifier node without a parent is
2972 // if it's the entire body of a function without a block statement –
2973 // i.e. an arrow function expression like `a => a`
2974 if (!parent) { return true; }
2975
2976 if (/(Function|Class)Expression/.test(parent.type)) { return false; }
2977
2978 if (parent.type === 'VariableDeclarator') { return node === parent.init; }
2979
2980 // TODO is this right?
2981 if (
2982 parent.type === 'MemberExpression' ||
2983 parent.type === 'MethodDefinition'
2984 ) {
2985 return parent.computed || node === parent.object;
2986 }
2987
2988 if (parent.type === 'ArrayPattern') { return false; }
2989
2990 // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
2991 if (parent.type === 'Property') {
2992 if (parent.parent.type === 'ObjectPattern') { return false; }
2993 return parent.computed || node === parent.value;
2994 }
2995
2996 // disregard the `bar` in `class Foo { bar () {...} }`
2997 if (parent.type === 'MethodDefinition') { return false; }
2998
2999 // disregard the `bar` in `export { foo as bar }`
3000 if (parent.type === 'ExportSpecifier' && node !== parent.local)
3001 { return false; }
3002
3003 return true;
3004 }
3005}
3006
3007var Identifier = /*@__PURE__*/(function (Node) {
3008 function Identifier () {
3009 Node.apply(this, arguments);
3010 }
3011
3012 if ( Node ) Identifier.__proto__ = Node;
3013 Identifier.prototype = Object.create( Node && Node.prototype );
3014 Identifier.prototype.constructor = Identifier;
3015
3016 Identifier.prototype.findScope = function findScope (functionScope) {
3017 if (this.parent.params && ~this.parent.params.indexOf(this)) {
3018 return this.parent.body.scope;
3019 }
3020
3021 if (this.parent.type === 'FunctionExpression' && this === this.parent.id) {
3022 return this.parent.body.scope;
3023 }
3024
3025 return this.parent.findScope(functionScope);
3026 };
3027
3028 Identifier.prototype.initialise = function initialise (transforms) {
3029 if (this.isLabel()) {
3030 return;
3031 }
3032
3033 if (isReference(this, this.parent)) {
3034 if (
3035 transforms.arrow &&
3036 this.name === 'arguments' &&
3037 !this.findScope(false).contains(this.name)
3038 ) {
3039 var lexicalBoundary = this.findLexicalBoundary();
3040 var arrowFunction = this.findNearest('ArrowFunctionExpression');
3041 var loop = this.findNearest(loopStatement);
3042
3043 if (arrowFunction && arrowFunction.depth > lexicalBoundary.depth) {
3044 this.alias = lexicalBoundary.getArgumentsAlias();
3045 }
3046
3047 if (
3048 loop &&
3049 loop.body.contains(this) &&
3050 loop.depth > lexicalBoundary.depth
3051 ) {
3052 this.alias = lexicalBoundary.getArgumentsAlias();
3053 }
3054 }
3055
3056 this.findScope(false).addReference(this);
3057 }
3058 };
3059
3060 Identifier.prototype.isLabel = function isLabel () {
3061 switch (this.parent.type) {
3062 case 'BreakStatement': return true;
3063 case 'ContinueStatement': return true;
3064 case 'LabeledStatement': return true;
3065 default: return false;
3066 }
3067 };
3068
3069 Identifier.prototype.transpile = function transpile (code) {
3070 if (this.alias) {
3071 code.overwrite(this.start, this.end, this.alias, {
3072 storeName: true,
3073 contentOnly: true
3074 });
3075 }
3076 };
3077
3078 return Identifier;
3079}(Node));
3080
3081var IfStatement = /*@__PURE__*/(function (Node) {
3082 function IfStatement () {
3083 Node.apply(this, arguments);
3084 }
3085
3086 if ( Node ) IfStatement.__proto__ = Node;
3087 IfStatement.prototype = Object.create( Node && Node.prototype );
3088 IfStatement.prototype.constructor = IfStatement;
3089
3090 IfStatement.prototype.initialise = function initialise (transforms) {
3091 Node.prototype.initialise.call(this, transforms);
3092 };
3093
3094 IfStatement.prototype.transpile = function transpile (code, transforms) {
3095 if (
3096 this.consequent.type !== 'BlockStatement' ||
3097 (this.consequent.type === 'BlockStatement' && this.consequent.synthetic)
3098 ) {
3099 code.appendLeft(this.consequent.start, '{ ');
3100 code.prependRight(this.consequent.end, ' }');
3101 }
3102
3103 if (
3104 this.alternate &&
3105 this.alternate.type !== 'IfStatement' &&
3106 (this.alternate.type !== 'BlockStatement' ||
3107 (this.alternate.type === 'BlockStatement' && this.alternate.synthetic))
3108 ) {
3109 code.appendLeft(this.alternate.start, '{ ');
3110 code.prependRight(this.alternate.end, ' }');
3111 }
3112
3113 Node.prototype.transpile.call(this, code, transforms);
3114 };
3115
3116 return IfStatement;
3117}(Node));
3118
3119var Import = /*@__PURE__*/(function (Node) {
3120 function Import () {
3121 Node.apply(this, arguments);
3122 }
3123
3124 if ( Node ) Import.__proto__ = Node;
3125 Import.prototype = Object.create( Node && Node.prototype );
3126 Import.prototype.constructor = Import;
3127
3128 Import.prototype.initialise = function initialise (transforms) {
3129 if (transforms.moduleImport) {
3130 CompileError.missingTransform("dynamic import expressions", "moduleImport", this);
3131 }
3132 Node.prototype.initialise.call(this, transforms);
3133 };
3134
3135 return Import;
3136}(Node));
3137
3138var ImportDeclaration = /*@__PURE__*/(function (Node) {
3139 function ImportDeclaration () {
3140 Node.apply(this, arguments);
3141 }
3142
3143 if ( Node ) ImportDeclaration.__proto__ = Node;
3144 ImportDeclaration.prototype = Object.create( Node && Node.prototype );
3145 ImportDeclaration.prototype.constructor = ImportDeclaration;
3146
3147 ImportDeclaration.prototype.initialise = function initialise (transforms) {
3148 if (transforms.moduleImport)
3149 { CompileError.missingTransform("import", "moduleImport", this); }
3150 Node.prototype.initialise.call(this, transforms);
3151 };
3152
3153 return ImportDeclaration;
3154}(Node));
3155
3156var ImportDefaultSpecifier = /*@__PURE__*/(function (Node) {
3157 function ImportDefaultSpecifier () {
3158 Node.apply(this, arguments);
3159 }
3160
3161 if ( Node ) ImportDefaultSpecifier.__proto__ = Node;
3162 ImportDefaultSpecifier.prototype = Object.create( Node && Node.prototype );
3163 ImportDefaultSpecifier.prototype.constructor = ImportDefaultSpecifier;
3164
3165 ImportDefaultSpecifier.prototype.initialise = function initialise (transforms) {
3166 this.findScope(true).addDeclaration(this.local, 'import');
3167 Node.prototype.initialise.call(this, transforms);
3168 };
3169
3170 return ImportDefaultSpecifier;
3171}(Node));
3172
3173var ImportSpecifier = /*@__PURE__*/(function (Node) {
3174 function ImportSpecifier () {
3175 Node.apply(this, arguments);
3176 }
3177
3178 if ( Node ) ImportSpecifier.__proto__ = Node;
3179 ImportSpecifier.prototype = Object.create( Node && Node.prototype );
3180 ImportSpecifier.prototype.constructor = ImportSpecifier;
3181
3182 ImportSpecifier.prototype.initialise = function initialise (transforms) {
3183 this.findScope(true).addDeclaration(this.local, 'import');
3184 Node.prototype.initialise.call(this, transforms);
3185 };
3186
3187 return ImportSpecifier;
3188}(Node));
3189
3190var hasDashes = function (val) { return /-/.test(val); };
3191
3192var formatKey = function (key) { return (hasDashes(key) ? ("'" + key + "'") : key); };
3193
3194var formatVal = function (val) { return (val ? '' : 'true'); };
3195
3196var JSXAttribute = /*@__PURE__*/(function (Node) {
3197 function JSXAttribute () {
3198 Node.apply(this, arguments);
3199 }
3200
3201 if ( Node ) JSXAttribute.__proto__ = Node;
3202 JSXAttribute.prototype = Object.create( Node && Node.prototype );
3203 JSXAttribute.prototype.constructor = JSXAttribute;
3204
3205 JSXAttribute.prototype.transpile = function transpile (code, transforms) {
3206 var ref = this.name;
3207 var start = ref.start;
3208 var name = ref.name;
3209
3210 // Overwrite equals sign if value is present.
3211 var end = this.value ? this.value.start : this.name.end;
3212
3213 code.overwrite(start, end, ((formatKey(name)) + ": " + (formatVal(this.value))));
3214
3215 Node.prototype.transpile.call(this, code, transforms);
3216 };
3217
3218 return JSXAttribute;
3219}(Node));
3220
3221function containsNewLine(node) {
3222 return (
3223 node.type === 'JSXText' && !/\S/.test(node.value) && /\n/.test(node.value)
3224 );
3225}
3226
3227var JSXClosingElement = /*@__PURE__*/(function (Node) {
3228 function JSXClosingElement () {
3229 Node.apply(this, arguments);
3230 }
3231
3232 if ( Node ) JSXClosingElement.__proto__ = Node;
3233 JSXClosingElement.prototype = Object.create( Node && Node.prototype );
3234 JSXClosingElement.prototype.constructor = JSXClosingElement;
3235
3236 JSXClosingElement.prototype.transpile = function transpile (code) {
3237 var spaceBeforeParen = true;
3238
3239 var lastChild = this.parent.children[this.parent.children.length - 1];
3240
3241 // omit space before closing paren if
3242 // a) this is on a separate line, or
3243 // b) there are no children but there are attributes
3244 if (
3245 (lastChild && containsNewLine(lastChild)) ||
3246 this.parent.openingElement.attributes.length
3247 ) {
3248 spaceBeforeParen = false;
3249 }
3250
3251 code.overwrite(this.start, this.end, spaceBeforeParen ? ' )' : ')');
3252 };
3253
3254 return JSXClosingElement;
3255}(Node));
3256
3257function containsNewLine$1(node) {
3258 return (
3259 node.type === 'JSXText' && !/\S/.test(node.value) && /\n/.test(node.value)
3260 );
3261}
3262
3263var JSXClosingFragment = /*@__PURE__*/(function (Node) {
3264 function JSXClosingFragment () {
3265 Node.apply(this, arguments);
3266 }
3267
3268 if ( Node ) JSXClosingFragment.__proto__ = Node;
3269 JSXClosingFragment.prototype = Object.create( Node && Node.prototype );
3270 JSXClosingFragment.prototype.constructor = JSXClosingFragment;
3271
3272 JSXClosingFragment.prototype.transpile = function transpile (code) {
3273 var spaceBeforeParen = true;
3274
3275 var lastChild = this.parent.children[this.parent.children.length - 1];
3276
3277 // omit space before closing paren if this is on a separate line
3278 if (lastChild && containsNewLine$1(lastChild)) {
3279 spaceBeforeParen = false;
3280 }
3281
3282 code.overwrite(this.start, this.end, spaceBeforeParen ? ' )' : ')');
3283 };
3284
3285 return JSXClosingFragment;
3286}(Node));
3287
3288function normalise(str, removeTrailingWhitespace) {
3289
3290 if (removeTrailingWhitespace && /\n/.test(str)) {
3291 str = str.replace(/[ \f\n\r\t\v]+$/, '');
3292 }
3293
3294 str = str
3295 .replace(/^\n\r?[ \f\n\r\t\v]+/, '') // remove leading newline + space
3296 .replace(/[ \f\n\r\t\v]*\n\r?[ \f\n\r\t\v]*/gm, ' '); // replace newlines with spaces
3297
3298 // TODO prefer single quotes?
3299 return JSON.stringify(str);
3300}
3301
3302var JSXElement = /*@__PURE__*/(function (Node) {
3303 function JSXElement () {
3304 Node.apply(this, arguments);
3305 }
3306
3307 if ( Node ) JSXElement.__proto__ = Node;
3308 JSXElement.prototype = Object.create( Node && Node.prototype );
3309 JSXElement.prototype.constructor = JSXElement;
3310
3311 JSXElement.prototype.transpile = function transpile (code, transforms) {
3312 Node.prototype.transpile.call(this, code, transforms);
3313
3314 var children = this.children.filter(function (child) {
3315 if (child.type !== 'JSXText') { return true; }
3316
3317 // remove whitespace-only literals, unless on a single line
3318 return /[^ \f\n\r\t\v]/.test(child.raw) || !/\n/.test(child.raw);
3319 });
3320
3321 if (children.length) {
3322 var c = (this.openingElement || this.openingFragment).end;
3323
3324 var i;
3325 for (i = 0; i < children.length; i += 1) {
3326 var child = children[i];
3327
3328 if (
3329 child.type === 'JSXExpressionContainer' &&
3330 child.expression.type === 'JSXEmptyExpression'
3331 ) ; else {
3332 var tail =
3333 code.original[c] === '\n' && child.type !== 'JSXText' ? '' : ' ';
3334 code.appendLeft(c, ("," + tail));
3335 }
3336
3337 if (child.type === 'JSXText') {
3338 var str = normalise(child.value, i === children.length - 1);
3339 code.overwrite(child.start, child.end, str);
3340 }
3341
3342 c = child.end;
3343 }
3344 }
3345 };
3346
3347 return JSXElement;
3348}(Node));
3349
3350var JSXExpressionContainer = /*@__PURE__*/(function (Node) {
3351 function JSXExpressionContainer () {
3352 Node.apply(this, arguments);
3353 }
3354
3355 if ( Node ) JSXExpressionContainer.__proto__ = Node;
3356 JSXExpressionContainer.prototype = Object.create( Node && Node.prototype );
3357 JSXExpressionContainer.prototype.constructor = JSXExpressionContainer;
3358
3359 JSXExpressionContainer.prototype.transpile = function transpile (code, transforms) {
3360 code.remove(this.start, this.expression.start);
3361 code.remove(this.expression.end, this.end);
3362
3363 Node.prototype.transpile.call(this, code, transforms);
3364 };
3365
3366 return JSXExpressionContainer;
3367}(Node));
3368
3369var JSXFragment = /*@__PURE__*/(function (JSXElement) {
3370 function JSXFragment () {
3371 JSXElement.apply(this, arguments);
3372 }if ( JSXElement ) JSXFragment.__proto__ = JSXElement;
3373 JSXFragment.prototype = Object.create( JSXElement && JSXElement.prototype );
3374 JSXFragment.prototype.constructor = JSXFragment;
3375
3376
3377
3378 return JSXFragment;
3379}(JSXElement));
3380
3381var JSXOpeningElement = /*@__PURE__*/(function (Node) {
3382 function JSXOpeningElement () {
3383 Node.apply(this, arguments);
3384 }
3385
3386 if ( Node ) JSXOpeningElement.__proto__ = Node;
3387 JSXOpeningElement.prototype = Object.create( Node && Node.prototype );
3388 JSXOpeningElement.prototype.constructor = JSXOpeningElement;
3389
3390 JSXOpeningElement.prototype.transpile = function transpile (code, transforms) {
3391 Node.prototype.transpile.call(this, code, transforms);
3392
3393 code.overwrite(this.start, this.name.start, ((this.program.jsx) + "( "));
3394
3395 var html =
3396 this.name.type === 'JSXIdentifier' &&
3397 this.name.name[0] === this.name.name[0].toLowerCase();
3398 if (html) { code.prependRight(this.name.start, "'"); }
3399
3400 var len = this.attributes.length;
3401 var c = this.name.end;
3402
3403 if (len) {
3404 var i;
3405
3406 var hasSpread = false;
3407 for (i = 0; i < len; i += 1) {
3408 if (this.attributes[i].type === 'JSXSpreadAttribute') {
3409 hasSpread = true;
3410 break;
3411 }
3412 }
3413
3414 c = this.attributes[0].end;
3415
3416 for (i = 0; i < len; i += 1) {
3417 var attr = this.attributes[i];
3418
3419 if (i > 0) {
3420 if (attr.start === c) { code.prependRight(c, ', '); }
3421 else { code.overwrite(c, attr.start, ', '); }
3422 }
3423
3424 if (hasSpread && attr.type !== 'JSXSpreadAttribute') {
3425 var lastAttr = this.attributes[i - 1];
3426 var nextAttr = this.attributes[i + 1];
3427
3428 if (!lastAttr || lastAttr.type === 'JSXSpreadAttribute') {
3429 code.prependRight(attr.start, '{ ');
3430 }
3431
3432 if (!nextAttr || nextAttr.type === 'JSXSpreadAttribute') {
3433 code.appendLeft(attr.end, ' }');
3434 }
3435 }
3436
3437 c = attr.end;
3438 }
3439
3440 var after;
3441 var before;
3442 if (hasSpread) {
3443 if (len === 1) {
3444 before = html ? "'," : ',';
3445 } else {
3446 if (!this.program.options.objectAssign) {
3447 throw new CompileError(
3448 "Mixed JSX attributes ending in spread requires specified objectAssign option with 'Object.assign' or polyfill helper.",
3449 this
3450 );
3451 }
3452 before = html
3453 ? ("', " + (this.program.options.objectAssign) + "({},")
3454 : (", " + (this.program.options.objectAssign) + "({},");
3455 after = ')';
3456 }
3457 } else {
3458 before = html ? "', {" : ', {';
3459 after = ' }';
3460 }
3461
3462 code.prependRight(this.name.end, before);
3463
3464 if (after) {
3465 code.appendLeft(this.attributes[len - 1].end, after);
3466 }
3467 } else {
3468 code.appendLeft(this.name.end, html ? "', null" : ", null");
3469 c = this.name.end;
3470 }
3471
3472 if (this.selfClosing) {
3473 code.overwrite(c, this.end, this.attributes.length ? ")" : " )");
3474 } else {
3475 code.remove(c, this.end);
3476 }
3477 };
3478
3479 return JSXOpeningElement;
3480}(Node));
3481
3482var JSXOpeningFragment = /*@__PURE__*/(function (Node) {
3483 function JSXOpeningFragment () {
3484 Node.apply(this, arguments);
3485 }
3486
3487 if ( Node ) JSXOpeningFragment.__proto__ = Node;
3488 JSXOpeningFragment.prototype = Object.create( Node && Node.prototype );
3489 JSXOpeningFragment.prototype.constructor = JSXOpeningFragment;
3490
3491 JSXOpeningFragment.prototype.transpile = function transpile (code) {
3492 code.overwrite(this.start, this.end, ((this.program.jsx) + "( " + (this.program.jsxFragment) + ", null"));
3493 };
3494
3495 return JSXOpeningFragment;
3496}(Node));
3497
3498var JSXSpreadAttribute = /*@__PURE__*/(function (Node) {
3499 function JSXSpreadAttribute () {
3500 Node.apply(this, arguments);
3501 }
3502
3503 if ( Node ) JSXSpreadAttribute.__proto__ = Node;
3504 JSXSpreadAttribute.prototype = Object.create( Node && Node.prototype );
3505 JSXSpreadAttribute.prototype.constructor = JSXSpreadAttribute;
3506
3507 JSXSpreadAttribute.prototype.transpile = function transpile (code, transforms) {
3508 code.remove(this.start, this.argument.start);
3509 code.remove(this.argument.end, this.end);
3510
3511 Node.prototype.transpile.call(this, code, transforms);
3512 };
3513
3514 return JSXSpreadAttribute;
3515}(Node));
3516
3517var nonAsciiLsOrPs = /[\u2028-\u2029]/g;
3518
3519var Literal = /*@__PURE__*/(function (Node) {
3520 function Literal () {
3521 Node.apply(this, arguments);
3522 }
3523
3524 if ( Node ) Literal.__proto__ = Node;
3525 Literal.prototype = Object.create( Node && Node.prototype );
3526 Literal.prototype.constructor = Literal;
3527
3528 Literal.prototype.initialise = function initialise () {
3529 if (typeof this.value === 'string') {
3530 this.program.indentExclusionElements.push(this);
3531 }
3532 };
3533
3534 Literal.prototype.transpile = function transpile (code, transforms) {
3535 if (transforms.numericLiteral) {
3536 if (this.raw.match(/^0[bo]/i)) {
3537 code.overwrite(this.start, this.end, String(this.value), {
3538 storeName: true,
3539 contentOnly: true
3540 });
3541 }
3542 }
3543
3544 if (this.regex) {
3545 var ref = this.regex;
3546 var pattern = ref.pattern;
3547 var flags = ref.flags;
3548
3549 if (transforms.stickyRegExp && /y/.test(flags))
3550 { CompileError.missingTransform('the regular expression sticky flag', 'stickyRegExp', this); }
3551 if (transforms.unicodeRegExp && /u/.test(flags)) {
3552 code.overwrite(
3553 this.start,
3554 this.end,
3555 ("/" + (rewritePattern(pattern, flags)) + "/" + (flags.replace('u', ''))),
3556 {
3557 contentOnly: true
3558 }
3559 );
3560 }
3561 } else if (typeof this.value === "string" && this.value.match(nonAsciiLsOrPs)) {
3562 code.overwrite(
3563 this.start,
3564 this.end,
3565 this.raw.replace(nonAsciiLsOrPs, function (m) { return m == '\u2028' ? '\\u2028' : '\\u2029'; }),
3566 {
3567 contentOnly: true
3568 }
3569 );
3570 }
3571 };
3572
3573 return Literal;
3574}(Node));
3575
3576var MemberExpression = /*@__PURE__*/(function (Node) {
3577 function MemberExpression () {
3578 Node.apply(this, arguments);
3579 }
3580
3581 if ( Node ) MemberExpression.__proto__ = Node;
3582 MemberExpression.prototype = Object.create( Node && Node.prototype );
3583 MemberExpression.prototype.constructor = MemberExpression;
3584
3585 MemberExpression.prototype.transpile = function transpile (code, transforms) {
3586 if (transforms.reservedProperties && reserved[this.property.name]) {
3587 code.overwrite(this.object.end, this.property.start, "['");
3588 code.appendLeft(this.property.end, "']");
3589 }
3590
3591 Node.prototype.transpile.call(this, code, transforms);
3592 };
3593
3594 return MemberExpression;
3595}(Node));
3596
3597var NewExpression = /*@__PURE__*/(function (Node) {
3598 function NewExpression () {
3599 Node.apply(this, arguments);
3600 }
3601
3602 if ( Node ) NewExpression.__proto__ = Node;
3603 NewExpression.prototype = Object.create( Node && Node.prototype );
3604 NewExpression.prototype.constructor = NewExpression;
3605
3606 NewExpression.prototype.initialise = function initialise (transforms) {
3607 if (transforms.spreadRest && this.arguments.length) {
3608 var lexicalBoundary = this.findLexicalBoundary();
3609
3610 var i = this.arguments.length;
3611 while (i--) {
3612 var arg = this.arguments[i];
3613 if (arg.type === 'SpreadElement' && isArguments(arg.argument)) {
3614 this.argumentsArrayAlias = lexicalBoundary.getArgumentsArrayAlias();
3615 break;
3616 }
3617 }
3618 }
3619
3620 Node.prototype.initialise.call(this, transforms);
3621 };
3622
3623 NewExpression.prototype.transpile = function transpile (code, transforms) {
3624 Node.prototype.transpile.call(this, code, transforms);
3625
3626 if (transforms.spreadRest && this.arguments.length) {
3627 inlineSpreads(code, this, this.arguments);
3628 // this.arguments.length may have changed, must retest.
3629 }
3630
3631 if (transforms.spreadRest && this.arguments.length) {
3632 var firstArgument = this.arguments[0];
3633 var isNew = true;
3634 var hasSpreadElements = spread(
3635 code,
3636 this.arguments,
3637 firstArgument.start,
3638 this.argumentsArrayAlias,
3639 isNew
3640 );
3641
3642 if (hasSpreadElements) {
3643 code.prependRight(
3644 this.start + 'new'.length,
3645 ' (Function.prototype.bind.apply('
3646 );
3647 code.overwrite(
3648 this.callee.end,
3649 firstArgument.start,
3650 ', [ null ].concat( '
3651 );
3652 code.appendLeft(this.end, ' ))');
3653 }
3654 }
3655
3656 if (this.arguments.length) {
3657 removeTrailingComma(code, this.arguments[this.arguments.length - 1].end);
3658 }
3659 };
3660
3661 return NewExpression;
3662}(Node));
3663
3664var ObjectExpression = /*@__PURE__*/(function (Node) {
3665 function ObjectExpression () {
3666 Node.apply(this, arguments);
3667 }
3668
3669 if ( Node ) ObjectExpression.__proto__ = Node;
3670 ObjectExpression.prototype = Object.create( Node && Node.prototype );
3671 ObjectExpression.prototype.constructor = ObjectExpression;
3672
3673 ObjectExpression.prototype.transpile = function transpile (code, transforms) {
3674 var ref;
3675
3676 Node.prototype.transpile.call(this, code, transforms);
3677
3678 var firstPropertyStart = this.start + 1;
3679 var spreadPropertyCount = 0;
3680 var computedPropertyCount = 0;
3681 var firstSpreadProperty = null;
3682 var firstComputedProperty = null;
3683
3684 for (var i = 0; i < this.properties.length; ++i) {
3685 var prop = this.properties[i];
3686 if (prop.type === 'SpreadElement') {
3687 // First see if we can inline the spread, to save needing objectAssign.
3688 var argument = prop.argument;
3689 if (
3690 argument.type === 'ObjectExpression' || (
3691 argument.type === 'Literal' &&
3692 typeof argument.value !== 'string'
3693 )
3694 ) {
3695 if (argument.type === 'ObjectExpression' && argument.properties.length > 0) {
3696 // Strip the `...{` and the `}` with a possible trailing comma before it,
3697 // leaving just the possible trailing comma after it.
3698 code.remove(prop.start, argument.properties[0].start);
3699 code.remove(argument.properties[argument.properties.length - 1].end, prop.end);
3700 (ref = this.properties).splice.apply(ref, [ i, 1 ].concat( argument.properties ));
3701 i--;
3702 } else {
3703 // An empty object, boolean, null, undefined, number or regexp (but NOT
3704 // string) will spread to nothing, so just remove the element altogether,
3705 // including a possible trailing comma.
3706 code.remove(prop.start, i === this.properties.length - 1
3707 ? prop.end
3708 : this.properties[i + 1].start);
3709 this.properties.splice(i, 1);
3710 i--;
3711 }
3712 } else {
3713 spreadPropertyCount += 1;
3714 if (firstSpreadProperty === null) { firstSpreadProperty = i; }
3715 }
3716 } else if (prop.computed && transforms.computedProperty) {
3717 computedPropertyCount += 1;
3718 if (firstComputedProperty === null) { firstComputedProperty = i; }
3719 }
3720 }
3721
3722 if (spreadPropertyCount && !transforms.objectRestSpread && !(computedPropertyCount && transforms.computedProperty)) {
3723 spreadPropertyCount = 0;
3724 firstSpreadProperty = null;
3725 } else if (spreadPropertyCount) {
3726 if (!this.program.options.objectAssign) {
3727 throw new CompileError(
3728 "Object spread operator requires specified objectAssign option with 'Object.assign' or polyfill helper.",
3729 this
3730 );
3731 }
3732 var i$1 = this.properties.length;
3733 while (i$1--) {
3734 var prop$1 = this.properties[i$1];
3735
3736 // enclose run of non-spread properties in curlies
3737 if (prop$1.type === 'Property' && !computedPropertyCount) {
3738 var lastProp = this.properties[i$1 - 1];
3739 var nextProp = this.properties[i$1 + 1];
3740
3741 if (!lastProp || lastProp.type !== 'Property') {
3742 code.prependRight(prop$1.start, '{');
3743 }
3744
3745 if (!nextProp || nextProp.type !== 'Property') {
3746 code.appendLeft(prop$1.end, '}');
3747 }
3748 }
3749
3750 // Remove ellipsis on spread property
3751 if (prop$1.type === 'SpreadElement') {
3752 code.remove(prop$1.start, prop$1.argument.start);
3753 code.remove(prop$1.argument.end, prop$1.end);
3754 }
3755 }
3756
3757 // wrap the whole thing in Object.assign
3758 firstPropertyStart = this.properties[0].start;
3759 if (!computedPropertyCount) {
3760 code.overwrite(
3761 this.start,
3762 firstPropertyStart,
3763 ((this.program.options.objectAssign) + "({}, ")
3764 );
3765 code.overwrite(
3766 this.properties[this.properties.length - 1].end,
3767 this.end,
3768 ')'
3769 );
3770 } else if (this.properties[0].type === 'SpreadElement') {
3771 code.overwrite(
3772 this.start,
3773 firstPropertyStart,
3774 ((this.program.options.objectAssign) + "({}, ")
3775 );
3776 code.remove(this.end - 1, this.end);
3777 code.appendRight(this.end, ')');
3778 } else {
3779 code.prependLeft(this.start, ((this.program.options.objectAssign) + "("));
3780 code.appendRight(this.end, ')');
3781 }
3782 }
3783
3784 if (computedPropertyCount && transforms.computedProperty) {
3785 var i0 = this.getIndentation();
3786
3787 var isSimpleAssignment;
3788 var name;
3789
3790 if (
3791 this.parent.type === 'VariableDeclarator' &&
3792 this.parent.parent.declarations.length === 1 &&
3793 this.parent.id.type === 'Identifier'
3794 ) {
3795 isSimpleAssignment = true;
3796 name = this.parent.id.alias || this.parent.id.name; // TODO is this right?
3797 } else if (
3798 this.parent.type === 'AssignmentExpression' &&
3799 this.parent.parent.type === 'ExpressionStatement' &&
3800 this.parent.left.type === 'Identifier'
3801 ) {
3802 isSimpleAssignment = true;
3803 name = this.parent.left.alias || this.parent.left.name; // TODO is this right?
3804 } else if (
3805 this.parent.type === 'AssignmentPattern' &&
3806 this.parent.left.type === 'Identifier'
3807 ) {
3808 isSimpleAssignment = true;
3809 name = this.parent.left.alias || this.parent.left.name; // TODO is this right?
3810 }
3811
3812 if (spreadPropertyCount) { isSimpleAssignment = false; }
3813
3814 // handle block scoping
3815 name = this.findScope(false).resolveName(name);
3816
3817 var start = firstPropertyStart;
3818 var end = this.end;
3819
3820 if (isSimpleAssignment) ; else {
3821 if (
3822 firstSpreadProperty === null ||
3823 firstComputedProperty < firstSpreadProperty
3824 ) {
3825 name = this.findScope(true).createDeclaration('obj');
3826
3827 code.prependRight(this.start, ("( " + name + " = "));
3828 } else { name = null; } // We don't actually need this variable
3829 }
3830
3831 var len = this.properties.length;
3832 var lastComputedProp;
3833 var sawNonComputedProperty = false;
3834 var isFirst = true;
3835
3836 for (var i$2 = 0; i$2 < len; i$2 += 1) {
3837 var prop$2 = this.properties[i$2];
3838 var moveStart = i$2 > 0 ? this.properties[i$2 - 1].end : start;
3839
3840 if (
3841 prop$2.type === 'Property' &&
3842 (prop$2.computed || (lastComputedProp && !spreadPropertyCount))
3843 ) {
3844 if (i$2 === 0) { moveStart = this.start + 1; } // Trim leading whitespace
3845 lastComputedProp = prop$2;
3846
3847 if (!name) {
3848 name = this.findScope(true).createDeclaration('obj');
3849
3850 var propId = name + (prop$2.computed ? '' : '.');
3851 code.appendRight(prop$2.start, ("( " + name + " = {}, " + propId));
3852 } else {
3853 var propId$1 =
3854 (isSimpleAssignment ? (";\n" + i0 + name) : (", " + name)) +
3855 (prop$2.key.type === 'Literal' || prop$2.computed ? '' : '.');
3856
3857 if (moveStart < prop$2.start) {
3858 code.overwrite(moveStart, prop$2.start, propId$1);
3859 } else {
3860 code.prependRight(prop$2.start, propId$1);
3861 }
3862 }
3863
3864 var c = prop$2.key.end;
3865 if (prop$2.computed) {
3866 while (code.original[c] !== ']') { c += 1; }
3867 c += 1;
3868 }
3869 if (prop$2.key.type === 'Literal' && !prop$2.computed) {
3870 code.overwrite(
3871 prop$2.start,
3872 prop$2.value.start,
3873 '[' + code.slice(prop$2.start, prop$2.key.end) + '] = '
3874 );
3875 } else if (prop$2.shorthand || (prop$2.method && !prop$2.computed && transforms.conciseMethodProperty)) {
3876 // Replace : with = if Property::transpile inserted the :
3877 code.overwrite(
3878 prop$2.key.start,
3879 prop$2.key.end,
3880 code.slice(prop$2.key.start, prop$2.key.end).replace(/:/, ' =')
3881 );
3882 } else {
3883 if (prop$2.value.start > c) { code.remove(c, prop$2.value.start); }
3884 code.prependLeft(c, ' = ');
3885 }
3886
3887 // This duplicates behavior from Property::transpile which is disabled
3888 // for computed properties or if conciseMethodProperty is false
3889 if (prop$2.method && (prop$2.computed || !transforms.conciseMethodProperty)) {
3890 if (prop$2.value.generator) { code.remove(prop$2.start, prop$2.key.start); }
3891 code.prependRight(prop$2.value.start, ("function" + (prop$2.value.generator ? '*' : '') + " "));
3892 }
3893 } else if (prop$2.type === 'SpreadElement') {
3894 if (name && i$2 > 0) {
3895 if (!lastComputedProp) {
3896 lastComputedProp = this.properties[i$2 - 1];
3897 }
3898 code.appendLeft(lastComputedProp.end, (", " + name + " )"));
3899
3900 lastComputedProp = null;
3901 name = null;
3902 }
3903 } else {
3904 if (!isFirst && spreadPropertyCount) {
3905 // We are in an Object.assign context, so we need to wrap regular properties
3906 code.prependRight(prop$2.start, '{');
3907 code.appendLeft(prop$2.end, '}');
3908 }
3909 sawNonComputedProperty = true;
3910 }
3911 if (isFirst && (prop$2.type === 'SpreadElement' || prop$2.computed)) {
3912 var beginEnd = sawNonComputedProperty
3913 ? this.properties[this.properties.length - 1].end
3914 : this.end - 1;
3915 // Trim trailing comma because it can easily become a leading comma which is illegal
3916 if (code.original[beginEnd] == ',') { ++beginEnd; }
3917 var closing = code.slice(beginEnd, end);
3918 code.prependLeft(moveStart, closing);
3919 code.remove(beginEnd, end);
3920 isFirst = false;
3921 }
3922
3923 // Clean up some extranous whitespace
3924 var c$1 = prop$2.end;
3925 if (i$2 < len - 1 && !sawNonComputedProperty) {
3926 while (code.original[c$1] !== ',') { c$1 += 1; }
3927 } else if (i$2 == len - 1) { c$1 = this.end; }
3928 if (prop$2.end != c$1) { code.overwrite(prop$2.end, c$1, '', {contentOnly: true}); }
3929 }
3930
3931 if (!isSimpleAssignment && name) {
3932 code.appendLeft(lastComputedProp.end, (", " + name + " )"));
3933 }
3934 }
3935 };
3936
3937 return ObjectExpression;
3938}(Node));
3939
3940var Property = /*@__PURE__*/(function (Node) {
3941 function Property () {
3942 Node.apply(this, arguments);
3943 }
3944
3945 if ( Node ) Property.__proto__ = Node;
3946 Property.prototype = Object.create( Node && Node.prototype );
3947 Property.prototype.constructor = Property;
3948
3949 Property.prototype.initialise = function initialise (transforms) {
3950 if ((this.kind === 'get' || this.kind === 'set') && transforms.getterSetter) {
3951 CompileError.missingTransform("getters and setters", "getterSetter", this);
3952 }
3953 Node.prototype.initialise.call(this, transforms);
3954 };
3955
3956 Property.prototype.transpile = function transpile (code, transforms) {
3957 Node.prototype.transpile.call(this, code, transforms);
3958
3959 if (
3960 transforms.conciseMethodProperty &&
3961 !this.computed &&
3962 this.parent.type !== 'ObjectPattern'
3963 ) {
3964 if (this.shorthand) {
3965 code.prependRight(this.start, ((this.key.name) + ": "));
3966 } else if (this.method) {
3967 var name = '';
3968 if (this.program.options.namedFunctionExpressions !== false) {
3969 if (
3970 this.key.type === 'Literal' &&
3971 typeof this.key.value === 'number'
3972 ) {
3973 name = '';
3974 } else if (this.key.type === 'Identifier') {
3975 if (
3976 reserved[this.key.name] ||
3977 !/^[a-z_$][a-z0-9_$]*$/i.test(this.key.name) ||
3978 this.value.body.scope.references[this.key.name]
3979 ) {
3980 name = this.findScope(true).createIdentifier(this.key.name);
3981 } else {
3982 name = this.key.name;
3983 }
3984 } else {
3985 name = this.findScope(true).createIdentifier(this.key.value);
3986 }
3987 name = ' ' + name;
3988 }
3989
3990 if (this.start < this.key.start) { code.remove(this.start, this.key.start); }
3991 code.appendLeft(
3992 this.key.end,
3993 (": " + (this.value.async ? 'async ' : '') + "function" + (this.value.generator ? '*' : '') + name)
3994 );
3995 }
3996 }
3997
3998 if (transforms.reservedProperties && reserved[this.key.name]) {
3999 code.prependRight(this.key.start, "'");
4000 code.appendLeft(this.key.end, "'");
4001 }
4002 };
4003
4004 return Property;
4005}(Node));
4006
4007var ReturnStatement = /*@__PURE__*/(function (Node) {
4008 function ReturnStatement () {
4009 Node.apply(this, arguments);
4010 }
4011
4012 if ( Node ) ReturnStatement.__proto__ = Node;
4013 ReturnStatement.prototype = Object.create( Node && Node.prototype );
4014 ReturnStatement.prototype.constructor = ReturnStatement;
4015
4016 ReturnStatement.prototype.initialise = function initialise (transforms) {
4017 this.loop = this.findNearest(loopStatement);
4018 this.nearestFunction = this.findNearest(/Function/);
4019
4020 if (
4021 this.loop &&
4022 (!this.nearestFunction || this.loop.depth > this.nearestFunction.depth)
4023 ) {
4024 this.loop.canReturn = true;
4025 this.shouldWrap = true;
4026 }
4027
4028 if (this.argument) { this.argument.initialise(transforms); }
4029 };
4030
4031 ReturnStatement.prototype.transpile = function transpile (code, transforms) {
4032 var shouldWrap =
4033 this.shouldWrap && this.loop && this.loop.shouldRewriteAsFunction;
4034
4035 if (this.argument) {
4036 if (shouldWrap) { code.prependRight(this.argument.start, "{ v: "); }
4037 this.argument.transpile(code, transforms);
4038 if (shouldWrap) { code.appendLeft(this.argument.end, " }"); }
4039 } else if (shouldWrap) {
4040 code.appendLeft(this.start + 6, ' {}');
4041 }
4042 };
4043
4044 return ReturnStatement;
4045}(Node));
4046
4047var Super = /*@__PURE__*/(function (Node) {
4048 function Super () {
4049 Node.apply(this, arguments);
4050 }
4051
4052 if ( Node ) Super.__proto__ = Node;
4053 Super.prototype = Object.create( Node && Node.prototype );
4054 Super.prototype.constructor = Super;
4055
4056 Super.prototype.initialise = function initialise (transforms) {
4057 if (transforms.classes) {
4058 this.method = this.findNearest('MethodDefinition');
4059 if (!this.method)
4060 { throw new CompileError('use of super outside class method', this); }
4061
4062 var parentClass = this.findNearest('ClassBody').parent;
4063 this.superClassName =
4064 parentClass.superClass && (parentClass.superClass.name || 'superclass');
4065
4066 if (!this.superClassName)
4067 { throw new CompileError('super used in base class', this); }
4068
4069 this.isCalled =
4070 this.parent.type === 'CallExpression' && this === this.parent.callee;
4071
4072 if (this.method.kind !== 'constructor' && this.isCalled) {
4073 throw new CompileError(
4074 'super() not allowed outside class constructor',
4075 this
4076 );
4077 }
4078
4079 this.isMember = this.parent.type === 'MemberExpression';
4080
4081 if (!this.isCalled && !this.isMember) {
4082 throw new CompileError(
4083 'Unexpected use of `super` (expected `super(...)` or `super.*`)',
4084 this
4085 );
4086 }
4087 }
4088
4089 if (transforms.arrow) {
4090 var lexicalBoundary = this.findLexicalBoundary();
4091 var arrowFunction = this.findNearest('ArrowFunctionExpression');
4092 var loop = this.findNearest(loopStatement);
4093
4094 if (arrowFunction && arrowFunction.depth > lexicalBoundary.depth) {
4095 this.thisAlias = lexicalBoundary.getThisAlias();
4096 }
4097
4098 if (
4099 loop &&
4100 loop.body.contains(this) &&
4101 loop.depth > lexicalBoundary.depth
4102 ) {
4103 this.thisAlias = lexicalBoundary.getThisAlias();
4104 }
4105 }
4106 };
4107
4108 Super.prototype.transpile = function transpile (code, transforms) {
4109 if (transforms.classes) {
4110 var expression =
4111 this.isCalled || this.method.static
4112 ? this.superClassName
4113 : ((this.superClassName) + ".prototype");
4114
4115 code.overwrite(this.start, this.end, expression, {
4116 storeName: true,
4117 contentOnly: true
4118 });
4119
4120 var callExpression = this.isCalled ? this.parent : this.parent.parent;
4121
4122 if (callExpression && callExpression.type === 'CallExpression') {
4123 if (!this.noCall) {
4124 // special case – `super( ...args )`
4125 code.appendLeft(callExpression.callee.end, '.call');
4126 }
4127
4128 var thisAlias = this.thisAlias || 'this';
4129
4130 if (callExpression.arguments.length) {
4131 code.appendLeft(callExpression.arguments[0].start, (thisAlias + ", "));
4132 } else {
4133 code.appendLeft(callExpression.end - 1, ("" + thisAlias));
4134 }
4135 }
4136 }
4137 };
4138
4139 return Super;
4140}(Node));
4141
4142var TaggedTemplateExpression = /*@__PURE__*/(function (Node) {
4143 function TaggedTemplateExpression () {
4144 Node.apply(this, arguments);
4145 }
4146
4147 if ( Node ) TaggedTemplateExpression.__proto__ = Node;
4148 TaggedTemplateExpression.prototype = Object.create( Node && Node.prototype );
4149 TaggedTemplateExpression.prototype.constructor = TaggedTemplateExpression;
4150
4151 TaggedTemplateExpression.prototype.initialise = function initialise (transforms) {
4152 if (
4153 transforms.templateString &&
4154 !transforms.dangerousTaggedTemplateString
4155 ) {
4156 CompileError.missingTransform(
4157 "tagged template strings", "templateString", this, "dangerousTaggedTemplateString"
4158 );
4159 }
4160
4161 Node.prototype.initialise.call(this, transforms);
4162 };
4163
4164 TaggedTemplateExpression.prototype.transpile = function transpile (code, transforms) {
4165 if (transforms.templateString && transforms.dangerousTaggedTemplateString) {
4166 var ordered = this.quasi.expressions
4167 .concat(this.quasi.quasis)
4168 .sort(function (a, b) { return a.start - b.start; });
4169
4170 var program = this.program;
4171 var rootScope = program.body.scope;
4172
4173 // insert strings at start
4174 var templateStrings = this.quasi.quasis.map(function (quasi) { return JSON.stringify(quasi.value.cooked); }
4175 ).join(', ');
4176
4177 var templateObject = this.program.templateLiteralQuasis[templateStrings];
4178 if (!templateObject) {
4179 templateObject = rootScope.createIdentifier('templateObject');
4180 code.prependLeft(this.program.prependAt, ("var " + templateObject + " = Object.freeze([" + templateStrings + "]);\n"));
4181
4182 this.program.templateLiteralQuasis[templateStrings] = templateObject;
4183 }
4184
4185 code.overwrite(
4186 this.tag.end,
4187 ordered[0].start,
4188 ("(" + templateObject)
4189 );
4190
4191 var lastIndex = ordered[0].start;
4192 ordered.forEach(function (node) {
4193 if (node.type === 'TemplateElement') {
4194 code.remove(lastIndex, node.end);
4195 } else {
4196 code.overwrite(lastIndex, node.start, ', ');
4197 }
4198
4199 lastIndex = node.end;
4200 });
4201
4202 code.overwrite(lastIndex, this.end, ')');
4203 }
4204
4205 Node.prototype.transpile.call(this, code, transforms);
4206 };
4207
4208 return TaggedTemplateExpression;
4209}(Node));
4210
4211var TemplateElement = /*@__PURE__*/(function (Node) {
4212 function TemplateElement () {
4213 Node.apply(this, arguments);
4214 }
4215
4216 if ( Node ) TemplateElement.__proto__ = Node;
4217 TemplateElement.prototype = Object.create( Node && Node.prototype );
4218 TemplateElement.prototype.constructor = TemplateElement;
4219
4220 TemplateElement.prototype.initialise = function initialise () {
4221 this.program.indentExclusionElements.push(this);
4222 };
4223
4224 return TemplateElement;
4225}(Node));
4226
4227var TemplateLiteral = /*@__PURE__*/(function (Node) {
4228 function TemplateLiteral () {
4229 Node.apply(this, arguments);
4230 }
4231
4232 if ( Node ) TemplateLiteral.__proto__ = Node;
4233 TemplateLiteral.prototype = Object.create( Node && Node.prototype );
4234 TemplateLiteral.prototype.constructor = TemplateLiteral;
4235
4236 TemplateLiteral.prototype.transpile = function transpile (code, transforms) {
4237 Node.prototype.transpile.call(this, code, transforms);
4238
4239 if (
4240 transforms.templateString &&
4241 this.parent.type !== 'TaggedTemplateExpression'
4242 ) {
4243 var ordered = this.expressions
4244 .concat(this.quasis)
4245 .sort(function (a, b) { return a.start - b.start || a.end - b.end; })
4246 .filter(function (node, i) {
4247 // include all expressions
4248 if (node.type !== 'TemplateElement') { return true; }
4249
4250 // include all non-empty strings
4251 if (node.value.raw) { return true; }
4252
4253 // exclude all empty strings not at the head
4254 return !i;
4255 });
4256
4257 // special case – we may be able to skip the first element,
4258 // if it's the empty string, but only if the second and
4259 // third elements aren't both expressions (since they maybe
4260 // be numeric, and `1 + 2 + '3' === '33'`)
4261 if (ordered.length >= 3) {
4262 var first = ordered[0];
4263 var third = ordered[2];
4264 if (
4265 first.type === 'TemplateElement' &&
4266 first.value.raw === '' &&
4267 third.type === 'TemplateElement'
4268 ) {
4269 ordered.shift();
4270 }
4271 }
4272
4273 var parenthesise =
4274 (this.quasis.length !== 1 || this.expressions.length !== 0) &&
4275 this.parent.type !== 'TemplateLiteral' &&
4276 this.parent.type !== 'AssignmentExpression' &&
4277 this.parent.type !== 'AssignmentPattern' &&
4278 this.parent.type !== 'VariableDeclarator' &&
4279 (this.parent.type !== 'BinaryExpression' ||
4280 this.parent.operator !== '+');
4281
4282 if (parenthesise) { code.appendRight(this.start, '('); }
4283
4284 var lastIndex = this.start;
4285
4286 ordered.forEach(function (node, i) {
4287 var prefix = i === 0 ? (parenthesise ? '(' : '') : ' + ';
4288
4289 if (node.type === 'TemplateElement') {
4290 code.overwrite(
4291 lastIndex,
4292 node.end,
4293 prefix + JSON.stringify(node.value.cooked)
4294 );
4295 } else {
4296 var parenthesise$1 = node.type !== 'Identifier'; // TODO other cases where it's safe
4297
4298 if (parenthesise$1) { prefix += '('; }
4299
4300 code.remove(lastIndex, node.start);
4301
4302 if (prefix) { code.prependRight(node.start, prefix); }
4303 if (parenthesise$1) { code.appendLeft(node.end, ')'); }
4304 }
4305
4306 lastIndex = node.end;
4307 });
4308
4309 if (parenthesise) { code.appendLeft(lastIndex, ')'); }
4310 code.overwrite(lastIndex, this.end, "", { contentOnly: true });
4311 }
4312 };
4313
4314 return TemplateLiteral;
4315}(Node));
4316
4317var ThisExpression = /*@__PURE__*/(function (Node) {
4318 function ThisExpression () {
4319 Node.apply(this, arguments);
4320 }
4321
4322 if ( Node ) ThisExpression.__proto__ = Node;
4323 ThisExpression.prototype = Object.create( Node && Node.prototype );
4324 ThisExpression.prototype.constructor = ThisExpression;
4325
4326 ThisExpression.prototype.initialise = function initialise (transforms) {
4327 var lexicalBoundary = this.findLexicalBoundary();
4328
4329 if (transforms.letConst) {
4330 // save all loops up to the lexical boundary in case we need
4331 // to alias them later for block-scoped declarations
4332 var node = this.findNearest(loopStatement);
4333 while (node && node.depth > lexicalBoundary.depth) {
4334 node.thisRefs.push(this);
4335 node = node.parent.findNearest(loopStatement);
4336 }
4337 }
4338
4339 if (transforms.arrow) {
4340 var arrowFunction = this.findNearest('ArrowFunctionExpression');
4341
4342 if (arrowFunction && arrowFunction.depth > lexicalBoundary.depth) {
4343 this.alias = lexicalBoundary.getThisAlias();
4344 }
4345 }
4346 };
4347
4348 ThisExpression.prototype.transpile = function transpile (code) {
4349 if (this.alias) {
4350 code.overwrite(this.start, this.end, this.alias, {
4351 storeName: true,
4352 contentOnly: true
4353 });
4354 }
4355 };
4356
4357 return ThisExpression;
4358}(Node));
4359
4360var UpdateExpression = /*@__PURE__*/(function (Node) {
4361 function UpdateExpression () {
4362 Node.apply(this, arguments);
4363 }
4364
4365 if ( Node ) UpdateExpression.__proto__ = Node;
4366 UpdateExpression.prototype = Object.create( Node && Node.prototype );
4367 UpdateExpression.prototype.constructor = UpdateExpression;
4368
4369 UpdateExpression.prototype.initialise = function initialise (transforms) {
4370 if (this.argument.type === 'Identifier') {
4371 var declaration = this.findScope(false).findDeclaration(
4372 this.argument.name
4373 );
4374 // special case – https://gitlab.com/Rich-Harris/buble/issues/150
4375 var statement = declaration && declaration.node.ancestor(3);
4376 if (
4377 statement &&
4378 statement.type === 'ForStatement' &&
4379 statement.body.contains(this)
4380 ) {
4381 statement.reassigned[this.argument.name] = true;
4382 }
4383 }
4384
4385 Node.prototype.initialise.call(this, transforms);
4386 };
4387
4388 UpdateExpression.prototype.transpile = function transpile (code, transforms) {
4389 if (this.argument.type === 'Identifier') {
4390 // Do this check after everything has been initialized to find
4391 // shadowing declarations after this expression
4392 checkConst(this.argument, this.findScope(false));
4393 }
4394 Node.prototype.transpile.call(this, code, transforms);
4395 };
4396
4397 return UpdateExpression;
4398}(Node));
4399
4400var VariableDeclaration = /*@__PURE__*/(function (Node) {
4401 function VariableDeclaration () {
4402 Node.apply(this, arguments);
4403 }
4404
4405 if ( Node ) VariableDeclaration.__proto__ = Node;
4406 VariableDeclaration.prototype = Object.create( Node && Node.prototype );
4407 VariableDeclaration.prototype.constructor = VariableDeclaration;
4408
4409 VariableDeclaration.prototype.initialise = function initialise (transforms) {
4410 this.scope = this.findScope(this.kind === 'var');
4411 this.declarations.forEach(function (declarator) { return declarator.initialise(transforms); });
4412 };
4413
4414 VariableDeclaration.prototype.transpile = function transpile (code, transforms) {
4415 var this$1 = this;
4416
4417 var i0 = this.getIndentation();
4418 var kind = this.kind;
4419
4420 if (transforms.letConst && kind !== 'var') {
4421 kind = 'var';
4422 code.overwrite(this.start, this.start + this.kind.length, kind, {
4423 contentOnly: true,
4424 storeName: true
4425 });
4426 }
4427
4428 if (transforms.destructuring && this.parent.type !== 'ForOfStatement' && this.parent.type !== 'ForInStatement') {
4429 var c = this.start;
4430 var lastDeclaratorIsPattern;
4431
4432 this.declarations.forEach(function (declarator, i) {
4433 declarator.transpile(code, transforms);
4434
4435 if (declarator.id.type === 'Identifier') {
4436 if (i > 0 && this$1.declarations[i - 1].id.type !== 'Identifier') {
4437 code.overwrite(c, declarator.id.start, "var ");
4438 }
4439 } else {
4440 var inline = loopStatement.test(this$1.parent.type);
4441
4442 if (i === 0) {
4443 code.remove(c, declarator.id.start);
4444 } else {
4445 code.overwrite(c, declarator.id.start, (";\n" + i0));
4446 }
4447
4448 var simple =
4449 declarator.init.type === 'Identifier' && !declarator.init.rewritten;
4450
4451 var name = simple
4452 ? (declarator.init.alias || declarator.init.name)
4453 : declarator.findScope(true).createIdentifier('ref');
4454
4455 c = declarator.start;
4456
4457 var statementGenerators = [];
4458
4459 if (simple) {
4460 code.remove(declarator.id.end, declarator.end);
4461 } else {
4462 statementGenerators.push(function (start, prefix, suffix) {
4463 code.prependRight(declarator.id.end, ("var " + name));
4464 code.appendLeft(declarator.init.end, ("" + suffix));
4465 code.move(declarator.id.end, declarator.end, start);
4466 });
4467 }
4468
4469 var scope = declarator.findScope(false);
4470 destructure(
4471 code,
4472 function (id) { return scope.createIdentifier(id); },
4473 function (ref) {
4474 var name = ref.name;
4475
4476 return scope.resolveName(name);
4477 },
4478 declarator.id,
4479 name,
4480 inline,
4481 statementGenerators
4482 );
4483
4484 var prefix = inline ? 'var ' : '';
4485 var suffix = inline ? ", " : (";\n" + i0);
4486 statementGenerators.forEach(function (fn, j) {
4487 if (
4488 i === this$1.declarations.length - 1 &&
4489 j === statementGenerators.length - 1
4490 ) {
4491 suffix = inline ? '' : ';';
4492 }
4493
4494 fn(declarator.start, j === 0 ? prefix : '', suffix);
4495 });
4496 }
4497
4498 c = declarator.end;
4499 lastDeclaratorIsPattern = declarator.id.type !== 'Identifier';
4500 });
4501
4502 if (lastDeclaratorIsPattern && this.end > c) {
4503 code.overwrite(c, this.end, '', { contentOnly: true });
4504 }
4505 } else {
4506 this.declarations.forEach(function (declarator) {
4507 declarator.transpile(code, transforms);
4508 });
4509 }
4510 };
4511
4512 return VariableDeclaration;
4513}(Node));
4514
4515var VariableDeclarator = /*@__PURE__*/(function (Node) {
4516 function VariableDeclarator () {
4517 Node.apply(this, arguments);
4518 }
4519
4520 if ( Node ) VariableDeclarator.__proto__ = Node;
4521 VariableDeclarator.prototype = Object.create( Node && Node.prototype );
4522 VariableDeclarator.prototype.constructor = VariableDeclarator;
4523
4524 VariableDeclarator.prototype.initialise = function initialise (transforms) {
4525 var kind = this.parent.kind;
4526 if (kind === 'let' && this.parent.parent.type === 'ForStatement') {
4527 kind = 'for.let'; // special case...
4528 }
4529
4530 this.parent.scope.addDeclaration(this.id, kind);
4531 Node.prototype.initialise.call(this, transforms);
4532 };
4533
4534 VariableDeclarator.prototype.transpile = function transpile (code, transforms) {
4535 if (!this.init && transforms.letConst && this.parent.kind !== 'var') {
4536 var inLoop = this.findNearest(
4537 /Function|^For(In|Of)?Statement|^(?:Do)?WhileStatement/
4538 );
4539 if (
4540 inLoop &&
4541 !/Function/.test(inLoop.type) &&
4542 !this.isLeftDeclaratorOfLoop()
4543 ) {
4544 code.appendLeft(this.id.end, ' = (void 0)');
4545 }
4546 }
4547
4548 if (this.id) { this.id.transpile(code, transforms); }
4549 if (this.init) { this.init.transpile(code, transforms); }
4550 };
4551
4552 VariableDeclarator.prototype.isLeftDeclaratorOfLoop = function isLeftDeclaratorOfLoop () {
4553 return (
4554 this.parent &&
4555 this.parent.type === 'VariableDeclaration' &&
4556 this.parent.parent &&
4557 (this.parent.parent.type === 'ForInStatement' ||
4558 this.parent.parent.type === 'ForOfStatement') &&
4559 this.parent.parent.left &&
4560 this.parent.parent.left.declarations[0] === this
4561 );
4562 };
4563
4564 return VariableDeclarator;
4565}(Node));
4566
4567var types = {
4568 ArrayExpression: ArrayExpression,
4569 ArrowFunctionExpression: ArrowFunctionExpression,
4570 AssignmentExpression: AssignmentExpression,
4571 AwaitExpression: AwaitExpression,
4572 BinaryExpression: BinaryExpression,
4573 BreakStatement: BreakStatement,
4574 CallExpression: CallExpression,
4575 CatchClause: CatchClause,
4576 ClassBody: ClassBody,
4577 ClassDeclaration: ClassDeclaration,
4578 ClassExpression: ClassExpression,
4579 ContinueStatement: ContinueStatement,
4580 DoWhileStatement: LoopStatement,
4581 ExportNamedDeclaration: ExportNamedDeclaration,
4582 ExportDefaultDeclaration: ExportDefaultDeclaration,
4583 ForStatement: ForStatement,
4584 ForInStatement: ForInStatement,
4585 ForOfStatement: ForOfStatement,
4586 FunctionDeclaration: FunctionDeclaration,
4587 FunctionExpression: FunctionExpression,
4588 Identifier: Identifier,
4589 IfStatement: IfStatement,
4590 Import: Import,
4591 ImportDeclaration: ImportDeclaration,
4592 ImportDefaultSpecifier: ImportDefaultSpecifier,
4593 ImportSpecifier: ImportSpecifier,
4594 JSXAttribute: JSXAttribute,
4595 JSXClosingElement: JSXClosingElement,
4596 JSXClosingFragment: JSXClosingFragment,
4597 JSXElement: JSXElement,
4598 JSXExpressionContainer: JSXExpressionContainer,
4599 JSXFragment: JSXFragment,
4600 JSXOpeningElement: JSXOpeningElement,
4601 JSXOpeningFragment: JSXOpeningFragment,
4602 JSXSpreadAttribute: JSXSpreadAttribute,
4603 Literal: Literal,
4604 MemberExpression: MemberExpression,
4605 NewExpression: NewExpression,
4606 ObjectExpression: ObjectExpression,
4607 Property: Property,
4608 ReturnStatement: ReturnStatement,
4609 Super: Super,
4610 TaggedTemplateExpression: TaggedTemplateExpression,
4611 TemplateElement: TemplateElement,
4612 TemplateLiteral: TemplateLiteral,
4613 ThisExpression: ThisExpression,
4614 UpdateExpression: UpdateExpression,
4615 VariableDeclaration: VariableDeclaration,
4616 VariableDeclarator: VariableDeclarator,
4617 WhileStatement: LoopStatement
4618};
4619
4620var keys = {
4621 Program: ['body'],
4622 Literal: []
4623};
4624
4625var statementsWithBlocks = {
4626 IfStatement: 'consequent',
4627 ForStatement: 'body',
4628 ForInStatement: 'body',
4629 ForOfStatement: 'body',
4630 WhileStatement: 'body',
4631 DoWhileStatement: 'body',
4632 ArrowFunctionExpression: 'body'
4633};
4634
4635function wrap(raw, parent) {
4636 if (!raw) { return; }
4637
4638 if ('length' in raw) {
4639 var i = raw.length;
4640 while (i--) { wrap(raw[i], parent); }
4641 return;
4642 }
4643
4644 // with e.g. shorthand properties, key and value are
4645 // the same node. We don't want to wrap an object twice
4646 if (raw.__wrapped) { return; }
4647 raw.__wrapped = true;
4648
4649 if (!keys[raw.type]) {
4650 keys[raw.type] = Object.keys(raw).filter(
4651 function (key) { return typeof raw[key] === 'object'; }
4652 );
4653 }
4654
4655 // special case – body-less if/for/while statements. TODO others?
4656 var bodyType = statementsWithBlocks[raw.type];
4657 if (bodyType && raw[bodyType].type !== 'BlockStatement') {
4658 var expression = raw[bodyType];
4659
4660 // create a synthetic block statement, otherwise all hell
4661 // breaks loose when it comes to block scoping
4662 raw[bodyType] = {
4663 start: expression.start,
4664 end: expression.end,
4665 type: 'BlockStatement',
4666 body: [expression],
4667 synthetic: true
4668 };
4669 }
4670
4671 raw.parent = parent;
4672 raw.program = parent.program || parent;
4673 raw.depth = parent.depth + 1;
4674 raw.keys = keys[raw.type];
4675 raw.indentation = undefined;
4676
4677 for (var i$1 = 0, list = keys[raw.type]; i$1 < list.length; i$1 += 1) {
4678 var key = list[i$1];
4679
4680 wrap(raw[key], raw);
4681 }
4682
4683 raw.program.magicString.addSourcemapLocation(raw.start);
4684 raw.program.magicString.addSourcemapLocation(raw.end);
4685
4686 var type =
4687 (raw.type === 'BlockStatement' ? BlockStatement : types[raw.type]) || Node;
4688 raw.__proto__ = type.prototype;
4689}
4690
4691function Program(source, ast, transforms, options) {
4692 this.type = 'Root';
4693
4694 // options
4695 this.jsx = options.jsx || 'React.createElement';
4696 this.jsxFragment = options.jsxFragment || 'React.Fragment';
4697 this.options = options;
4698
4699 this.source = source;
4700 this.magicString = new MagicString(source);
4701
4702 this.ast = ast;
4703 this.depth = 0;
4704
4705 wrap((this.body = ast), this);
4706 this.body.__proto__ = BlockStatement.prototype;
4707
4708 this.templateLiteralQuasis = Object.create(null);
4709 for (var i = 0; i < this.body.body.length; ++i) {
4710 if (!this.body.body[i].directive) {
4711 this.prependAt = this.body.body[i].start;
4712 break;
4713 }
4714 }
4715 this.objectWithoutPropertiesHelper = null;
4716
4717 this.indentExclusionElements = [];
4718 this.body.initialise(transforms);
4719
4720 this.indentExclusions = Object.create(null);
4721 for (var i$2 = 0, list = this.indentExclusionElements; i$2 < list.length; i$2 += 1) {
4722 var node = list[i$2];
4723
4724 for (var i$1 = node.start; i$1 < node.end; i$1 += 1) {
4725 this.indentExclusions[i$1] = true;
4726 }
4727 }
4728
4729 this.body.transpile(this.magicString, transforms);
4730}
4731
4732Program.prototype = {
4733 export: function export$1(options) {
4734 if ( options === void 0 ) options = {};
4735
4736 return {
4737 code: this.magicString.toString(),
4738 map: this.magicString.generateMap({
4739 file: options.file,
4740 source: options.source,
4741 includeContent: options.includeContent !== false
4742 })
4743 };
4744 },
4745
4746 findNearest: function findNearest() {
4747 return null;
4748 },
4749
4750 findScope: function findScope() {
4751 return null;
4752 },
4753
4754 getObjectWithoutPropertiesHelper: function getObjectWithoutPropertiesHelper(code) {
4755 if (!this.objectWithoutPropertiesHelper) {
4756 this.objectWithoutPropertiesHelper = this.body.scope.createIdentifier('objectWithoutProperties');
4757 code.prependLeft(this.prependAt, "function " + (this.objectWithoutPropertiesHelper) + " (obj, exclude) { " +
4758 "var target = {}; for (var k in obj) " +
4759 "if (Object.prototype.hasOwnProperty.call(obj, k) && exclude.indexOf(k) === -1) " +
4760 "target[k] = obj[k]; return target; }\n"
4761 );
4762 }
4763 return this.objectWithoutPropertiesHelper;
4764 }
4765};
4766
4767var matrix = {
4768 chrome: {
4769 48: 610719,
4770 49: 652287,
4771 50: 783359,
4772 51: 783359,
4773 52: 1045503,
4774 53: 1045503,
4775 54: 1045503,
4776 55: 3142655,
4777 56: 3142655,
4778 57: 3142655,
4779 58: 4191231,
4780 59: 4191231,
4781 60: 8385535,
4782 61: 8385535,
4783 62: 8385535,
4784 63: 8385535,
4785 64: 8385535,
4786 65: 8385535,
4787 66: 8385535,
4788 67: 8385535,
4789 68: 8385535,
4790 69: 8385535,
4791 70: 8385535,
4792 71: 8385535
4793 },
4794 firefox: {
4795 43: 643515,
4796 44: 643515,
4797 45: 643519,
4798 46: 774591,
4799 47: 774655,
4800 48: 774655,
4801 49: 774655,
4802 50: 774655,
4803 51: 775167,
4804 52: 4191231,
4805 53: 4191231,
4806 54: 4191231,
4807 55: 8385535,
4808 56: 8385535,
4809 57: 8385535,
4810 58: 8385535,
4811 59: 8385535,
4812 60: 8385535,
4813 61: 8385535,
4814 62: 8385535,
4815 63: 8385535,
4816 64: 8385535
4817 },
4818 safari: {
4819 8: 524297,
4820 9: 594141,
4821 10: 1831935,
4822 '10.1': 4191231,
4823 11: 4191231,
4824 '11.1': 8385535,
4825 12: 8385535
4826 },
4827 ie: {
4828 8: 0,
4829 9: 524289,
4830 10: 524289,
4831 11: 524289 // no let/const in for loops
4832 },
4833 edge: {
4834 12: 610459,
4835 13: 774559,
4836 14: 2085887,
4837 15: 4183039,
4838 16: 4183039,
4839 17: 4183039,
4840 18: 4183039,
4841 19: 4183039
4842 },
4843 node: {
4844 '0.10': 524289,
4845 '0.12': 524417,
4846 4: 594335,
4847 5: 594335,
4848 6: 783359,
4849 8: 4191231,
4850 '8.3': 8385535,
4851 '8.7': 8385535,
4852 '8.10': 8385535
4853 }
4854};
4855
4856var features = [
4857 'getterSetter',
4858 'arrow',
4859 'classes',
4860 'computedProperty',
4861 'conciseMethodProperty',
4862 'defaultParameter',
4863 'destructuring',
4864 'forOf',
4865 'generator',
4866 'letConst',
4867 'moduleExport',
4868 'moduleImport',
4869 'numericLiteral',
4870 'parameterDestructuring',
4871 'spreadRest',
4872 'stickyRegExp',
4873 'templateString',
4874 'unicodeRegExp',
4875
4876 // ES2016
4877 'exponentiation',
4878
4879 // additional transforms, not from
4880 // https://featuretests.io
4881 'reservedProperties',
4882
4883 'trailingFunctionCommas',
4884 'asyncAwait',
4885 'objectRestSpread'
4886];
4887
4888var version = "0.20.0";
4889
4890var parser = Parser.extend(acornDynamicImport, acornJsx());
4891
4892var dangerousTransforms = ['dangerousTaggedTemplateString', 'dangerousForOf'];
4893
4894function target(target) {
4895 var targets = Object.keys(target);
4896 var bitmask = targets.length
4897 ? 8388607
4898 : 524289;
4899
4900 Object.keys(target).forEach(function (environment) {
4901 var versions = matrix[environment];
4902 if (!versions)
4903 { throw new Error(
4904 ("Unknown environment '" + environment + "'. Please raise an issue at https://github.com/bublejs/buble/issues")
4905 ); }
4906
4907 var targetVersion = target[environment];
4908 if (!(targetVersion in versions))
4909 { throw new Error(
4910 ("Support data exists for the following versions of " + environment + ": " + (Object.keys(
4911 versions
4912 ).join(
4913 ', '
4914 )) + ". Please raise an issue at https://github.com/bublejs/buble/issues")
4915 ); }
4916 var support = versions[targetVersion];
4917
4918 bitmask &= support;
4919 });
4920
4921 var transforms = Object.create(null);
4922 features.forEach(function (name, i) {
4923 transforms[name] = !(bitmask & (1 << i));
4924 });
4925
4926 dangerousTransforms.forEach(function (name) {
4927 transforms[name] = false;
4928 });
4929
4930 return transforms;
4931}
4932
4933function transform(source, options) {
4934 if ( options === void 0 ) options = {};
4935
4936 var ast;
4937 var jsx = null;
4938
4939 try {
4940 ast = parser.parse(source, {
4941 ecmaVersion: 10,
4942 preserveParens: true,
4943 sourceType: 'module',
4944 allowAwaitOutsideFunction: true,
4945 allowReturnOutsideFunction: true,
4946 allowHashBang: true,
4947 onComment: function (block, text) {
4948 if (!jsx) {
4949 var match = /@jsx\s+([^\s]+)/.exec(text);
4950 if (match) { jsx = match[1]; }
4951 }
4952 }
4953 });
4954 options.jsx = jsx || options.jsx;
4955 } catch (err) {
4956 err.snippet = getSnippet(source, err.loc);
4957 err.toString = function () { return ((err.name) + ": " + (err.message) + "\n" + (err.snippet)); };
4958 throw err;
4959 }
4960
4961 var transforms = target(options.target || {});
4962 Object.keys(options.transforms || {}).forEach(function (name) {
4963 if (name === 'modules') {
4964 if (!('moduleImport' in options.transforms))
4965 { transforms.moduleImport = options.transforms.modules; }
4966 if (!('moduleExport' in options.transforms))
4967 { transforms.moduleExport = options.transforms.modules; }
4968 return;
4969 }
4970
4971 if (!(name in transforms)) { throw new Error(("Unknown transform '" + name + "'")); }
4972 transforms[name] = options.transforms[name];
4973 });
4974 if (options.objectAssign === true) { options.objectAssign = 'Object.assign'; }
4975 return new Program(source, ast, transforms, options).export(options);
4976}
4977
4978export { version as VERSION, target, transform };
4979//# sourceMappingURL=buble-browser.es.js.map