esperanto-source 0.6.8

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,2552 @@
1
+ /*
2
+ esperanto.js v0.6.8 - 2015-02-07
3
+ http://esperantojs.org
4
+
5
+ Released under the MIT License.
6
+ */
7
+
8
+ 'use strict';
9
+
10
+ var acorn = require('acorn');
11
+ var MagicString = require('magic-string');
12
+ var path = require('path');
13
+ var sander = require('sander');
14
+ var estraverse = require('estraverse');
15
+
16
+ var hasOwnProp = Object.prototype.hasOwnProperty;
17
+
18
+ function hasNamedImports ( mod ) {
19
+ var i = mod.imports.length;
20
+
21
+ while ( i-- ) {
22
+ if ( mod.imports[i].isNamed ) {
23
+ return true;
24
+ }
25
+ }
26
+ }
27
+
28
+ function hasNamedExports ( mod ) {
29
+ var i = mod.exports.length;
30
+
31
+ while ( i-- ) {
32
+ if ( !mod.exports[i].isDefault ) {
33
+ return true;
34
+ }
35
+ }
36
+ }
37
+
38
+ /*
39
+ This module traverse a module's AST, attaching scope information
40
+ to nodes as it goes, which is later used to determine which
41
+ identifiers need to be rewritten to avoid collisions
42
+ */
43
+
44
+ var Scope = function ( options ) {
45
+ options = options || {};
46
+
47
+ this.parent = options.parent;
48
+ this.names = options.params || [];
49
+ };
50
+
51
+ Scope.prototype = {
52
+ add: function ( name ) {
53
+ this.names.push( name );
54
+ },
55
+
56
+ contains: function ( name, ignoreTopLevel ) {
57
+ if ( ignoreTopLevel && !this.parent ) {
58
+ return false;
59
+ }
60
+
61
+ if ( ~this.names.indexOf( name ) ) {
62
+ return true;
63
+ }
64
+
65
+ if ( this.parent ) {
66
+ return this.parent.contains( name, ignoreTopLevel );
67
+ }
68
+
69
+ return false;
70
+ }
71
+ };
72
+
73
+ function annotateAst ( ast ) {
74
+ var scope = new Scope(), blockScope = new Scope(), declared = {}, topLevelFunctionNames = [], templateLiteralRanges = [];
75
+
76
+ var envDepth = 0;
77
+
78
+ estraverse.traverse( ast, {
79
+ enter: function ( node ) {
80
+ if ( node.type === 'ImportDeclaration' ) {
81
+ node._skip = true;
82
+ }
83
+
84
+ if ( node._skip ) {
85
+ return this.skip();
86
+ }
87
+
88
+ switch ( node.type ) {
89
+ case 'FunctionExpression':
90
+ case 'FunctionDeclaration':
91
+
92
+ envDepth++;
93
+
94
+ // fallthrough
95
+
96
+ case 'ArrowFunctionExpression':
97
+ if ( node.id ) {
98
+ addToScope( node );
99
+
100
+ // If this is the root scope, this may need to be
101
+ // exported early, so we make a note of it
102
+ if ( !scope.parent && node.type === 'FunctionDeclaration' ) {
103
+ topLevelFunctionNames.push( node.id.name );
104
+ }
105
+ }
106
+
107
+ scope = node._scope = new Scope({
108
+ parent: scope,
109
+ params: node.params.map( function(x ) {return x.name} ) // TODO rest params?
110
+ });
111
+
112
+ break;
113
+
114
+ case 'BlockStatement':
115
+ blockScope = node._blockScope = new Scope({
116
+ parent: blockScope
117
+ });
118
+
119
+ break;
120
+
121
+ case 'VariableDeclaration':
122
+ node.declarations.forEach( node.kind === 'let' ? addToBlockScope : addToScope );
123
+ break;
124
+
125
+ case 'ClassExpression':
126
+ case 'ClassDeclaration':
127
+ addToScope( node );
128
+ break;
129
+
130
+ case 'MemberExpression':
131
+ if ( envDepth === 0 && node.object.type === 'ThisExpression' ) {
132
+ throw new Error('`this` at the top level is undefined');
133
+ }
134
+ !node.computed && ( node.property._skip = true );
135
+ break;
136
+
137
+ case 'Property':
138
+ node.key._skip = true;
139
+ break;
140
+
141
+ case 'TemplateLiteral':
142
+ templateLiteralRanges.push([ node.start, node.end ]);
143
+ break;
144
+
145
+ case 'ThisExpression':
146
+ if (envDepth === 0) {
147
+ node._topLevel = true;
148
+ }
149
+ break;
150
+ }
151
+ },
152
+ leave: function ( node ) {
153
+ switch ( node.type ) {
154
+ case 'FunctionExpression':
155
+ case 'FunctionDeclaration':
156
+
157
+ envDepth--;
158
+
159
+ // fallthrough
160
+
161
+ case 'ArrowFunctionExpression':
162
+
163
+ scope = scope.parent;
164
+
165
+ break;
166
+
167
+ case 'BlockStatement':
168
+ blockScope = blockScope.parent;
169
+ break;
170
+ }
171
+ }
172
+ });
173
+
174
+ function addToScope ( declarator ) {
175
+ var name = declarator.id.name;
176
+
177
+ scope.add( name );
178
+ declared[ name ] = true;
179
+ }
180
+
181
+ function addToBlockScope ( declarator ) {
182
+ var name = declarator.id.name;
183
+
184
+ blockScope.add( name );
185
+ declared[ name ] = true;
186
+ }
187
+
188
+ ast._scope = scope;
189
+ ast._blockScope = blockScope;
190
+ ast._topLevelNames = ast._scope.names.concat( ast._blockScope.names );
191
+ ast._topLevelFunctionNames = topLevelFunctionNames;
192
+ ast._declared = declared;
193
+ ast._templateLiteralRanges = templateLiteralRanges;
194
+ }
195
+
196
+ /**
197
+ * Inspects a module and discovers/categorises import & export declarations
198
+ * @param {object} mod - the module object
199
+ * @param {string} source - the module's original source code
200
+ * @param {object} ast - the result of parsing `source` with acorn
201
+ * @returns {array} - [ imports, exports ]
202
+ */
203
+ function findImportsAndExports ( mod, source, ast ) {
204
+ var imports = [], exports = [], previousDeclaration;
205
+
206
+ ast.body.forEach( function(node ) {
207
+ var passthrough, declaration;
208
+
209
+ if ( previousDeclaration ) {
210
+ previousDeclaration.next = node.start;
211
+
212
+ if ( node.type !== 'EmptyStatement' ) {
213
+ previousDeclaration = null;
214
+ }
215
+ }
216
+
217
+ if ( node.type === 'ImportDeclaration' ) {
218
+ declaration = processImport( node );
219
+ imports.push( declaration );
220
+ }
221
+
222
+ else if ( node.type === 'ExportDeclaration' ) {
223
+ declaration = processExport( node, source );
224
+ exports.push( declaration );
225
+
226
+ if ( declaration.isDefault ) {
227
+ if ( mod.defaultExport ) {
228
+ throw new Error( 'Duplicate default exports' );
229
+ }
230
+ mod.defaultExport = declaration;
231
+ }
232
+
233
+ if ( node.source ) {
234
+ // it's both an import and an export, e.g.
235
+ // `export { foo } from './bar';
236
+ passthrough = processImport( node, true );
237
+ imports.push( passthrough );
238
+
239
+ declaration.passthrough = passthrough;
240
+ }
241
+ }
242
+
243
+ if ( declaration ) {
244
+ previousDeclaration = declaration;
245
+ }
246
+ });
247
+
248
+ // catch any trailing semicolons
249
+ if ( previousDeclaration ) {
250
+ previousDeclaration.next = source.length;
251
+ previousDeclaration.isFinal = true;
252
+ }
253
+
254
+ return [ imports, exports ];
255
+ }
256
+
257
+ /**
258
+ * Generates a representation of an import declaration
259
+ * @param {object} node - the original AST node
260
+ * @param {boolean} passthrough - `true` if this is an `export { foo } from 'bar'`-style declaration
261
+ * @returns {object}
262
+ */
263
+ function processImport ( node, passthrough ) {
264
+ var x = {
265
+ id: null, // used by bundler - filled in later
266
+ node: node,
267
+ start: node.start,
268
+ end: node.end,
269
+ passthrough: !!passthrough,
270
+
271
+ path: node.source.value,
272
+ specifiers: node.specifiers.map( function(s ) {
273
+ var id;
274
+
275
+ if ( s.type === 'ImportBatchSpecifier' ) {
276
+ return {
277
+ isBatch: true,
278
+ name: s.name.name,
279
+ as: s.name.name
280
+ };
281
+ }
282
+
283
+ id = s.id.name;
284
+
285
+ return {
286
+ isDefault: !!s.default,
287
+ name: s.default ? 'default' : id,
288
+ as: s.name ? s.name.name : id
289
+ };
290
+ })
291
+ };
292
+
293
+ // TODO have different types of imports - batch, default, named
294
+ if ( x.specifiers.length === 0 ) {
295
+ x.isEmpty = true;
296
+ } else if ( x.specifiers.length === 1 && x.specifiers[0].isDefault ) {
297
+ x.isDefault = true;
298
+ x.name = x.specifiers[0].as;
299
+
300
+ } else if ( x.specifiers.length === 1 && x.specifiers[0].isBatch ) {
301
+ x.isBatch = true;
302
+ x.name = x.specifiers[0].name;
303
+ } else {
304
+ x.isNamed = true;
305
+ }
306
+
307
+ return x;
308
+ }
309
+
310
+ /**
311
+ * Generates a representation of an export declaration
312
+ * @param {object} node - the original AST node
313
+ * @param {string} source - the original source code
314
+ * @returns {object}
315
+ */
316
+ function processExport ( node, source ) {
317
+ var result, d;
318
+
319
+ result = {
320
+ node: node,
321
+ start: node.start,
322
+ end: node.end
323
+ };
324
+
325
+ if ( d = node.declaration ) {
326
+ result.value = source.slice( d.start, d.end );
327
+ result.valueStart = d.start;
328
+
329
+ // Case 1: `export var foo = 'bar'`
330
+ if ( d.type === 'VariableDeclaration' ) {
331
+ result.hasDeclaration = true; // TODO remove in favour of result.type
332
+ result.type = 'varDeclaration';
333
+ result.name = d.declarations[0].id.name;
334
+ }
335
+
336
+ // Case 2: `export function foo () {...}`
337
+ else if ( d.type === 'FunctionDeclaration' ) {
338
+ result.hasDeclaration = true; // TODO remove in favour of result.type
339
+ result.type = 'namedFunction';
340
+ result.isDefault = !!node.default;
341
+ result.name = d.id.name;
342
+ }
343
+
344
+ else if ( d.type === 'FunctionExpression' ) {
345
+ result.hasDeclaration = true; // TODO remove in favour of result.type
346
+ result.isDefault = true;
347
+
348
+ // Case 3: `export default function foo () {...}`
349
+ if ( d.id ) {
350
+ result.type = 'namedFunction';
351
+ result.name = d.id.name;
352
+ }
353
+
354
+ // Case 4: `export default function () {...}`
355
+ else {
356
+ result.type = 'anonFunction';
357
+ }
358
+ }
359
+
360
+ // Case 5: `export class Foo {...}`
361
+ else if ( d.type === 'ClassDeclaration' ) {
362
+ result.hasDeclaration = true; // TODO remove in favour of result.type
363
+ result.type = 'namedClass';
364
+ result.isDefault = !!node.default;
365
+ result.name = d.id.name;
366
+ }
367
+
368
+ else if ( d.type === 'ClassExpression' ) {
369
+ result.hasDeclaration = true; // TODO remove in favour of result.type
370
+ result.isDefault = true;
371
+
372
+ // Case 6: `export default class Foo {...}`
373
+ if ( d.id ) {
374
+ result.type = 'namedClass';
375
+ result.name = d.id.name;
376
+ }
377
+
378
+ // Case 7: `export default class {...}`
379
+ else {
380
+ result.type = 'anonClass';
381
+ }
382
+ }
383
+
384
+ // Case 8: `export default 1 + 2`
385
+ else {
386
+ result.type = 'expression';
387
+ result.isDefault = true;
388
+ result.name = 'default';
389
+ }
390
+ }
391
+
392
+ // Case 9: `export { foo, bar };`
393
+ else {
394
+ result.type = 'named';
395
+ result.specifiers = node.specifiers.map( function(s ) {return { name: s.id.name }} ); // TODO as?
396
+ }
397
+
398
+ return result;
399
+ }
400
+
401
+ function getUnscopedNames ( mod ) {
402
+ var unscoped = [], importedNames, scope;
403
+
404
+ function imported ( name ) {
405
+ if ( !importedNames ) {
406
+ importedNames = {};
407
+ mod.imports.forEach( function(i ) {
408
+ !i.passthrough && i.specifiers.forEach( function(s ) {
409
+ importedNames[ s.as ] = true;
410
+ });
411
+ });
412
+ }
413
+ return hasOwnProp.call( importedNames, name );
414
+ }
415
+
416
+ estraverse.traverse( mod.ast, {
417
+ enter: function ( node ) {
418
+ // we're only interested in references, not property names etc
419
+ if ( node._skip ) return this.skip();
420
+
421
+ if ( node._scope ) {
422
+ scope = node._scope;
423
+ }
424
+
425
+ if ( node.type === 'Identifier' &&
426
+ !scope.contains( node.name ) &&
427
+ !imported( node.name ) &&
428
+ !~unscoped.indexOf( node.name ) ) {
429
+ unscoped.push( node.name );
430
+ }
431
+ },
432
+
433
+ leave: function ( node ) {
434
+ if ( node.type === 'Program' ) {
435
+ return;
436
+ }
437
+
438
+ if ( node._scope ) {
439
+ scope = scope.parent;
440
+ }
441
+ }
442
+ });
443
+
444
+ return unscoped;
445
+ }
446
+
447
+ var reserved = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield'.split( ' ' );
448
+
449
+ /**
450
+ * Generates a sanitized (i.e. valid identifier) name from a module ID
451
+ * @param {string} id - a module ID, or part thereof
452
+ * @returns {string}
453
+ */
454
+ function sanitize ( name ) {
455
+ name = name.replace( /[^a-zA-Z0-9_$]/g, '_' );
456
+ if ( /[^a-zA-Z_$]/.test( name[0] ) ) {
457
+ name = '_' + name;
458
+ }
459
+
460
+ if ( ~reserved.indexOf( name ) ) {
461
+ name = '_' + name;
462
+ }
463
+
464
+ return name;
465
+ }
466
+
467
+ var pathSplitRE = /\/|\\/;
468
+ function splitPath ( path ) {
469
+ return path.split( pathSplitRE );
470
+ }
471
+
472
+ function getModuleNameHelper ( userFn ) {var usedNames = arguments[1];if(usedNames === void 0)usedNames = {};
473
+ var nameById = {}, getModuleName;
474
+
475
+ getModuleName = function(x ) {
476
+ var moduleId, parts, i, prefix = '', name, candidate;
477
+
478
+ moduleId = x.path;
479
+
480
+ // use existing value
481
+ if ( hasOwnProp.call( nameById, moduleId ) ) {
482
+ return nameById[ moduleId ];
483
+ }
484
+
485
+ // if user supplied a function, defer to it
486
+ if ( userFn && ( name = userFn( moduleId ) ) ) {
487
+ name = sanitize( name );
488
+
489
+ if ( hasOwnProp.call( usedNames, name ) ) {
490
+ // TODO write a test for this
491
+ throw new Error( 'Naming collision: module ' + moduleId + ' cannot be called ' + name );
492
+ }
493
+ }
494
+
495
+ else if ( x.isDefault || x.isBatch ) {
496
+ name = x.name;
497
+ }
498
+
499
+ else {
500
+ parts = splitPath( moduleId );
501
+ i = parts.length;
502
+
503
+ do {
504
+ while ( i-- ) {
505
+ candidate = prefix + sanitize( parts.slice( i ).join( '__' ) );
506
+
507
+ if ( !hasOwnProp.call( usedNames, candidate ) ) {
508
+ name = candidate;
509
+ break;
510
+ }
511
+ }
512
+
513
+ prefix += '_';
514
+ } while ( !name );
515
+ }
516
+
517
+ usedNames[ name ] = true;
518
+ nameById[ moduleId ] = name;
519
+
520
+ return name;
521
+ };
522
+
523
+ return getModuleName;
524
+ }
525
+
526
+ function getStandaloneModule ( options ) {var $D$0;
527
+ var mod, imports, exports, conflicts = {};
528
+
529
+ mod = {
530
+ body: new MagicString( options.source ),
531
+ ast: acorn.parse( options.source, {
532
+ ecmaVersion: 6,
533
+ locations: true
534
+ })
535
+ };
536
+
537
+ imports = ($D$0 = findImportsAndExports( mod, options.source, mod.ast ))[0], exports = $D$0[1], $D$0;
538
+
539
+
540
+ mod.imports = imports;
541
+ mod.exports = exports;
542
+
543
+ if ( options.strict ) {
544
+ annotateAst( mod.ast );
545
+
546
+ // TODO there's probably an easier way to get this array
547
+ Object.keys( mod.ast._declared ).concat( getUnscopedNames( mod ) ).forEach( function(n ) {
548
+ conflicts[n] = true;
549
+ });
550
+ } else {
551
+ conflicts = mod.ast._declared;
552
+ }
553
+
554
+ mod.getName = getModuleNameHelper( options.getModuleName, conflicts );
555
+
556
+ return mod;
557
+ ;$D$0 = void 0}
558
+
559
+ function resolveId ( importPath, importerPath ) {
560
+ var resolved, importerParts, importParts;
561
+
562
+ if ( importPath[0] !== '.' ) {
563
+ resolved = importPath;
564
+ } else {
565
+ importerParts = splitPath( importerPath );
566
+ importParts = splitPath( importPath );
567
+
568
+ if ( importParts[0] === '.' ) {
569
+ importParts.shift();
570
+ }
571
+
572
+ importerParts.pop(); // get dirname
573
+ while ( importParts[0] === '..' ) {
574
+ importParts.shift();
575
+ importerParts.pop();
576
+ }
577
+
578
+ while ( importParts[0] === '.' ) {
579
+ importParts.shift();
580
+ }
581
+
582
+ resolved = importerParts.concat( importParts ).join( '/' );
583
+ }
584
+
585
+ return resolved.replace( /\.js$/, '' );
586
+ }
587
+
588
+ function resolveAgainst ( importerPath ) {
589
+ return function ( importPath ) {
590
+ return resolveId( importPath, importerPath );
591
+ };
592
+ }
593
+
594
+ function sortModules ( entry, moduleLookup ) {
595
+ var seen = {},
596
+ ordered = [];
597
+
598
+ function visit ( mod ) {
599
+ // ignore external modules, and modules we've
600
+ // already included
601
+ if ( !mod || hasOwnProp.call( seen, mod.id ) ) {
602
+ return;
603
+ }
604
+
605
+ seen[ mod.id ] = true;
606
+
607
+ mod.imports.forEach( function(x ) {
608
+ visit( moduleLookup[ x.id ] );
609
+ });
610
+
611
+ ordered.push( mod );
612
+ }
613
+
614
+ visit( entry );
615
+
616
+ return ordered;
617
+ }
618
+
619
+ function resolveChains ( modules, moduleLookup ) {
620
+ var chains = {};
621
+
622
+ // First pass - resolving intra-module chains
623
+ modules.forEach( function(mod ) {
624
+ var origin = {};
625
+
626
+ mod.imports.forEach( function(x ) {
627
+ x.specifiers.forEach( function(s ) {
628
+ if ( s.isBatch ) {
629
+ // if this is an internal module, we need to tell that module that
630
+ // it needs to export an object full of getters
631
+ if ( hasOwnProp.call( moduleLookup, x.id ) ) {
632
+ moduleLookup[ x.id ]._exportsNamespace = true;
633
+ }
634
+
635
+ return; // TODO can batch imports be chained?
636
+ }
637
+
638
+ origin[ s.as ] = x.id + '@' + s.name;
639
+ });
640
+ });
641
+
642
+ mod.exports.forEach( function(x ) {
643
+ if ( !x.specifiers ) return;
644
+
645
+ x.specifiers.forEach( function(s ) {
646
+ if ( hasOwnProp.call( origin, s.name ) ) {
647
+ chains[ mod.id + '@' + s.name ] = origin[ s.name ];
648
+ }
649
+ });
650
+ });
651
+ });
652
+
653
+ return chains;
654
+ }
655
+
656
+ // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
657
+ // we add `exports` to this list, to avoid conflicst
658
+ var builtins = 'Array ArrayBuffer DataView Date Error EvalError Float32Array Float64Array Function Generator GeneratorFunction Infinity Int16Array Int32Array Int8Array InternalError Intl Iterator JSON Map Math NaN Number Object ParallelArray Promise Proxy RangeError ReferenceError Reflect RegExp Set StopIteration String Symbol SyntaxError TypeError TypedArray URIError Uint16Array Uint32Array Uint8Array Uint8ClampedArray WeakMap WeakSet decodeURI decodeURIComponent encodeURI encodeURIComponent escape eval exports isFinite isNaN null parseFloat parseInt undefined unescape uneval'.split( ' ' );
659
+
660
+ function getUniqueNames ( modules, externalModules, userNames ) {
661
+ var names = {}, used = {};
662
+
663
+ // copy builtins
664
+ builtins.forEach( function(n ) {return used[n] = true} );
665
+
666
+ // copy user-specified names
667
+ if ( userNames ) {
668
+ Object.keys( userNames ).forEach( function(n ) {
669
+ names[n] = userNames[n];
670
+ used[ userNames[n] ] = true;
671
+ });
672
+ }
673
+
674
+ // infer names from default imports
675
+ modules.forEach( function(mod ) {
676
+ mod.imports.forEach( function(x ) {
677
+ if ( x.isDefault && !hasOwnProp.call( names, x.id ) && !hasOwnProp.call( used, x.name ) ) {
678
+ names[ x.id ] = x.name;
679
+ used[ x.name ] = true;
680
+ }
681
+ });
682
+ });
683
+
684
+ // for the rest, make names as compact as possible without
685
+ // introducing conflicts
686
+ modules.concat( externalModules ).forEach( function(mod ) {
687
+ var parts, i, name;
688
+
689
+ // is this already named?
690
+ if ( hasOwnProp.call( names, mod.id ) ) {
691
+ return;
692
+ }
693
+
694
+ parts = splitPath( mod.id );
695
+
696
+ i = parts.length;
697
+ while ( i-- ) {
698
+ name = sanitize( parts.slice( i ).join( '_' ) );
699
+
700
+ if ( !hasOwnProp.call( used, name ) ) {
701
+ break;
702
+ }
703
+ }
704
+
705
+ while ( hasOwnProp.call( used, name ) ) {
706
+ name = '_' + name;
707
+ }
708
+
709
+ used[ name ] = true;
710
+ names[ mod.id ] = name;
711
+ });
712
+
713
+ return names;
714
+ }
715
+
716
+ function populateExternalModuleImports ( bundle ) {
717
+ bundle.modules.forEach( function(mod ) {
718
+ mod.imports.forEach( function(x ) {
719
+ var externalModule = bundle.externalModuleLookup[ x.id ];
720
+
721
+ if ( !externalModule ) {
722
+ return;
723
+ }
724
+
725
+ x.specifiers.forEach( function(s ) {
726
+ if ( s.isDefault ) {
727
+ externalModule.needsDefault = true;
728
+ } else {
729
+ externalModule.needsNamed = true;
730
+ }
731
+ });
732
+ });
733
+ });
734
+ }
735
+
736
+ function getRenamedImports ( mod ) {
737
+ var renamed = [];
738
+
739
+ mod.imports.forEach( function(x ) {
740
+ if ( x.specifiers ) {
741
+ x.specifiers.forEach( function(s ) {
742
+ if ( s.name !== s.as && !~renamed.indexOf( s.name ) ) {
743
+ renamed.push( s.name );
744
+ }
745
+ });
746
+ }
747
+ });
748
+
749
+ return renamed;
750
+ }
751
+
752
+ function topLevelScopeConflicts ( bundle ) {
753
+ var conflicts = {}, inBundle = {};
754
+
755
+ bundle.modules.forEach( function(mod ) {
756
+ var names = builtins
757
+
758
+ // all top defined identifiers are in top scope
759
+ .concat( mod.ast._topLevelNames )
760
+
761
+ // all unattributed identifiers could collide with top scope
762
+ .concat( getUnscopedNames( mod ) )
763
+
764
+ .concat( getRenamedImports( mod ) );
765
+
766
+ if ( mod._exportsNamespace ) {
767
+ conflicts[ mod.name ] = true;
768
+ }
769
+
770
+ // merge this module's top scope with bundle top scope
771
+ names.forEach( function(name ) {
772
+ if ( hasOwnProp.call( inBundle, name ) ) {
773
+ conflicts[ name ] = true;
774
+ } else {
775
+ inBundle[ name ] = true;
776
+ }
777
+ });
778
+ });
779
+
780
+ return conflicts;
781
+ }
782
+
783
+ function populateIdentifierReplacements ( bundle ) {
784
+ // first, discover conflicts
785
+ var conflicts = topLevelScopeConflicts( bundle );
786
+
787
+ // then figure out what identifiers need to be created
788
+ // for default exports
789
+ bundle.modules.forEach( function(mod ) {
790
+ var x;
791
+
792
+ if ( x = mod.defaultExport ) {
793
+ if ( x.hasDeclaration && x.name ) {
794
+ mod.identifierReplacements.default = hasOwnProp.call( conflicts, x.name ) || otherModulesDeclare( mod, x.name ) ?
795
+ mod.name + '__' + x.name :
796
+ x.name;
797
+ } else {
798
+ mod.identifierReplacements.default = hasOwnProp.call( conflicts, mod.name ) || otherModulesDeclare( mod, mod.name ) ?
799
+ mod.name + '__default' :
800
+ mod.name;
801
+ }
802
+ }
803
+ });
804
+
805
+ // then determine which existing identifiers
806
+ // need to be replaced
807
+ bundle.modules.forEach( function(mod ) {
808
+ var moduleIdentifiers, x;
809
+
810
+ moduleIdentifiers = mod.identifierReplacements;
811
+
812
+ mod.ast._topLevelNames.forEach( function(n ) {
813
+ moduleIdentifiers[n] = hasOwnProp.call( conflicts, n ) ?
814
+ mod.name + '__' + n :
815
+ n;
816
+ });
817
+
818
+ mod.imports.forEach( function(x ) {
819
+ var externalModule;
820
+
821
+ if ( x.passthrough ) {
822
+ return;
823
+ }
824
+
825
+ externalModule = hasOwnProp.call( bundle.externalModuleLookup, x.id ) && bundle.externalModuleLookup[ x.id ];
826
+
827
+ x.specifiers.forEach( function(s ) {
828
+ var moduleId, mod, moduleName, specifierName, replacement, hash, isChained, separatorIndex;
829
+
830
+ moduleId = x.id;
831
+
832
+ if ( s.isBatch ) {
833
+ replacement = ( bundle.moduleLookup[ moduleId ] || bundle.externalModuleLookup[ moduleId ] ).name;
834
+ }
835
+
836
+ else {
837
+ specifierName = s.name;
838
+
839
+ // If this is a chained import, get the origin
840
+ hash = moduleId + '@' + specifierName;
841
+ while ( hasOwnProp.call( bundle.chains, hash ) ) {
842
+ hash = bundle.chains[ hash ];
843
+ isChained = true;
844
+ }
845
+
846
+ if ( isChained ) {
847
+ separatorIndex = hash.indexOf( '@' );
848
+ moduleId = hash.substr( 0, separatorIndex );
849
+ specifierName = hash.substring( separatorIndex + 1 );
850
+ }
851
+
852
+ mod = ( bundle.moduleLookup[ moduleId ] || bundle.externalModuleLookup[ moduleId ] );
853
+ moduleName = mod && mod.name;
854
+
855
+ if ( specifierName === 'default' ) {
856
+ // if it's an external module, always use __default if the
857
+ // bundle also uses named imports
858
+ if ( !!externalModule ) {
859
+ replacement = externalModule.needsNamed ? moduleName + '__default' : moduleName;
860
+ }
861
+
862
+ // TODO We currently need to check for the existence of `mod`, because modules
863
+ // can be skipped. Would be better to replace skipped modules with dummies
864
+ // - see https://github.com/Rich-Harris/esperanto/issues/32
865
+ else if ( mod ) {
866
+ replacement = mod.identifierReplacements.default;
867
+ }
868
+ } else if ( !externalModule ) {
869
+ replacement = hasOwnProp.call( conflicts, specifierName ) ?
870
+ moduleName + '__' + specifierName :
871
+ specifierName;
872
+ } else {
873
+ replacement = moduleName + '.' + specifierName;
874
+ }
875
+ }
876
+
877
+ if ( replacement !== s.as ) {
878
+ moduleIdentifiers[ s.as ] = replacement;
879
+ }
880
+ });
881
+ });
882
+ });
883
+
884
+ function otherModulesDeclare ( mod, replacement ) {
885
+ var i, otherMod;
886
+
887
+ i = bundle.modules.length;
888
+ while ( i-- ) {
889
+ otherMod = bundle.modules[i];
890
+
891
+ if ( mod === otherMod ) {
892
+ continue;
893
+ }
894
+
895
+ if ( hasOwnProp.call( otherMod.ast._declared, replacement ) ) {
896
+ return true;
897
+ }
898
+ }
899
+ }
900
+ }
901
+
902
+ function resolveExports ( bundle ) {
903
+ var bundleExports = {};
904
+
905
+ bundle.entryModule.exports.forEach( function(x ) {
906
+ var name;
907
+
908
+ if ( x.specifiers ) {
909
+ x.specifiers.forEach( function(s ) {
910
+ var hash = bundle.entryModule.id + '@' + s.name,
911
+ split,
912
+ moduleId,
913
+ name;
914
+
915
+ while ( bundle.chains[ hash ] ) {
916
+ hash = bundle.chains[ hash ];
917
+ }
918
+
919
+ split = hash.split( '@' );
920
+ moduleId = split[0];
921
+ name = split[1];
922
+
923
+ addExport( moduleId, name, s.name );
924
+
925
+ // if ( !bundleExports[ moduleId ] ) {
926
+ // bundleExports[ moduleId ] = {};
927
+ // }
928
+
929
+ // bundleExports[ moduleId ][ name ] = s.name;
930
+ });
931
+ }
932
+
933
+ else if ( !x.isDefault && ( name = x.name ) ) {
934
+ addExport( bundle.entry, name, name );
935
+ }
936
+ });
937
+
938
+ function addExport ( moduleId, name, as ) {
939
+ if ( !bundleExports[ moduleId ] ) {
940
+ bundleExports[ moduleId ] = {};
941
+ }
942
+
943
+ bundleExports[ moduleId ][ name ] = as;
944
+ }
945
+
946
+ return bundleExports;
947
+ }
948
+
949
+ /**
950
+ * Scans an array of imports, and determines which identifiers
951
+ are readonly, and which cannot be assigned to. For example
952
+ you cannot `import foo from 'foo'` then do `foo = 42`, nor
953
+ can you `import * from 'foo'` then do `foo.answer = 42`
954
+ * @param {array} imports - the array of imports
955
+ * @returns {array} [ importedBindings, importedNamespaces ]
956
+ */
957
+ function getReadOnlyIdentifiers ( imports ) {
958
+ var importedBindings = {}, importedNamespaces = {};
959
+
960
+ imports.forEach( function(x ) {
961
+ if ( x.passthrough ) return;
962
+
963
+ x.specifiers.forEach( function(s ) {
964
+ if ( s.isBatch ) {
965
+ importedNamespaces[ s.as ] = true;
966
+ } else {
967
+ importedBindings[ s.as ] = true;
968
+ }
969
+ });
970
+ });
971
+
972
+ return [ importedBindings, importedNamespaces ];
973
+ }
974
+
975
+ var bindingMessage = 'Cannot reassign imported binding ',
976
+ namespaceMessage = 'Cannot reassign imported binding of namespace ';
977
+
978
+ function disallowIllegalReassignment ( node, importedBindings, importedNamespaces, scope ) {
979
+ var assignee, name, isNamespaceAssignment;
980
+
981
+ if ( node.type === 'AssignmentExpression' ) {
982
+ assignee = node.left;
983
+ } else if ( node.type === 'UpdateExpression' ) {
984
+ assignee = node.argument;
985
+ } else {
986
+ return; // not an assignment
987
+ }
988
+
989
+ if ( assignee.type === 'MemberExpression' ) {
990
+ assignee = assignee.object;
991
+ isNamespaceAssignment = true;
992
+ }
993
+
994
+ if ( assignee.type !== 'Identifier' ) {
995
+ return; // not assigning to a binding
996
+ }
997
+
998
+ name = assignee.name;
999
+
1000
+ if ( hasOwnProp.call( isNamespaceAssignment ? importedNamespaces : importedBindings, name ) && !scope.contains( name ) ) {
1001
+ throw new Error( ( isNamespaceAssignment ? namespaceMessage : bindingMessage ) + '`' + name + '`' );
1002
+ }
1003
+ }
1004
+
1005
+ function rewriteIdentifiers ( body, node, identifierReplacements, scope ) {
1006
+ var name, replacement;
1007
+
1008
+ if ( node.type === 'Identifier' ) {
1009
+ name = node.name;
1010
+ replacement = hasOwnProp.call( identifierReplacements, name ) && identifierReplacements[ name ];
1011
+
1012
+ // TODO unchanged identifiers shouldn't have got this far -
1013
+ // remove the `replacement !== name` safeguard once that's the case
1014
+ if ( replacement && replacement !== name && !scope.contains( name, true ) ) {
1015
+ // rewrite
1016
+ body.replace( node.start, node.end, replacement );
1017
+ }
1018
+ }
1019
+ }
1020
+
1021
+ function rewriteExportAssignments ( body, node, exports, scope, alreadyExported, isTopLevelNode, capturedUpdates ) {
1022
+ var assignee, name, exportAs;
1023
+
1024
+ if ( node.type === 'AssignmentExpression' ) {
1025
+ assignee = node.left;
1026
+ } else if ( node.type === 'UpdateExpression' ) {
1027
+ assignee = node.argument;
1028
+ } else {
1029
+ return; // not an assignment
1030
+ }
1031
+
1032
+ if ( assignee.type !== 'Identifier' ) {
1033
+ return;
1034
+ }
1035
+
1036
+ name = assignee.name;
1037
+
1038
+ if ( scope.contains( name, true ) ) {
1039
+ return; // shadows an export
1040
+ }
1041
+
1042
+ if ( exports && hasOwnProp.call( exports, name ) && ( exportAs = exports[ name ] ) ) {
1043
+ if ( !!capturedUpdates ) {
1044
+ capturedUpdates.push({
1045
+ name: name,
1046
+ exportAs: exportAs
1047
+ });
1048
+ return;
1049
+ }
1050
+
1051
+ // special case - increment/decrement operators
1052
+ if ( node.operator === '++' || node.operator === '--' ) {
1053
+ body.replace( node.end, node.end, ((", exports." + exportAs) + (" = " + name) + "") );
1054
+ } else {
1055
+ body.replace( node.start, node.start, (("exports." + exportAs) + " = ") );
1056
+ }
1057
+
1058
+ // keep track of what we've already exported - we don't need to
1059
+ // export it again later
1060
+ if ( isTopLevelNode ) {
1061
+ alreadyExported[ name ] = true;
1062
+ }
1063
+ }
1064
+ }
1065
+
1066
+ function traverseAst ( ast, body, identifierReplacements, importedBindings, importedNamespaces, exportNames, alreadyExported ) {
1067
+ var scope = ast._scope,
1068
+ blockScope = ast._blockScope,
1069
+ capturedUpdates = null,
1070
+ previousCapturedUpdates = null;
1071
+
1072
+ estraverse.traverse( ast, {
1073
+ enter: function ( node ) {
1074
+ // we're only interested in references, not property names etc
1075
+ if ( node._skip ) return this.skip();
1076
+
1077
+ if ( node._scope ) {
1078
+ scope = node._scope;
1079
+ } else if ( node._blockScope ) {
1080
+ blockScope = node._blockScope;
1081
+ }
1082
+
1083
+ // Special case: if you have a variable declaration that updates existing
1084
+ // bindings as a side-effect, e.g. `var a = b++`, where `b` is an exported
1085
+ // value, we can't simply append `exports.b = b` to the update (as we
1086
+ // normally would) because that would be syntactically invalid. Instead,
1087
+ // we capture the change and update the export (and any others) after the
1088
+ // variable declaration
1089
+ if ( node.type === 'VariableDeclaration' ) {
1090
+ previousCapturedUpdates = capturedUpdates;
1091
+ capturedUpdates = [];
1092
+ return;
1093
+ }
1094
+
1095
+ // Catch illegal reassignments
1096
+ disallowIllegalReassignment( node, importedBindings, importedNamespaces, scope );
1097
+
1098
+ // Rewrite assignments to exports. This call may mutate `alreadyExported`
1099
+ // and `capturedUpdates`, which are used elsewhere
1100
+ rewriteExportAssignments( body, node, exportNames, scope, alreadyExported, scope === ast._scope, capturedUpdates );
1101
+
1102
+ // Replace identifiers
1103
+ rewriteIdentifiers( body, node, identifierReplacements, scope );
1104
+
1105
+ // Replace top-level this with undefined ES6 8.1.1.5.4
1106
+ if ( node.type === 'ThisExpression' && node._topLevel ) {
1107
+ body.replace( node.start, node.end, 'undefined' );
1108
+ }
1109
+ },
1110
+
1111
+ leave: function ( node ) {
1112
+ // Special case - see above
1113
+ if ( node.type === 'VariableDeclaration' ) {
1114
+ if ( capturedUpdates.length ) {
1115
+ body.insert( node.end, capturedUpdates.map( exportCapturedUpdate ).join( '' ) );
1116
+ }
1117
+
1118
+ capturedUpdates = previousCapturedUpdates;
1119
+ }
1120
+
1121
+ if ( node._scope ) {
1122
+ scope = scope.parent;
1123
+ } else if ( node._blockScope ) {
1124
+ blockScope = blockScope.parent;
1125
+ }
1126
+ }
1127
+ });
1128
+ }
1129
+
1130
+ function exportCapturedUpdate ( c ) {
1131
+ return ((" exports." + (c.name)) + (" = " + (c.exportAs)) + ";");
1132
+ }
1133
+
1134
+ function transformBody__transformBody ( bundle, mod, body ) {var $D$1;
1135
+ var identifierReplacements,
1136
+ importedBindings,
1137
+ importedNamespaces,
1138
+ exportNames,
1139
+ alreadyExported = {},
1140
+ shouldExportEarly = {},
1141
+ exportBlock;
1142
+
1143
+ identifierReplacements = mod.identifierReplacements;
1144
+ importedBindings = ($D$1 = getReadOnlyIdentifiers( mod.imports ))[0], importedNamespaces = $D$1[1], $D$1;
1145
+
1146
+ exportNames = hasOwnProp.call( bundle.exports, mod.id ) && bundle.exports[ mod.id ];
1147
+
1148
+ traverseAst( mod.ast, body, identifierReplacements, importedBindings, importedNamespaces, exportNames, alreadyExported );
1149
+
1150
+ // Remove import statements
1151
+ mod.imports.forEach( function(x ) {
1152
+ if ( !x.passthrough ) {
1153
+ body.remove( x.start, x.next );
1154
+ }
1155
+ });
1156
+
1157
+ // Remove export statements
1158
+ mod.exports.forEach( function(x ) {
1159
+ var name;
1160
+
1161
+ if ( x.isDefault ) {
1162
+ if ( x.type === 'namedFunction' || x.type === 'namedClass' ) {
1163
+ // if you have a default export like
1164
+ //
1165
+ // export default function foo () {...}
1166
+ //
1167
+ // you need to rewrite it as
1168
+ //
1169
+ // function foo () {...}
1170
+ // exports.default = foo;
1171
+ //
1172
+ // as the `foo` reference may be used elsewhere
1173
+
1174
+ // remove the `export default `, keep the rest
1175
+ body.remove( x.start, x.valueStart );
1176
+ }
1177
+
1178
+ else if ( x.node.declaration && ( name = x.node.declaration.name ) ) {
1179
+ if ( name === identifierReplacements.default ) {
1180
+ body.remove( x.start, x.end );
1181
+ } else {
1182
+ body.replace( x.start, x.end, (("var " + (identifierReplacements.default)) + (" = " + (identifierReplacements[name])) + ";") );
1183
+ }
1184
+ }
1185
+
1186
+ else {
1187
+ body.replace( x.start, x.valueStart, (("var " + (identifierReplacements.default)) + " = ") );
1188
+ }
1189
+
1190
+ return;
1191
+ }
1192
+
1193
+ if ( x.hasDeclaration ) {
1194
+ if ( x.type === 'namedFunction' ) {
1195
+ shouldExportEarly[ x.name ] = true; // TODO what about `function foo () {}; export { foo }`?
1196
+ }
1197
+
1198
+ body.remove( x.start, x.valueStart );
1199
+ } else {
1200
+ body.remove( x.start, x.next );
1201
+ }
1202
+ });
1203
+
1204
+ // If this module exports a namespace - i.e. another module does
1205
+ // `import * from 'foo'` - then we need to make all this module's
1206
+ // exports available, using Object.defineProperty
1207
+ var indentStr = body.getIndentString();
1208
+ if ( mod._exportsNamespace ) {
1209
+ var namespaceExportBlock = (("var " + (mod.name)) + " = {\n"),
1210
+ namespaceExports = [];
1211
+
1212
+ mod.exports.forEach( function(x ) {
1213
+ if ( x.hasDeclaration ) {
1214
+ namespaceExports.push( indentStr + (("get " + (x.name)) + (" () { return " + (identifierReplacements[x.name])) + "; }") );
1215
+ }
1216
+
1217
+ else if ( x.isDefault ) {
1218
+ namespaceExports.push( indentStr + (("get default () { return " + (identifierReplacements.default)) + "; }") );
1219
+ }
1220
+
1221
+ else {
1222
+ x.specifiers.forEach( function(s ) {
1223
+ namespaceExports.push( indentStr + (("get " + (s.name)) + (" () { return " + (s.name)) + "; }") );
1224
+ });
1225
+ }
1226
+ });
1227
+
1228
+ namespaceExportBlock += namespaceExports.join( ',\n' ) + '\n};\n\n';
1229
+
1230
+ body.prepend( namespaceExportBlock );
1231
+ }
1232
+
1233
+ // If this module is responsible for one of the bundle's exports
1234
+ // (it doesn't have to be the entry module, which could re-export
1235
+ // a binding from another module), we write exports here
1236
+ if ( exportNames ) {
1237
+ exportBlock = [];
1238
+
1239
+ Object.keys( exportNames ).forEach( function(name ) {
1240
+ var exportAs;
1241
+
1242
+ if ( !alreadyExported[ name ] ) {
1243
+ exportAs = exportNames[ name ];
1244
+ exportBlock.push( (("exports." + exportAs) + (" = " + (identifierReplacements[name])) + ";") );
1245
+ }
1246
+ });
1247
+
1248
+ if ( exportBlock.length ) {
1249
+ body.trim().append( '\n\n' + exportBlock.join( '\n' ) );
1250
+ }
1251
+ }
1252
+
1253
+ return body.trim();
1254
+ ;$D$1 = void 0}
1255
+
1256
+ function combine ( bundle ) {
1257
+ var body;
1258
+
1259
+ body = new MagicString.Bundle({
1260
+ separator: '\n\n'
1261
+ });
1262
+
1263
+ // populate names
1264
+ var uniqueNames = getUniqueNames( bundle.modules, bundle.externalModules, bundle.names );
1265
+ var setName = function(mod ) {return mod.name = uniqueNames[ mod.id ]};
1266
+ bundle.modules.forEach( setName );
1267
+ bundle.externalModules.forEach( setName );
1268
+
1269
+ // determine which specifiers are imported from
1270
+ // external modules
1271
+ populateExternalModuleImports( bundle );
1272
+
1273
+ // determine which identifiers need to be replaced
1274
+ // inside this bundle
1275
+ populateIdentifierReplacements( bundle );
1276
+
1277
+ bundle.exports = resolveExports( bundle );
1278
+
1279
+ bundle.modules.forEach( function(mod ) {
1280
+ // verify that this module doesn't import non-exported identifiers
1281
+ mod.imports.forEach( function(x ) {
1282
+ var importedModule = bundle.moduleLookup[ x.id ];
1283
+
1284
+ if ( !importedModule || x.isBatch ) {
1285
+ return;
1286
+ }
1287
+
1288
+ x.specifiers.forEach( function(s ) {
1289
+ if ( !importedModule.doesExport[ s.name ] ) {
1290
+ throw new Error( 'Module ' + importedModule.id + ' does not export ' + s.name + ' (imported by ' + mod.id + ')' );
1291
+ }
1292
+ });
1293
+ });
1294
+
1295
+ body.addSource({
1296
+ filename: path.resolve( bundle.base, mod.file ),
1297
+ content: transformBody__transformBody( bundle, mod, mod.body.clone() ),
1298
+ indentExclusionRanges: mod.ast._templateLiteralRanges
1299
+ });
1300
+ });
1301
+
1302
+ bundle.body = body;
1303
+ }
1304
+
1305
+ function getModule ( mod ) {var $D$2;
1306
+ var imports, exports;
1307
+
1308
+ mod.body = new MagicString( mod.source );
1309
+
1310
+ try {
1311
+ mod.ast = acorn.parse( mod.source, {
1312
+ ecmaVersion: 6,
1313
+ locations: true
1314
+ });
1315
+
1316
+ annotateAst( mod.ast );
1317
+ } catch ( err ) {
1318
+ // If there's a parse error, attach file info
1319
+ // before throwing the error
1320
+ if ( err.loc ) {
1321
+ err.file = mod.path;
1322
+ }
1323
+
1324
+ throw err;
1325
+ }
1326
+
1327
+ imports = ($D$2 = findImportsAndExports( mod, mod.source, mod.ast ))[0], exports = $D$2[1], $D$2;
1328
+
1329
+ mod.imports = imports;
1330
+ mod.exports = exports;
1331
+
1332
+ // identifiers to replace within this module
1333
+ // (gets filled in later, once bundle is combined)
1334
+ mod.identifierReplacements = {};
1335
+
1336
+ // collect exports by name, for quick lookup when verifying
1337
+ // that this module exports a given identifier
1338
+ mod.doesExport = {};
1339
+
1340
+ exports.forEach( function(x ) {
1341
+ if ( x.isDefault ) {
1342
+ mod.doesExport.default = true;
1343
+ }
1344
+
1345
+ else if ( x.name ) {
1346
+ mod.doesExport[ x.name ] = true;
1347
+ }
1348
+
1349
+ else if ( x.specifiers ) {
1350
+ x.specifiers.forEach( function(s ) {
1351
+ mod.doesExport[ s.name ] = true;
1352
+ });
1353
+ }
1354
+
1355
+ else {
1356
+ throw new Error( 'Unexpected export type' );
1357
+ }
1358
+ });
1359
+
1360
+ return mod;
1361
+ ;$D$2 = void 0}
1362
+
1363
+ var getBundle__Promise = sander.Promise;
1364
+
1365
+ function getBundle ( options ) {
1366
+ var entry = options.entry.replace( /\.js$/, '' ),
1367
+ modules = [],
1368
+ moduleLookup = {},
1369
+ promiseById = {},
1370
+ skip = options.skip,
1371
+ names = options.names,
1372
+ base = ( options.base ? path.resolve( options.base ) : process.cwd() ) + '/',
1373
+ externalModules = [],
1374
+ externalModuleLookup = {};
1375
+
1376
+ if ( !entry.indexOf( base ) ) {
1377
+ entry = entry.substring( base.length );
1378
+ }
1379
+
1380
+ return fetchModule( entry ).then( function() {
1381
+ var entryModule, bundle;
1382
+
1383
+ entryModule = moduleLookup[ entry ];
1384
+ modules = sortModules( entryModule, moduleLookup ); // TODO is this necessary? surely it's already sorted because of the fetch order? or do we need to prevent parallel reads?
1385
+
1386
+ bundle = {
1387
+ entry: entry,
1388
+ entryModule: entryModule,
1389
+ base: base,
1390
+ modules: modules,
1391
+ moduleLookup: moduleLookup,
1392
+ externalModules: externalModules,
1393
+ externalModuleLookup: externalModuleLookup,
1394
+ skip: skip,
1395
+ names: names,
1396
+ chains: resolveChains( modules, moduleLookup )
1397
+ };
1398
+
1399
+ combine( bundle );
1400
+
1401
+ return bundle;
1402
+ });
1403
+
1404
+ function fetchModule ( moduleId ) {
1405
+ var modulePath;
1406
+
1407
+ modulePath = path.resolve( base, moduleId + '.js' );
1408
+
1409
+ if ( !hasOwnProp.call( promiseById, moduleId ) ) {
1410
+ promiseById[ moduleId ] = sander.readFile( modulePath ).catch( function ( err ) {
1411
+ if ( err.code === 'ENOENT' ) {
1412
+ modulePath = modulePath.replace( /\.js$/, '/index.js' );
1413
+ return sander.readFile( modulePath );
1414
+ }
1415
+
1416
+ throw err;
1417
+ }).then( function ( source ) {
1418
+ source = String( source );
1419
+
1420
+ if ( options.transform ) {
1421
+ source = options.transform( source, modulePath );
1422
+
1423
+ if ( typeof source !== 'string' && !isThenable( source ) ) {
1424
+ throw new Error( 'transform should return String or Promise' );
1425
+ }
1426
+ }
1427
+
1428
+ return source;
1429
+ }).then( function ( source ) {
1430
+ var module, promises;
1431
+
1432
+ module = getModule({
1433
+ source: source,
1434
+ id: moduleId,
1435
+ file: modulePath.substring( base.length ),
1436
+ path: modulePath
1437
+ });
1438
+
1439
+ modules.push( module );
1440
+ moduleLookup[ moduleId ] = module;
1441
+
1442
+ promises = module.imports.map( function(x ) {
1443
+ x.id = resolveId( x.path, module.file );
1444
+
1445
+ if ( x.id === moduleId ) {
1446
+ throw new Error( 'A module (' + moduleId + ') cannot import itself' );
1447
+ }
1448
+
1449
+ // Some modules can be skipped
1450
+ if ( skip && ~skip.indexOf( x.id ) ) {
1451
+ return;
1452
+ }
1453
+
1454
+ // short-circuit cycles
1455
+ if ( hasOwnProp.call( promiseById, x.id ) ) {
1456
+ return;
1457
+ }
1458
+
1459
+ return fetchModule( x.id );
1460
+ });
1461
+
1462
+ return getBundle__Promise.all( promises );
1463
+ }).catch( function ( err ) {
1464
+ var externalModule;
1465
+
1466
+ if ( err.code === 'ENOENT' ) {
1467
+ if ( moduleId === entry ) {
1468
+ throw new Error( 'Could not find entry module (' + entry + ')' );
1469
+ }
1470
+
1471
+ // Most likely an external module
1472
+ if ( !hasOwnProp.call( externalModuleLookup, moduleId ) ) {
1473
+ externalModule = {
1474
+ id: moduleId
1475
+ };
1476
+
1477
+ externalModules.push( externalModule );
1478
+ externalModuleLookup[ moduleId ] = externalModule;
1479
+ }
1480
+ } else {
1481
+ throw err;
1482
+ }
1483
+ });
1484
+ }
1485
+
1486
+ return promiseById[ moduleId ];
1487
+ }
1488
+ }
1489
+
1490
+ function isThenable ( obj ) {
1491
+ return obj && typeof obj.then === 'function';
1492
+ }
1493
+
1494
+ function transformExportDeclaration ( declaration, body ) {
1495
+ var exportedValue;
1496
+
1497
+ if ( declaration ) {
1498
+ switch ( declaration.type ) {
1499
+ case 'namedFunction':
1500
+ case 'namedClass':
1501
+ body.remove( declaration.start, declaration.valueStart );
1502
+ exportedValue = declaration.name;
1503
+ break;
1504
+
1505
+ case 'anonFunction':
1506
+ case 'anonClass':
1507
+ if ( declaration.isFinal ) {
1508
+ body.replace( declaration.start, declaration.valueStart, 'return ' );
1509
+ } else {
1510
+ body.replace( declaration.start, declaration.valueStart, 'var __export = ' );
1511
+ exportedValue = '__export';
1512
+ }
1513
+
1514
+ // add semi-colon, if necessary
1515
+ if ( declaration.value.slice( -1 ) !== ';' ) {
1516
+ body.insert( declaration.end, ';' );
1517
+ }
1518
+
1519
+ break;
1520
+
1521
+ case 'expression':
1522
+ body.remove( declaration.start, declaration.next );
1523
+ exportedValue = declaration.value;
1524
+ break;
1525
+
1526
+ default:
1527
+ throw new Error( 'Unexpected export type' );
1528
+ }
1529
+
1530
+ if ( exportedValue ) {
1531
+ body.append( '\nreturn ' + exportedValue + ';' );
1532
+ }
1533
+ }
1534
+ }
1535
+
1536
+ var warned = {};
1537
+
1538
+ function packageResult ( body, options, methodName, isBundle ) {
1539
+ var code, map;
1540
+
1541
+ // wrap output
1542
+ if ( options.banner ) body.prepend( options.banner );
1543
+ if ( options.footer ) body.append( options.footer );
1544
+
1545
+ code = body.toString();
1546
+
1547
+ if ( !!options.sourceMap ) {
1548
+ if ( !options.sourceMapFile || ( !isBundle && !options.sourceMapSource ) ) {
1549
+ throw new Error( 'You must provide `sourceMapSource` and `sourceMapFile` options' );
1550
+ }
1551
+
1552
+ map = body.generateMap({
1553
+ includeContent: true,
1554
+ hires: true,
1555
+ file: options.sourceMapFile,
1556
+ source: !isBundle ? getRelativePath( options.sourceMapFile, options.sourceMapSource ) : null
1557
+ });
1558
+
1559
+ if ( options.sourceMap === 'inline' ) {
1560
+ code += '\n//# sourceMa' + 'ppingURL=' + map.toUrl();
1561
+ map = null;
1562
+ } else {
1563
+ code += '\n//# sourceMa' + 'ppingURL=./' + splitPath( options.sourceMapFile ).pop() + '.map';
1564
+ }
1565
+ } else {
1566
+ map = null;
1567
+ }
1568
+
1569
+ return {
1570
+ code: code,
1571
+ map: map,
1572
+ toString: function () {
1573
+ if ( !warned[ methodName ] ) {
1574
+ console.log( 'Warning: esperanto.' + methodName + '() returns an object with a \'code\' property. You should use this instead of using the returned value directly' );
1575
+ warned[ methodName ] = true;
1576
+ }
1577
+
1578
+ return code;
1579
+ }
1580
+ };
1581
+ }
1582
+
1583
+ function getRelativePath ( from, to ) {
1584
+ var fromParts, toParts, i;
1585
+
1586
+ fromParts = splitPath( from );
1587
+ toParts = splitPath( to );
1588
+
1589
+ fromParts.pop(); // get dirname
1590
+
1591
+ while ( fromParts[0] === toParts[0] ) {
1592
+ fromParts.shift();
1593
+ toParts.shift();
1594
+ }
1595
+
1596
+ if ( fromParts.length ) {
1597
+ i = fromParts.length;
1598
+ while ( i-- ) fromParts[i] = '..';
1599
+
1600
+ return fromParts.concat( toParts ).join( '/' );
1601
+ } else {
1602
+ toParts.unshift( '.' );
1603
+ return toParts.join( '/' );
1604
+ }
1605
+ }
1606
+
1607
+ /**
1608
+ * Creates a template function from a template string. The template
1609
+ may have `<%= someVar %>` interpolators, and the returned function
1610
+ should be called with a data object e.g. `{ someVar: 'someData' }`
1611
+ * @param {string} str - the template string
1612
+ * @returns {function}
1613
+ */
1614
+ function template ( str ) {
1615
+ return function ( data ) {
1616
+ return str.replace( /<%=\s*([^\s]+)\s*%>/g, function ( match, $1 ) {
1617
+ return $1 in data ? data[ $1 ] : match;
1618
+ });
1619
+ };
1620
+ }
1621
+
1622
+ function getId ( m ) {
1623
+ return m.id;
1624
+ }
1625
+
1626
+ function getName ( m ) {
1627
+ return m.name;
1628
+ }
1629
+
1630
+ function quote ( str ) {
1631
+ return "'" + JSON.stringify(str).slice(1, -1).replace(/'/g, "\\'") + "'";
1632
+ }
1633
+
1634
+ function req ( path ) {
1635
+ return 'require(' + quote(path) + ')';
1636
+ }
1637
+
1638
+ function globalify ( name ) {
1639
+ if ( /^__dep\d+__$/.test( name ) ) {
1640
+ return 'undefined';
1641
+ } else {
1642
+ return 'global.' + name;
1643
+ }
1644
+ }
1645
+
1646
+ var amd__introTemplate = template( 'define(<%= amdName %><%= paths %>function (<%= names %>) {\n\n' );
1647
+
1648
+ function amd__amd ( mod, body, options ) {
1649
+ var seen = {},
1650
+ importNames = [],
1651
+ importPaths = [],
1652
+ intro,
1653
+ placeholders = 0;
1654
+
1655
+ // gather imports, and remove import declarations
1656
+ mod.imports.forEach( function(x ) {
1657
+ var path = options.absolutePaths ? resolveId( x.path, options.amdName ) : x.path;
1658
+
1659
+ if ( !hasOwnProp.call( seen, path ) ) {
1660
+ importPaths.push( path );
1661
+
1662
+ if ( x.name ) {
1663
+ while ( placeholders ) {
1664
+ importNames.push( '__dep' + importNames.length + '__' );
1665
+ placeholders--;
1666
+ }
1667
+ importNames.push( x.name );
1668
+ } else {
1669
+ placeholders++;
1670
+ }
1671
+
1672
+ seen[ path ] = true;
1673
+ }
1674
+
1675
+ body.remove( x.start, x.next );
1676
+ });
1677
+
1678
+ transformExportDeclaration( mod.exports[0], body );
1679
+
1680
+ intro = amd__introTemplate({
1681
+ amdName: options.amdName ? (("'" + (options.amdName)) + "', ") : '',
1682
+ paths: importPaths.length ? '[' + importPaths.map( quote ).join( ', ' ) + '], ' : '',
1683
+ names: importNames.join( ', ' )
1684
+ });
1685
+
1686
+ body.trim()
1687
+ .prepend( "'use strict';\n\n" )
1688
+ .trim()
1689
+ .indent()
1690
+ .prepend( intro )
1691
+ .append( '\n\n});' );
1692
+
1693
+ return packageResult( body, options, 'toAmd' );
1694
+ }
1695
+
1696
+ function cjs__cjs ( mod, body, options ) {
1697
+ var seen = {}, exportDeclaration;
1698
+
1699
+ mod.imports.forEach( function(x ) {
1700
+ if ( !hasOwnProp.call( seen, x.path ) ) {
1701
+ var replacement = x.isEmpty ? (("" + (req(x.path))) + ";") : (("var " + (x.name)) + (" = " + (req(x.path))) + ";");
1702
+ body.replace( x.start, x.end, replacement );
1703
+
1704
+ seen[ x.path ] = true;
1705
+ } else {
1706
+ body.remove( x.start, x.next );
1707
+ }
1708
+ });
1709
+
1710
+ exportDeclaration = mod.exports[0];
1711
+
1712
+ if ( exportDeclaration ) {
1713
+ switch ( exportDeclaration.type ) {
1714
+ case 'namedFunction':
1715
+ case 'namedClass':
1716
+ body.remove( exportDeclaration.start, exportDeclaration.valueStart );
1717
+ body.replace( exportDeclaration.end, exportDeclaration.end, (("\nmodule.exports = " + (exportDeclaration.node.declaration.id.name)) + ";") );
1718
+ break;
1719
+
1720
+ case 'anonFunction':
1721
+ case 'anonClass':
1722
+ case 'expression':
1723
+ body.replace( exportDeclaration.start, exportDeclaration.valueStart, 'module.exports = ' );
1724
+ break;
1725
+
1726
+ default:
1727
+ throw new Error( 'Unexpected export type' );
1728
+ }
1729
+ }
1730
+
1731
+ body.prepend( "'use strict';\n\n" ).trimLines();
1732
+
1733
+ return packageResult( body, options, 'toCjs' );
1734
+ }
1735
+
1736
+ function standaloneUmdIntro ( options, indentStr ) {
1737
+ var amdName = options.amdName ?
1738
+ quote(options.amdName) + ", " :
1739
+ '';
1740
+
1741
+ var intro =
1742
+ (("(function (factory) {\
1743
+ \n !(typeof exports === 'object' && typeof module !== 'undefined') &&\
1744
+ \n typeof define === 'function' && define.amd ? define(" + amdName) + "factory) :\
1745
+ \n factory()\
1746
+ \n}(function () { 'use strict';\
1747
+ \n\
1748
+ \n");
1749
+
1750
+ return intro.replace( /\t/g, indentStr );
1751
+ }
1752
+
1753
+ function defaultUmdIntro ( options, indentStr ) {
1754
+ var hasExports = options.hasExports;
1755
+
1756
+ var amdName = options.amdName ?
1757
+ quote(options.amdName) + ", " :
1758
+ '';
1759
+ var amdDeps = options.importPaths.length > 0 ?
1760
+ '[' + ( options.absolutePaths ? options.importPaths.map( resolveAgainst( options.amdName ) ) : options.importPaths ).map( quote ).join( ', ' ) + '], ' :
1761
+ '';
1762
+ var cjsDeps = options.importPaths.map( req ).join( ', ' );
1763
+ var globalDeps = options.importNames.map( globalify ).join( ', ' );
1764
+ var args = options.importNames.join( ', ' );
1765
+
1766
+ var cjsExport =
1767
+ (hasExports ? 'module.exports = ' : '') + (("factory(" + cjsDeps) + ")");
1768
+
1769
+ var globalExport =
1770
+ (hasExports ? (("global." + (options.name)) + " = ") : '') + (("factory(" + globalDeps) + ")");
1771
+
1772
+
1773
+ var intro =
1774
+ (("(function (global, factory) {\
1775
+ \n typeof exports === 'object' && typeof module !== 'undefined' ? " + cjsExport) + (" :\
1776
+ \n typeof define === 'function' && define.amd ? define(" + amdName) + ("" + amdDeps) + ("factory) :\
1777
+ \n " + globalExport) + ("\
1778
+ \n}(this, function (" + args) + ") { 'use strict';\
1779
+ \n\
1780
+ \n");
1781
+
1782
+ return intro.replace( /\t/g, indentStr );
1783
+ }
1784
+
1785
+ var EsperantoError = function ( message, data ) {
1786
+ var prop;
1787
+
1788
+ this.message = message;
1789
+ this.stack = (new Error()).stack;
1790
+
1791
+ for ( prop in data ) {
1792
+ if ( data.hasOwnProperty( prop ) ) {
1793
+ this[ prop ] = data[ prop ];
1794
+ }
1795
+ }
1796
+ };
1797
+
1798
+ EsperantoError.prototype = new Error();
1799
+ EsperantoError.prototype.constructor = EsperantoError;
1800
+ EsperantoError.prototype.name = 'EsperantoError';
1801
+
1802
+ function requireName ( options ) {
1803
+ if ( !options.name ) {
1804
+ throw new EsperantoError( 'You must supply a `name` option for UMD modules', {
1805
+ code: 'MISSING_NAME'
1806
+ });
1807
+ }
1808
+ }
1809
+
1810
+ function umd__umd ( mod, body, options ) {
1811
+ var importNames = [];
1812
+ var importPaths = [];
1813
+ var seen = {};
1814
+ var placeholders = 0;
1815
+
1816
+ requireName( options );
1817
+
1818
+ var hasImports = mod.imports.length > 0;
1819
+ var hasExports = mod.exports.length > 0;
1820
+
1821
+ var intro;
1822
+ if (!hasImports && !hasExports) {
1823
+ intro = standaloneUmdIntro({
1824
+ amdName: options.amdName,
1825
+ }, body.getIndentString() );
1826
+ } else {
1827
+ // gather imports, and remove import declarations
1828
+ mod.imports.forEach( function(x ) {
1829
+ if ( !hasOwnProp.call( seen, x.path ) ) {
1830
+ importPaths.push( x.path );
1831
+
1832
+ if ( x.name ) {
1833
+ while ( placeholders ) {
1834
+ importNames.push( '__dep' + importNames.length + '__' );
1835
+ placeholders--;
1836
+ }
1837
+ importNames.push( x.name );
1838
+ } else {
1839
+ placeholders++;
1840
+ }
1841
+
1842
+ seen[ x.path ] = true;
1843
+ }
1844
+
1845
+ body.remove( x.start, x.next );
1846
+ });
1847
+
1848
+ transformExportDeclaration( mod.exports[0], body );
1849
+
1850
+ intro = defaultUmdIntro({
1851
+ hasExports: hasExports,
1852
+ importPaths: importPaths,
1853
+ importNames: importNames,
1854
+ amdName: options.amdName,
1855
+ absolutePaths: options.absolutePaths,
1856
+ name: options.name
1857
+ }, body.getIndentString() );
1858
+ }
1859
+
1860
+ body.indent().prepend( intro ).trimLines().append( '\n\n}));' );
1861
+
1862
+ return packageResult( body, options, 'toUmd' );
1863
+ }
1864
+
1865
+ var defaultsMode = {
1866
+ amd: amd__amd,
1867
+ cjs: cjs__cjs,
1868
+ umd: umd__umd
1869
+ };
1870
+
1871
+ function gatherImports ( imports, getName ) {
1872
+ var chains = {}, identifierReplacements = {};
1873
+
1874
+ imports.forEach( function(x ) {
1875
+ var moduleName = getName( x );
1876
+
1877
+ x.specifiers.forEach( function(s ) {
1878
+ var name, replacement;
1879
+
1880
+ if ( s.isBatch ) {
1881
+ return;
1882
+ }
1883
+
1884
+ name = s.as;
1885
+ replacement = moduleName + ( s.isDefault ? ("['default']") : ("." + (s.name)) );
1886
+
1887
+ if ( !x.passthrough ) {
1888
+ identifierReplacements[ name ] = replacement;
1889
+ }
1890
+
1891
+ chains[ name ] = replacement;
1892
+ });
1893
+ });
1894
+
1895
+ return [ chains, identifierReplacements ];
1896
+ }
1897
+
1898
+ function getExportNames ( exports ) {
1899
+ var result = {};
1900
+
1901
+ exports.forEach( function(x ) {
1902
+ if ( x.isDefault ) return;
1903
+
1904
+ if ( x.hasDeclaration ) {
1905
+ result[ x.name ] = x.name;
1906
+ return;
1907
+ }
1908
+
1909
+ x.specifiers.forEach( function(s ) {
1910
+ result[ s.name ] = s.name;
1911
+ });
1912
+ });
1913
+
1914
+ return result;
1915
+ }
1916
+
1917
+ function utils_transformBody__transformBody ( mod, body, options ) {var $D$3;
1918
+ var chains,
1919
+ identifierReplacements,
1920
+ importedBindings = {},
1921
+ importedNamespaces = {},
1922
+ exportNames,
1923
+ alreadyExported = {},
1924
+ earlyExports,
1925
+ lateExports;
1926
+
1927
+ chains = ($D$3 = gatherImports( mod.imports, mod.getName ))[0], identifierReplacements = $D$3[1], $D$3;
1928
+ exportNames = getExportNames( mod.exports );
1929
+
1930
+ importedBindings = ($D$3 = getReadOnlyIdentifiers( mod.imports ))[0], importedNamespaces = $D$3[1], $D$3;
1931
+
1932
+ // ensure no conflict with `exports`
1933
+ identifierReplacements.exports = deconflict( 'exports', mod.ast._declared );
1934
+
1935
+ traverseAst( mod.ast, body, identifierReplacements, importedBindings, importedNamespaces, exportNames, alreadyExported );
1936
+
1937
+ // Remove import statements from the body of the module
1938
+ mod.imports.forEach( function(x ) {
1939
+ if ( x.passthrough ) {
1940
+ // this is an `export { foo } from './bar'` statement -
1941
+ // it will be dealt with in the next section
1942
+ return;
1943
+ }
1944
+
1945
+ body.remove( x.start, x.next );
1946
+ });
1947
+
1948
+ // Prepend require() statements (CommonJS output only)
1949
+ if ( options.header ) {
1950
+ body.prepend( options.header + '\n\n' );
1951
+ }
1952
+
1953
+ // Remove export statements (but keep declarations)
1954
+ mod.exports.forEach( function(x ) {
1955
+ switch ( x.type ) {
1956
+ case 'varDeclaration': // export var answer = 42;
1957
+ body.remove( x.start, x.valueStart );
1958
+ return;
1959
+
1960
+ case 'namedFunction':
1961
+ case 'namedClass':
1962
+ if ( x.isDefault ) {
1963
+ // export default function answer () { return 42; }
1964
+ body.remove( x.start, x.valueStart );
1965
+ body.insert( x.end, (("\nexports['default'] = " + (x.name)) + ";") );
1966
+ } else {
1967
+ // export function answer () { return 42; }
1968
+ body.remove( x.start, x.valueStart );
1969
+ }
1970
+ return;
1971
+
1972
+ case 'anonFunction': // export default function () {}
1973
+ case 'anonClass': // export default class () {}
1974
+ case 'expression': // export default 40 + 2;
1975
+ body.replace( x.start, x.valueStart, 'exports[\'default\'] = ' );
1976
+ return;
1977
+
1978
+ case 'named': // export { foo, bar };
1979
+ body.remove( x.start, x.next );
1980
+ break;
1981
+
1982
+ default:
1983
+ throw new Error( 'Unknown export type: ' + x.type );
1984
+ }
1985
+ });
1986
+
1987
+ // Append export block (this is the same for all module types, unlike imports)
1988
+ earlyExports = [];
1989
+ lateExports = [];
1990
+
1991
+ Object.keys( exportNames ).forEach( function(name ) {
1992
+ var exportAs = exportNames[ name ];
1993
+
1994
+ if ( chains.hasOwnProperty( name ) ) {
1995
+ // special case - a binding from another module
1996
+ if ( !options._evilES3SafeReExports ) {
1997
+ earlyExports.push( (("Object.defineProperty(exports, '" + exportAs) + ("', { enumerable: true, get: function () { return " + (chains[name])) + "; }});") );
1998
+ } else {
1999
+ lateExports.push( (("exports." + exportAs) + (" = " + (chains[name])) + ";") );
2000
+ }
2001
+ } else if ( ~mod.ast._topLevelFunctionNames.indexOf( name ) ) {
2002
+ // functions should be exported early, in
2003
+ // case of cyclic dependencies
2004
+ earlyExports.push( (("exports." + exportAs) + (" = " + name) + ";") );
2005
+ } else if ( !alreadyExported.hasOwnProperty( name ) ) {
2006
+ lateExports.push( (("exports." + exportAs) + (" = " + name) + ";") );
2007
+ }
2008
+ });
2009
+
2010
+ // Function exports should be exported immediately after 'use strict'
2011
+ if ( earlyExports.length ) {
2012
+ body.trim().prepend( earlyExports.join( '\n' ) + '\n\n' );
2013
+ }
2014
+
2015
+ // Everything else should be exported at the end
2016
+ if ( lateExports.length ) {
2017
+ body.trim().append( '\n\n' + lateExports.join( '\n' ) );
2018
+ }
2019
+
2020
+ if ( options.intro && options.outro ) {
2021
+ body.indent().prepend( options.intro ).trimLines().append( options.outro );
2022
+ }
2023
+ ;$D$3 = void 0}
2024
+
2025
+ function deconflict ( name, declared ) {
2026
+ while ( hasOwnProp.call( declared, name ) ) {
2027
+ name = '_' + name;
2028
+ }
2029
+
2030
+ return name;
2031
+ }
2032
+
2033
+ function getImportSummary ( mod ) {
2034
+ var importPaths = [], importNames = [], seen = {}, placeholders = 0;
2035
+
2036
+ mod.imports.forEach( function(x ) {
2037
+ if ( !hasOwnProp.call( seen, x.path ) ) {
2038
+ importPaths.push( x.path );
2039
+
2040
+ if ( x.specifiers.length ) {
2041
+ while ( placeholders ) {
2042
+ importNames.push( '__dep' + importNames.length + '__' );
2043
+ placeholders--;
2044
+ }
2045
+ importNames.push( mod.getName( x ) );
2046
+ } else {
2047
+ placeholders++;
2048
+ }
2049
+
2050
+ seen[ x.path ] = true;
2051
+ }
2052
+ });
2053
+
2054
+ return [ importPaths, importNames ];
2055
+ }
2056
+
2057
+ var strictMode_amd__introTemplate;
2058
+
2059
+ strictMode_amd__introTemplate = template( 'define(<%= amdName %><%= paths %>function (<%= names %>) {\n\n\t\'use strict\';\n\n' );
2060
+
2061
+ function strictMode_amd__amd ( mod, body, options ) {var $D$4;
2062
+ var importPaths,
2063
+ importNames,
2064
+ intro;
2065
+
2066
+ importPaths = ($D$4 = getImportSummary( mod ))[0], importNames = $D$4[1], $D$4;
2067
+
2068
+ if ( mod.exports.length ) {
2069
+ importPaths.unshift( 'exports' );
2070
+ importNames.unshift( 'exports' );
2071
+ }
2072
+
2073
+ intro = strictMode_amd__introTemplate({
2074
+ amdName: options.amdName ? (("'" + (options.amdName)) + "', ") : '',
2075
+ paths: importPaths.length ? '[' + ( options.absolutePaths ? importPaths.map( resolveAgainst( options.amdName ) ) : importPaths ).map( quote ).join( ', ' ) + '], ' : '',
2076
+ names: importNames.join( ', ' )
2077
+ }).replace( /\t/g, body.getIndentString() );
2078
+
2079
+ utils_transformBody__transformBody( mod, body, {
2080
+ intro: intro,
2081
+ outro: '\n\n});',
2082
+ _evilES3SafeReExports: options._evilES3SafeReExports
2083
+ });
2084
+
2085
+ return packageResult( body, options, 'toAmd' );
2086
+ ;$D$4 = void 0}
2087
+
2088
+ function strictMode_cjs__cjs ( mod, body, options ) {
2089
+ var importBlock, seen = {};
2090
+
2091
+ // Create block of require statements
2092
+ importBlock = mod.imports.map( function(x ) {
2093
+ var name, replacement;
2094
+
2095
+ if ( !hasOwnProp.call( seen, x.path ) ) {
2096
+ if ( x.isEmpty ) {
2097
+ replacement = (("" + (req(x.path))) + ";");
2098
+ } else {
2099
+ name = mod.getName( x );
2100
+ replacement = (("var " + name) + (" = " + (req(x.path))) + ";");
2101
+ }
2102
+
2103
+ seen[ x.path ] = true;
2104
+ }
2105
+
2106
+ return replacement;
2107
+ }).filter( Boolean ).join( '\n' );
2108
+
2109
+ utils_transformBody__transformBody( mod, body, {
2110
+ header: importBlock,
2111
+ _evilES3SafeReExports: options._evilES3SafeReExports
2112
+ });
2113
+
2114
+ body.prepend( "'use strict';\n\n" ).trimLines();
2115
+
2116
+ return packageResult( body, options, 'toCjs' );
2117
+ }
2118
+
2119
+ function strictUmdIntro ( options, indentStr ) {
2120
+ var hasExports = options.hasExports;
2121
+
2122
+ var amdName = options.amdName ?
2123
+ "'" + options.amdName + "', " :
2124
+ '';
2125
+ var amdDeps = hasExports || options.importPaths.length > 0 ?
2126
+ '[' +
2127
+ ( hasExports ? [ 'exports' ] : [] ).concat( options.absolutePaths ? options.importPaths.map( resolveAgainst( options.amdName ) ) : options.importPaths ).map( quote ).join( ', ' ) +
2128
+ '], ' :
2129
+ '';
2130
+ var cjsDeps = ( hasExports ? [ 'exports' ] : [] ).concat( options.importPaths.map( req ) ).join( ', ' );
2131
+ var globalDeps = ( hasExports ? [ (("(global." + (options.name)) + " = {})") ] : [] )
2132
+ .concat( options.importNames.map( globalify ) ).join( ', ' );
2133
+ var args = ( hasExports ? [ 'exports' ] : [] ).concat( options.importNames ).join( ', ' );
2134
+
2135
+ var defaultsBlock = '';
2136
+ if ( options.externalDefaults && options.externalDefaults.length > 0 ) {
2137
+ defaultsBlock = options.externalDefaults.map( function(x )
2138
+ {return '\t' + ( x.needsNamed ? (("var " + (x.name)) + "__default") : x.name ) +
2139
+ ((" = ('default' in " + (x.name)) + (" ? " + (x.name)) + ("['default'] : " + (x.name)) + ");")}
2140
+ ).join('\n') + '\n\n';
2141
+ }
2142
+
2143
+ var intro =
2144
+ (("(function (global, factory) {\
2145
+ \n typeof exports === 'object' && typeof module !== 'undefined' ? factory(" + cjsDeps) + (") :\
2146
+ \n typeof define === 'function' && define.amd ? define(" + amdName) + ("" + amdDeps) + ("factory) :\
2147
+ \n factory(" + globalDeps) + (")\
2148
+ \n}(this, function (" + args) + (") { 'use strict';\
2149
+ \n\
2150
+ \n" + defaultsBlock) + "");
2151
+
2152
+ return intro.replace( /\t/g, indentStr );
2153
+ }
2154
+
2155
+ function strictMode_umd__umd ( mod, body, options ) {
2156
+ requireName( options );
2157
+
2158
+ var importPaths = (importNames = getImportSummary( mod ))[0], importNames = importNames[1];
2159
+
2160
+ var hasImports = mod.imports.length > 0;
2161
+ var hasExports = mod.exports.length > 0;
2162
+
2163
+ var intro;
2164
+ if (!hasImports && !hasExports) {
2165
+ intro = standaloneUmdIntro({
2166
+ amdName: options.amdName,
2167
+ }, body.getIndentString() );
2168
+ } else {
2169
+ intro = strictUmdIntro({
2170
+ hasExports: hasExports,
2171
+ importPaths: importPaths,
2172
+ importNames: importNames,
2173
+ amdName: options.amdName,
2174
+ absolutePaths: options.absolutePaths,
2175
+ name: options.name
2176
+ }, body.getIndentString() );
2177
+ }
2178
+
2179
+ utils_transformBody__transformBody( mod, body, {
2180
+ intro: intro,
2181
+ outro: '\n\n}));',
2182
+ _evilES3SafeReExports: options._evilES3SafeReExports
2183
+ });
2184
+
2185
+ return packageResult( body, options, 'toUmd' );
2186
+ }
2187
+
2188
+ var strictMode = {
2189
+ amd: strictMode_amd__amd,
2190
+ cjs: strictMode_cjs__cjs,
2191
+ umd: strictMode_umd__umd
2192
+ };
2193
+
2194
+ // TODO rewrite with named imports/exports
2195
+ var moduleBuilders = {
2196
+ defaultsMode: defaultsMode,
2197
+ strictMode: strictMode
2198
+ };
2199
+
2200
+ var defaultsMode_amd__introTemplate = template( 'define(<%= amdName %><%= amdDeps %>function (<%= names %>) {\n\n\t\'use strict\';\n\n' );
2201
+
2202
+ function defaultsMode_amd__amd ( bundle, body, options ) {
2203
+ var defaultName = bundle.entryModule.identifierReplacements.default;
2204
+ if ( defaultName ) {
2205
+ body.append( (("\n\nreturn " + defaultName) + ";") );
2206
+ }
2207
+
2208
+ var intro = defaultsMode_amd__introTemplate({
2209
+ amdName: options.amdName ? (("" + (quote(options.amdName))) + ", ") : '',
2210
+ amdDeps: bundle.externalModules.length ? '[' + bundle.externalModules.map( quoteId ).join( ', ' ) + '], ' : '',
2211
+ names: bundle.externalModules.map( getName ).join( ', ' )
2212
+ }).replace( /\t/g, body.getIndentString() );
2213
+
2214
+ body.indent().prepend( intro ).trimLines().append( '\n\n});' );
2215
+ return packageResult( body, options, 'toAmd', true );
2216
+ }
2217
+
2218
+ function quoteId ( m ) {
2219
+ return "'" + m.id + "'";
2220
+ }
2221
+
2222
+ function defaultsMode_cjs__cjs ( bundle, body, options ) {
2223
+ var importBlock = bundle.externalModules.map( function(x ) {
2224
+ return (("var " + (x.name)) + (" = " + (req(x.id))) + ";");
2225
+ }).join( '\n' );
2226
+
2227
+ if ( importBlock ) {
2228
+ body.prepend( importBlock + '\n\n' );
2229
+ }
2230
+
2231
+ var defaultName = bundle.entryModule.identifierReplacements.default;
2232
+ if ( defaultName ) {
2233
+ body.append( (("\n\nmodule.exports = " + defaultName) + ";") );
2234
+ }
2235
+
2236
+ body.prepend("'use strict';\n\n").trimLines();
2237
+
2238
+ return packageResult( body, options, 'toCjs', true );
2239
+ }
2240
+
2241
+ function defaultsMode_umd__umd ( bundle, body, options ) {
2242
+ requireName( options );
2243
+
2244
+ var entry = bundle.entryModule;
2245
+
2246
+ var hasImports = bundle.externalModules.length > 0;
2247
+ var hasExports = entry.exports.length > 0;
2248
+
2249
+ var intro;
2250
+ if (!hasImports && !hasExports) {
2251
+ intro = standaloneUmdIntro({
2252
+ amdName: options.amdName,
2253
+ }, body.getIndentString() );
2254
+ } else {
2255
+
2256
+ var defaultName = entry.identifierReplacements.default;
2257
+ if ( defaultName ) {
2258
+ body.append( (("\n\nreturn " + defaultName) + ";") );
2259
+ }
2260
+
2261
+ var importPaths = bundle.externalModules.map( getId );
2262
+ var importNames = bundle.externalModules.map( getName );
2263
+
2264
+ intro = defaultUmdIntro({
2265
+ hasExports: hasExports,
2266
+ importPaths: importPaths,
2267
+ importNames: importNames,
2268
+ amdName: options.amdName,
2269
+ name: options.name
2270
+ }, body.getIndentString() );
2271
+ }
2272
+
2273
+ body.indent().prepend( intro ).trimLines().append('\n\n}));');
2274
+
2275
+ return packageResult( body, options, 'toUmd', true );
2276
+ }
2277
+
2278
+ var builders_defaultsMode = {
2279
+ amd: defaultsMode_amd__amd,
2280
+ cjs: defaultsMode_cjs__cjs,
2281
+ umd: defaultsMode_umd__umd
2282
+ };
2283
+
2284
+ function getExportBlock ( entry ) {
2285
+ var name = entry.identifierReplacements.default;
2286
+ return (("exports['default'] = " + name) + ";");
2287
+ }
2288
+
2289
+ var builders_strictMode_amd__introTemplate = template( 'define(<%= amdName %><%= amdDeps %>function (<%= names %>) {\n\n\t\'use strict\';\n\n' );
2290
+
2291
+ function builders_strictMode_amd__amd ( bundle, body, options ) {
2292
+ var externalDefaults = bundle.externalModules.filter( builders_strictMode_amd__needsDefault );
2293
+ var entry = bundle.entryModule;
2294
+
2295
+ var importIds = bundle.externalModules.map( getId );
2296
+ var importNames = bundle.externalModules.map( getName );
2297
+
2298
+ if ( externalDefaults.length ) {
2299
+ var defaultsBlock = externalDefaults.map( function(x ) {
2300
+ // Case 1: default is used, and named is not
2301
+ if ( !x.needsNamed ) {
2302
+ return (("" + (x.name)) + (" = ('default' in " + (x.name)) + (" ? " + (x.name)) + ("['default'] : " + (x.name)) + ");");
2303
+ }
2304
+
2305
+ // Case 2: both default and named are used
2306
+ return (("var " + (x.name)) + ("__default = ('default' in " + (x.name)) + (" ? " + (x.name)) + ("['default'] : " + (x.name)) + ");");
2307
+ }).join( '\n' );
2308
+
2309
+ body.prepend( defaultsBlock + '\n\n' );
2310
+ }
2311
+
2312
+ if ( entry.exports.length ) {
2313
+ importIds.unshift( 'exports' );
2314
+ importNames.unshift( 'exports' );
2315
+
2316
+ if ( entry.defaultExport ) {
2317
+ body.append( '\n\n' + getExportBlock( entry ) );
2318
+ }
2319
+ }
2320
+
2321
+ var intro = builders_strictMode_amd__introTemplate({
2322
+ amdName: options.amdName ? (("" + (quote(options.amdName))) + ", ") : '',
2323
+ amdDeps: importIds.length ? '[' + importIds.map( quote ).join( ', ' ) + '], ' : '',
2324
+ names: importNames.join( ', ' )
2325
+ }).replace( /\t/g, body.getIndentString() );
2326
+
2327
+ body.indent().prepend( intro ).trimLines().append( '\n\n});' );
2328
+ return packageResult( body, options, 'toAmd', true );
2329
+ }
2330
+
2331
+ function builders_strictMode_amd__needsDefault ( externalModule ) {
2332
+ return externalModule.needsDefault;
2333
+ }
2334
+
2335
+ function builders_strictMode_cjs__cjs ( bundle, body, options ) {
2336
+ var entry = bundle.entryModule;
2337
+
2338
+ var importBlock = bundle.externalModules.map( function(x ) {
2339
+ var statement = (("var " + (x.name)) + (" = " + (req(x.id))) + ";");
2340
+
2341
+ if ( x.needsDefault ) {
2342
+ statement += '\n' +
2343
+ ( x.needsNamed ? (("var " + (x.name)) + "__default") : x.name ) +
2344
+ ((" = ('default' in " + (x.name)) + (" ? " + (x.name)) + ("['default'] : " + (x.name)) + ");");
2345
+ }
2346
+
2347
+ return statement;
2348
+ }).join( '\n' );
2349
+
2350
+ if ( importBlock ) {
2351
+ body.prepend( importBlock + '\n\n' );
2352
+ }
2353
+
2354
+ if ( entry.defaultExport ) {
2355
+ body.append( '\n\n' + getExportBlock( entry ) );
2356
+ }
2357
+
2358
+ body.prepend("'use strict';\n\n").trimLines();
2359
+
2360
+ return packageResult( body, options, 'toCjs', true );
2361
+ }
2362
+
2363
+ function builders_strictMode_umd__umd ( bundle, body, options ) {
2364
+ requireName( options );
2365
+
2366
+ var entry = bundle.entryModule;
2367
+
2368
+ var hasImports = bundle.externalModules.length > 0;
2369
+ var hasExports = entry.exports.length > 0;
2370
+
2371
+ var intro;
2372
+ if (!hasImports && !hasExports) {
2373
+ intro = standaloneUmdIntro({
2374
+ amdName: options.amdName,
2375
+ }, body.getIndentString() );
2376
+ } else {
2377
+
2378
+ if ( hasExports && entry.defaultExport ) {
2379
+ body.append( '\n\n' + getExportBlock( entry ) );
2380
+ }
2381
+
2382
+ var importPaths = bundle.externalModules.map( getId );
2383
+ var importNames = bundle.externalModules.map( getName );
2384
+
2385
+ intro = strictUmdIntro({
2386
+ hasExports: hasExports,
2387
+ importPaths: importPaths,
2388
+ importNames: importNames,
2389
+ externalDefaults: bundle.externalModules.filter( builders_strictMode_umd__needsDefault ),
2390
+ amdName: options.amdName,
2391
+ name: options.name,
2392
+ }, body.getIndentString() );
2393
+ }
2394
+
2395
+ body.indent().prepend( intro ).trimLines().append('\n\n}));');
2396
+
2397
+ return packageResult( body, options, 'toUmd', true );
2398
+ }
2399
+
2400
+ function builders_strictMode_umd__needsDefault ( externalModule ) {
2401
+ return externalModule.needsDefault;
2402
+ }
2403
+
2404
+ var builders_strictMode = {
2405
+ amd: builders_strictMode_amd__amd,
2406
+ cjs: builders_strictMode_cjs__cjs,
2407
+ umd: builders_strictMode_umd__umd
2408
+ };
2409
+
2410
+ // TODO rewrite with named imports/exports
2411
+ var bundleBuilders = {
2412
+ defaultsMode: builders_defaultsMode,
2413
+ strictMode: builders_strictMode
2414
+ };
2415
+
2416
+ function concat ( bundle, options ) {
2417
+ var body, intro, outro, indent;
2418
+
2419
+ // This bundle must be self-contained - no imports or exports
2420
+ if ( bundle.externalModules.length || bundle.entryModule.exports.length ) {
2421
+ throw new Error( (("bundle.concat() can only be used with bundles that have no imports/exports (imports: [" + (bundle.externalModules.map(function(x){return x.id}).join(', '))) + ("], exports: [" + (bundle.entryModule.exports.join(', '))) + "])") );
2422
+ }
2423
+
2424
+ body = bundle.body.clone();
2425
+
2426
+ // TODO test these options
2427
+ intro = 'intro' in options ? options.intro : ("(function () { 'use strict';\n\n");
2428
+ outro = 'outro' in options ? options.outro : '\n\n})();';
2429
+
2430
+ if ( !( 'indent' in options ) || options.indent === true ) {
2431
+ indent = body.getIndentString();
2432
+ } else {
2433
+ indent = options.indent || '';
2434
+ }
2435
+
2436
+ body.trimLines().indent( indent ).prepend( intro ).append( outro );
2437
+
2438
+ return packageResult( body, options, 'toString', true );
2439
+ }
2440
+
2441
+ var deprecateMessage = 'options.defaultOnly has been deprecated, and is now standard behaviour. To use named imports/exports, pass `strict: true`.',
2442
+ alreadyWarned = false;
2443
+
2444
+ function transpileMethod ( format ) {
2445
+ return function ( source ) {var options = arguments[1];if(options === void 0)options = {};
2446
+ var mod,
2447
+ body,
2448
+ builder;
2449
+
2450
+ mod = getStandaloneModule({ source: source, getModuleName: options.getModuleName, strict: options.strict });
2451
+ body = mod.body.clone();
2452
+
2453
+ if ( 'defaultOnly' in options && !alreadyWarned ) {
2454
+ // TODO link to a wiki page explaining this, or something
2455
+ console.log( deprecateMessage );
2456
+ alreadyWarned = true;
2457
+ }
2458
+
2459
+ if ( options.absolutePaths && !options.amdName ) {
2460
+ throw new Error( 'You must specify an `amdName` in order to use the `absolutePaths` option' );
2461
+ }
2462
+
2463
+ if ( !options.strict ) {
2464
+ // ensure there are no named imports/exports. TODO link to a wiki page...
2465
+ if ( hasNamedImports( mod ) || hasNamedExports( mod ) ) {
2466
+ throw new Error( 'You must be in strict mode (pass `strict: true`) to use named imports or exports' );
2467
+ }
2468
+
2469
+ builder = moduleBuilders.defaultsMode[ format ];
2470
+ } else {
2471
+ builder = moduleBuilders.strictMode[ format ];
2472
+ }
2473
+
2474
+ return builder( mod, body, options );
2475
+ };
2476
+ }
2477
+
2478
+ var esperanto = {
2479
+ toAmd: transpileMethod( 'amd' ),
2480
+ toCjs: transpileMethod( 'cjs' ),
2481
+ toUmd: transpileMethod( 'umd' ),
2482
+
2483
+ bundle: function ( options ) {
2484
+ return getBundle( options ).then( function ( bundle ) {
2485
+ return {
2486
+ imports: bundle.externalModules.map( function(mod ) {return mod.id} ),
2487
+ exports: flattenExports( bundle.entryModule.exports ),
2488
+
2489
+ toAmd: function(options ) {return transpile( 'amd', options )},
2490
+ toCjs: function(options ) {return transpile( 'cjs', options )},
2491
+ toUmd: function(options ) {return transpile( 'umd', options )},
2492
+
2493
+ concat: function(options ) {return concat( bundle, options || {} )}
2494
+ };
2495
+
2496
+ function transpile ( format, options ) {
2497
+ var builder;
2498
+
2499
+ options = options || {};
2500
+
2501
+ if ( 'defaultOnly' in options && !alreadyWarned ) {
2502
+ // TODO link to a wiki page explaining this, or something
2503
+ console.log( deprecateMessage );
2504
+ alreadyWarned = true;
2505
+ }
2506
+
2507
+ if ( !options.strict ) {
2508
+ // ensure there are no named imports/exports
2509
+ if ( hasNamedExports( bundle.entryModule ) ) {
2510
+ throw new Error( 'Entry module can only have named exports in strict mode (pass `strict: true`)' );
2511
+ }
2512
+
2513
+ bundle.modules.forEach( function(mod ) {
2514
+ mod.imports.forEach( function(x ) {
2515
+ if ( hasOwnProp.call( bundle.externalModuleLookup, x.id ) && ( !x.isDefault && !x.isBatch ) ) {
2516
+ throw new Error( 'You can only have named external imports in strict mode (pass `strict: true`)' );
2517
+ }
2518
+ });
2519
+ });
2520
+
2521
+ builder = bundleBuilders.defaultsMode[ format ];
2522
+ } else {
2523
+ builder = bundleBuilders.strictMode[ format ];
2524
+ }
2525
+
2526
+ return builder( bundle, bundle.body.clone(), options );
2527
+ }
2528
+ });
2529
+ }
2530
+ };
2531
+
2532
+ function flattenExports ( exports ) {
2533
+ var flattened = [];
2534
+
2535
+ exports.forEach( function(x ) {
2536
+ if ( x.isDefault ) {
2537
+ flattened.push( 'default' );
2538
+ }
2539
+
2540
+ else if ( x.name ) {
2541
+ flattened.push( x.name );
2542
+ }
2543
+
2544
+ else if ( x.specifiers ) {
2545
+ flattened.push.apply( flattened, x.specifiers.map( getName ) );
2546
+ }
2547
+ });
2548
+
2549
+ return flattened;
2550
+ }
2551
+
2552
+ module.exports = esperanto;