-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
addon.js
1772 lines (1435 loc) · 50.2 KB
/
addon.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/**
@module ember-cli
*/
const fs = require('fs');
const path = require('path');
const SilentError = require('silent-error');
const heimdallLogger = require('heimdalljs-logger');
const logger = heimdallLogger('ember-cli:addon');
const treeCacheLogger = heimdallLogger('ember-cli:addon:tree-cache');
const cacheKeyLogger = heimdallLogger('ember-cli:addon:cache-key-for-tree');
const PackageInfoCache = require('../models/package-info-cache');
const p = require('ember-cli-preprocess-registry/preprocessors');
const preprocessJs = p.preprocessJs;
const preprocessCss = p.preprocessCss;
const preprocessTemplates = p.preprocessTemplates;
const instantiateAddons = require('../models/instantiate-addons');
const CoreObject = require('core-object');
const Project = require('../models/project');
const mergeTrees = require('../broccoli/merge-trees');
const Funnel = require('broccoli-funnel');
const walkSync = require('walk-sync');
const ensurePosixPath = require('ensure-posix-path');
const { defaultsDeep } = require('ember-cli-lodash-subset');
const findAddonByName = require('../utilities/find-addon-by-name');
const heimdall = require('heimdalljs');
const calculateCacheKeyForTree = require('calculate-cache-key-for-tree');
const addonProcessTree = require('../utilities/addon-process-tree');
const emberCLIBabelConfigKey = require('../utilities/ember-cli-babel-config-key');
const semver = require('semver');
const processModulesOnly = require('../broccoli/babel-process-modules-only');
const registryHasPreprocessor = require('../utilities/registry-has-preprocessor');
const BUILD_BABEL_OPTIONS_FOR_PREPROCESSORS = Symbol('BUILD_BABEL_OPTIONS_FOR_PREPROCESSORS');
if (!heimdall.hasMonitor('addon-tree-cache')) {
heimdall.registerMonitor('addon-tree-cache', function AddonTreeCacheSchema() {
this.hits = 0;
this.misses = 0;
this.adds = 0;
});
}
if (!heimdall.hasMonitor('cache-key-for-tree')) {
heimdall.registerMonitor('cache-key-for-tree', function CacheKeyForTreeSchema() {
this.modifiedMethods = 0;
this.treeForMethodsOverride = 0;
});
}
let DEFAULT_TREE_FOR_METHODS = {
app: 'treeForApp',
addon: 'treeForAddon',
'addon-styles': 'treeForAddonStyles',
'addon-templates': 'treeForAddonTemplates',
'addon-test-support': 'treeForAddonTestSupport',
public: 'treeForPublic',
styles: 'treeForStyles',
templates: 'treeForTemplates',
'test-support': 'treeForTestSupport',
vendor: 'treeForVendor',
};
let GLOBAL_TREE_FOR_METHOD_METHODS = ['treeFor', '_treeFor', 'treeGenerator'];
let DEFAULT_TREE_FOR_METHOD_METHODS = {
app: ['treeForApp'],
addon: [
'treeForAddon',
'treeForAddonStyles',
'treeForAddonTemplates',
'compileAddon',
'processedAddonJsFiles',
'compileTemplates',
'_addonTemplateFiles',
'compileStyles',
'preprocessJs',
],
'addon-styles': ['treeForAddonStyles'],
'addon-templates': ['treeForAddonTemplates'],
'addon-test-support': ['treeForAddonTestSupport', 'preprocessJs'],
public: ['treeForPublic'],
styles: ['treeForStyles'],
templates: ['treeForTemplates'],
'test-support': ['treeForTestSupport'],
vendor: ['treeForVendor'],
};
let ADDON_TREE_CACHE = {
__cache: Object.create(null),
getItem(key) {
let addonTreeCacheStats = heimdall.statsFor('addon-tree-cache');
let cachedValue = this.__cache[key];
if (cachedValue) {
addonTreeCacheStats.hits++;
treeCacheLogger.info(`Cache Hit: ${key}`);
return cachedValue;
} else {
addonTreeCacheStats.misses++;
treeCacheLogger.info(`Cache Miss: ${key}`);
return null;
}
},
setItem(key, value) {
let hasValue = !!value;
heimdall.statsFor('addon-tree-cache').adds++;
treeCacheLogger.info(`Cache Add: ${key} - ${hasValue}`);
this.__cache[key] = value;
},
clear() {
this.__cache = Object.create(null);
},
};
function _resetTreeCache() {
ADDON_TREE_CACHE.clear();
}
function warn(message) {
if (this.ui) {
this.ui.writeDeprecateLine(message);
} else {
const chalk = require('chalk');
console.log(chalk.yellow(`DEPRECATION: ${message}`));
}
}
/**
Root class for an Addon. If your addon module exports an Object this
will be extended from this base class. If you export a constructor (function),
it will **not** extend from this class.
Hooks:
- {{#crossLink "Addon/config:method"}}{{/crossLink}}
- {{#crossLink "Addon/blueprintsPath:method"}}{{/crossLink}}
- {{#crossLink "Addon/includedCommands:method"}}{{/crossLink}}
- {{#crossLink "Addon/importTransforms:method"}}{{/crossLink}}
- {{#crossLink "Addon/serverMiddleware:method"}}{{/crossLink}}
- {{#crossLink "Addon/testemMiddleware:method"}}{{/crossLink}}
- {{#crossLink "Addon/postBuild:method"}}{{/crossLink}}
- {{#crossLink "Addon/preBuild:method"}}{{/crossLink}}
- {{#crossLink "Addon/outputReady:method"}}{{/crossLink}}
- {{#crossLink "Addon/buildError:method"}}{{/crossLink}}
- {{#crossLink "Addon/included:method"}}{{/crossLink}}
- {{#crossLink "Addon/shouldIncludeChildAddon:method"}}{{/crossLink}}
- {{#crossLink "Addon/setupPreprocessorRegistry:method"}}{{/crossLink}}
- {{#crossLink "Addon/preprocessTree:method"}}{{/crossLink}}
- {{#crossLink "Addon/postprocessTree:method"}}{{/crossLink}}
- {{#crossLink "Addon/lintTree:method"}}{{/crossLink}}
- {{#crossLink "Addon/contentFor:method"}}{{/crossLink}}
- {{#crossLink "Addon/treeFor:method"}}{{/crossLink}}
@class Addon
@extends CoreObject
@constructor
@param {Project|Addon} parent The project or addon that directly depends on this addon
@param {Project} project The current project (deprecated)
*/
let addonProto = {
/**
The name of this addon.
@public
@final
@type String
@property name
*/
/**
The absolute path of the root directory where this addon is located.
@public
@final
@type String
@property root
*/
/**
The host app instance.
**Note**: this property will only be present on addons that are a direct dependency
of the application itself, not of other addons. It is also not available in `init()`,
but will be set before `setupPreprocessorRegistry()` and `included()` are invoked.
@public
@final
@type EmberApp
@property app
*/
/**
The root {{#crossLink "Project"}}project{{/crossLink}} to which this addon belongs.
@public
@final
@type Project
@property project
*/
/**
This addon's parent.
If the addon is a direct dependency of an application, then `parent` will be the
corresponding {{#crossLink "Project"}}project{{/crossLink}} instance. If it's a
dependency of another addon, then `parent` will be a reference to that addon.
@public
@final
@type Project|Addon
@property parent
*/
/**
The set of addons that this addon itself depends on.
This array is populated from the addon's listed `dependencies` and any items in
`ember-addon.paths` in its `package.json`.
@public
@final
@type Addon[]
@property addons
*/
/**
A [`console-ui`](https://github.com/ember-cli/console-ui) object that can be used
to log messages for the user and indicate progress on long-running operations.
@public
@final
@type UI
@property ui
*/
/**
The contents of the addon's `package.json`.
@public
@final
@type Object
@property pkg
*/
/**
Initializes the addon. If you override this method make sure and call `this._super.init && this._super.init.apply(this, arguments);` or your addon will not work.
@public
@method init
@param {Project|Addon} parent The project or addon that directly depends on this addon
@param {Project} project The current project (deprecated)
@example
```js
init(parent, project) {
this._super.init && this._super.init.apply(this, arguments);
this._someCustomSetup();
}
```
*/
init(parent, project) {
this._super();
this.parent = parent;
this.project = project;
this.ui = project && project.ui;
this.addonPackages = Object.create(null);
this.addons = [];
this.registry = p.defaultRegistry(this);
if (!this.root) {
throw new Error('Addon classes must be instantiated with the `root` property');
}
if (!this.name) {
throw new SilentError(`An addon must define a \`name\` property (found at ${this.root}).`);
}
this._nodeModulesPath = null;
this.treePaths = {
app: 'app',
styles: 'app/styles',
templates: 'app/templates',
addon: 'addon',
'addon-styles': 'addon/styles',
'addon-templates': 'addon/templates',
vendor: 'vendor',
'test-support': 'test-support',
'addon-test-support': 'addon-test-support',
public: 'public',
};
this.treeForMethods = defaultsDeep({}, DEFAULT_TREE_FOR_METHODS);
if (this.parent) {
// The parent should already have a packageInfoCache.
// Because it does, this package should already be in the cache.
this.packageInfoCache = this.parent.packageInfoCache;
}
if (!this.packageInfoCache) {
// this is most likely a 'root' addon, so create a new PackageInfoCache
// for it so we get the PackageInfo for it and its children.
//
// this may also be someone who failed to mock their addon correctly in testing.
this.packageInfoCache = new PackageInfoCache(this.ui);
}
this._packageInfo = this.packageInfoCache.loadAddon(this);
p.setupRegistry(this);
this._initDefaultBabelOptions();
},
_initDefaultBabelOptions() {
this.__originalOptions = this.options = defaultsDeep(this.options, {
babel: this[BUILD_BABEL_OPTIONS_FOR_PREPROCESSORS](),
});
let defaultEmberCLIBabelOptions = {
compileModules: true,
};
let emberCLIBabelConfigKey = this._emberCLIBabelConfigKey();
this.__originalOptions[emberCLIBabelConfigKey] = this.options[emberCLIBabelConfigKey] = defaultsDeep(
this.options[emberCLIBabelConfigKey],
defaultEmberCLIBabelOptions
);
},
/**
* Find an addon of the current addon.
*
* Example: ember-data depends on ember-cli-babel and wishes to have
* additional control over transpilation this method helps.
*
* ```js
* // ember-data/index.js
* treeForAddon(tree) {
* let babel = this.findOwnAddonByName('ember-cli-babel');
*
* return babel.transpileTree(tree, {
* // customize the babel step (see: ember-cli-addons readme for more details);
* });
* }
* ```
*
* @public
* @method findOwnAddonByName
*/
findOwnAddonByName(name) {
return this.addons.find((addon) => addon.name === name);
},
/**
* Check if the current addon intends to be hinted. Typically this is for
* hinting/linting libraries such as eslint or jshint
*
* @public
* @method hintingEnabled
*/
hintingEnabled() {
let isProduction = process.env.EMBER_ENV === 'production';
let testsEnabledDefault = process.env.EMBER_CLI_TEST_COMMAND === 'true' || !isProduction;
let explicitlyDisabled = this.app && this.app.options && this.app.options.hinting === false;
return testsEnabledDefault && !explicitlyDisabled;
},
/**
Shorthand method for [broccoli-concat](https://github.com/ember-cli/broccoli-concat)
@private
@method concatFiles
@param {tree} tree Tree of files
@param {Object} options Options for broccoli-concat
@return {tree} Modified tree
*/
concatFiles(tree, options) {
options.sourceMapConfig = this.app.options.sourcemaps;
return require('broccoli-concat')(tree, options);
},
/**
Allows to mark the addon as developing, triggering live-reload in the project the addon is linked to.
#### Uses:
- Working on projects with internal addons
@public
@method isDevelopingAddon
@return {Boolean}
*/
isDevelopingAddon() {
if (process.env.EMBER_ADDON_ENV === 'development' && this.parent instanceof Project) {
const parentName = this.parent.name();
// If the name in package.json and index.js match, we're definitely developing
if (parentName === this.name) {
return true;
}
// Addon names in index.js and package.json should be the same at all times whether they have scope or not.
if (this.root === this.parent.root) {
if (parentName !== this.name && !process.env.EMBER_CLI_IGNORE_ADDON_NAME_MISMATCH) {
let pathToDisplay = process.cwd() === this.root ? process.cwd() : path.relative(process.cwd(), this.root);
throw new SilentError(
'ember-cli: Your names in package.json and index.js should match. ' +
`The addon in ${pathToDisplay} currently have '${parentName}' in package.json and '${this.name}' in index.js. ` +
'Until ember-cli v3.9, this error can be disabled by setting env variable EMBER_CLI_IGNORE_ADDON_NAME_MISMATCH to "true". ' +
'For more information about this workaround, see: https://github.com/ember-cli/ember-cli/pull/7950.'
);
}
return true;
}
}
return false;
},
/**
* Discovers all child addons of this addon and an AddonInfo about
* each addon in this.addonPackages (keyed on addon name).
*
* Child addons include those from 'dependencies' (not devDependencies)
* and in-repo addons
*
* Any packageInfos that we find that are marked as not valid are excluded.
*
* @private
* @method discoverAddons
*/
discoverAddons() {
// prefer `packageRoot`, fallback to `root`; this is to maintain backwards compatibility for
// consumers who create a new instance of the base addon model class directly and don't set
// `packageRoot`
let pkgInfo = this.packageInfoCache.getEntry(this.packageRoot || this.root);
if (pkgInfo) {
let addonPackageList = pkgInfo.discoverAddonAddons();
this.addonPackages = pkgInfo.generateAddonPackages(
addonPackageList,
(addonInfo) => this.shouldIncludeChildAddon && !this.shouldIncludeChildAddon(addonInfo)
);
// in case any child addons are invalid, dump to the console about them.
pkgInfo.dumpInvalidAddonPackages(addonPackageList);
} else {
// There are cases where an addon can be created in memory and not actually
// have a root entry (or have one that is not actually pointing to a directory,
// like 'foo' in some of the tests. We don't want to crash, but want to let
// things continue even though they're empty.
this.addonPackages = Object.create(null);
}
},
initializeAddons() {
if (this._addonsInitialized) {
return;
}
this._addonsInitialized = true;
logger.info('initializeAddons for: %s', this.name);
this.discoverAddons();
this.addons = instantiateAddons(this, this.project, this.addonPackages);
this.addons.forEach((addon) => logger.info('addon: %s', addon.name));
},
/**
Invoke the specified method for each enabled addon.
@private
@method eachAddonInvoke
@param {String} methodName the method to invoke on each addon
@param {Array} args the arguments to pass to the invoked method
*/
eachAddonInvoke(methodName, args) {
this.initializeAddons();
let invokeArguments = args || [];
return this.addons.reduce((sum, addon) => {
let method = addon[methodName];
if (method) {
let val = method.apply(addon, invokeArguments);
if (val) {
sum.push(val);
}
}
return sum;
}, []);
},
/**
Invoke the specified method for each of the project's addons.
@private
@method _eachProjectAddonInvoke
@param {String} methodName the method to invoke on each addon
@param {Array} args the arguments to pass to the invoked method
*/
_eachProjectAddonInvoke(methodName, args) {
this.initializeAddons();
let invokeArguments = args || [];
return this.project.addons.reduce((sum, addon) => {
let method = addon[methodName];
if (method) {
let val = method.apply(addon, invokeArguments);
if (val) {
sum.push(val);
}
}
return sum;
}, []);
},
_addonPreprocessTree(type, tree) {
return addonProcessTree(this, 'preprocessTree', type, tree);
},
_addonPostprocessTree(type, tree) {
return addonProcessTree(this, 'postprocessTree', type, tree);
},
/**
Generates a tree for the specified path
@private
@method treeGenerator
@return {tree}
*/
treeGenerator(dir) {
let tree;
if (!this.project) {
this._warn(
`Addon: \`${this.name}\` is missing addon.project, this may be the result of an addon forgetting to invoke \`super\` in its init.`
);
}
// TODO: fix law of demeter `_watchmanInfo.canNestRoots` is obviously a poor idea
if ((this.project && this.project._watchmanInfo.canNestRoots) || this.isDevelopingAddon()) {
const WatchedDir = require('broccoli-source').WatchedDir;
tree = new WatchedDir(dir);
} else {
const UnwatchedDir = require('broccoli-source').UnwatchedDir;
tree = new UnwatchedDir(dir);
}
return tree;
},
_treePathFor(treeName) {
let treePath = this.treePaths[treeName];
let absoluteTreePath = path.join(this.root, treePath);
let normalizedAbsoluteTreePath = path.normalize(absoluteTreePath);
return ensurePosixPath(normalizedAbsoluteTreePath);
},
/**
* @private
* @method _warn
*/
_warn: warn,
_emberCLIBabelConfigKey() {
let emberCLIBabelInstance = findAddonByName(this.addons, 'ember-cli-babel');
return emberCLIBabelConfigKey(emberCLIBabelInstance);
},
/**
Returns a given type of tree (if present), merged with the
application tree. For each of the trees available using this
method, you can also use a direct method called `treeFor[Type]` (eg. `treeForApp`).
Available tree names:
- {{#crossLink "Addon/treeForApp:method"}}app{{/crossLink}}
- {{#crossLink "Addon/treeForStyles:method"}}styles{{/crossLink}}
- {{#crossLink "Addon/treeForTemplates:method"}}templates{{/crossLink}}
- {{#crossLink "Addon/treeForAddonTemplates:method"}}addon-templates{{/crossLink}}
- {{#crossLink "Addon/treeForAddon:method"}}addon{{/crossLink}}
- {{#crossLink "Addon/treeForVendor:method"}}vendor{{/crossLink}}
- {{#crossLink "Addon/treeForTestSupport:method"}}test-support{{/crossLink}}
- {{#crossLink "Addon/treeForAddonTestSupport:method"}}addon-test-support{{/crossLink}}
- {{#crossLink "Addon/treeForPublic:method"}}public{{/crossLink}}
#### Uses:
- manipulating trees at build time
@public
@method treeFor
@param {String} name
@return {Tree}
*/
treeFor(treeType) {
let node = heimdall.start({
name: `treeFor(${this.name} - ${treeType})`,
addonName: this.name,
treeType,
treeFor: true,
});
let cacheKeyForTreeType = this.cacheKeyForTree(treeType);
let cachedTree = ADDON_TREE_CACHE.getItem(cacheKeyForTreeType);
if (cachedTree) {
node.stop();
return cachedTree;
}
let trees = this.eachAddonInvoke('treeFor', [treeType]);
let tree = this._treeFor(treeType);
if (tree) {
trees.push(tree);
}
if (this.isDevelopingAddon() && this.hintingEnabled() && treeType === 'app') {
trees.push(this.jshintAddonTree());
}
let mergedTreesForType = mergeTrees(trees, {
overwrite: true,
annotation: `Addon#treeFor (${this.name} - ${treeType})`,
});
if (cacheKeyForTreeType) {
ADDON_TREE_CACHE.setItem(cacheKeyForTreeType, mergedTreesForType);
}
node.stop();
return mergedTreesForType;
},
/**
@private
@param {String} name
@method _treeFor
@return {tree}
*/
_treeFor(name) {
let treePath = path.resolve(this.root, this.treePaths[name]);
let treeForMethod = this.treeForMethods[name];
let tree;
if (fs.existsSync(treePath)) {
tree = this.treeGenerator(treePath);
}
if (this[treeForMethod]) {
tree = this[treeForMethod](tree);
}
return tree;
},
/**
Calculates a cacheKey for the given treeType. It is expected to return a
cache key allowing multiple builds of the same tree to simply return the
original tree (preventing duplicate work). If it returns null / undefined
the tree in question will opt out of this caching system.
This method is invoked prior to calling treeFor with the same tree name.
You should override this method if you implement custom treeFor or treeFor*
methods, which cause addons to opt-out of this caching.
@public
@method cacheKeyForTree
@param {String} treeType
@return {String} cacheKey
*/
cacheKeyForTree(treeType) {
let methodsToValidate = methodsForTreeType(treeType);
let cacheKeyStats = heimdall.statsFor('cache-key-for-tree');
// determine if treeFor* (or other methods for tree type) overrides for the given tree
let modifiedMethods = methodsToValidate.filter((methodName) => this[methodName] !== addonProto[methodName]);
if (modifiedMethods.length) {
cacheKeyStats.modifiedMethods++;
cacheKeyLogger.info(`Opting out due to: modified methods: ${modifiedMethods.join(', ')}`);
return null; // uncacheable
}
// determine if treeForMethods overrides for given tree
if (this.treeForMethods[treeType] !== DEFAULT_TREE_FOR_METHODS[treeType]) {
cacheKeyStats.treeForMethodsOverride++;
cacheKeyLogger.info('Opting out due to: treeForMethods override');
return null; // uncacheable
}
// compute cache key
let cacheKey = calculateCacheKeyForTree(treeType, this);
return cacheKey; // profit?
},
/**
This method climbs up the hierarchy of addons
up to the host application.
This prevents previous addons (prior to `this.import`, ca 2.7.0)
to break at importing assets when they are used nested in other addons.
@private
@method _findHost
*/
_findHost() {
let current = this;
let app;
// Keep iterating upward until we don't have a grandparent.
// Has to do this grandparent check because at some point we hit the project.
do {
app = current.app || app;
} while (current.parent.parent && (current = current.parent));
return app;
},
/**
This method is called when the addon is included in a build. You
would typically use this hook to perform additional imports
#### Uses:
- including vendor files
- setting configuration options
*Note:* Any options set in the consuming application will override the addon.
@public
@method included
@param {EmberApp|EmberAddon} parent The parent object which included this addon
@example
```js
included(parent) {
this._super.included.apply(this, arguments);
this.import(somePath);
}
```
*/
included(/* parent */) {
if (!this._addonsInitialized) {
// someone called `this._super.included` without `apply` (because of older
// core-object issues that prevent a "real" super call from working properly)
return;
}
this.eachAddonInvoke('included', [this]);
},
/**
Imports an asset into this addon.
@public
@method import
@param {Object|String} asset Either a path to the asset or an object with environment names and paths as key-value pairs.
@param {Object} [options] Options object
@param {String} [options.type] Either 'vendor' or 'test', defaults to 'vendor'
@param {Boolean} [options.prepend] Whether or not this asset should be prepended, defaults to false
@param {String} [options.destDir] Destination directory, defaults to the name of the directory the asset is in
@since 2.7.0
*/
import(asset, options) {
options = options || {};
options.resolveFrom = options.resolveFrom || this.root;
let app = this._findHost();
app.import(asset, options);
},
/**
Returns the tree for all app files
@public
@method treeForApp
@param {Tree} tree
@return {Tree} App file tree
*/
treeForApp(tree) {
return tree;
},
/**
Returns the tree for all template files
@public
@method treeForTemplates
@param {Tree} tree
@return {Tree} Template file tree
*/
treeForTemplates(tree) {
return tree;
},
/**
Returns the tree for this addon's templates
@public
@method treeForAddonTemplates
@param {Tree} tree
@return {Tree} Addon Template file tree
*/
treeForAddonTemplates(tree) {
return tree;
},
/**
Returns a tree for this addon
@public
@method treeForAddon
@param {Tree} tree
@return {Tree} Addon file tree
@example
```js
treeForAddon() {
var tree = this._super.treeForAddon.apply(this, arguments);
var checker = new VersionChecker(this);
var isOldEmber = checker.for('ember', 'bower').lt('1.13.0');
if (isOldEmber) {
tree = new Funnel(tree, { exclude: [ /instance-initializers/ ] });
}
return tree;
}
```
*/
treeForAddon(tree) {
if (!tree) {
return tree;
}
let addonTree = this.compileAddon(tree);
let stylesTree = this.compileStyles(this._treeFor('addon-styles'));
return mergeTrees([addonTree, stylesTree], { annotation: `Addon#treeForAddon(${this.name})` });
},
/**
Returns the tree for all style files
@public
@method treeForStyles
@param {Tree} tree The tree to process, usually `app/styles/` in the addon.
@return {Tree} The return tree has the same contents as the input tree, but is moved so that the `app/styles/` path is preserved.
*/
treeForStyles(tree) {
if (!tree) {
return tree;
}
return new Funnel(tree, {
destDir: 'app/styles',
annotation: `Addon#treeForStyles (${this.name})`,
});
},
/**
Returns the tree for all vendor files
@public
@method treeForVendor
@param {Tree} tree
@return {Tree} Vendor file tree
*/
treeForVendor(tree) {
return tree;
},
/**
Returns the tree for all test support files
@public
@method treeForTestSupport
@param {Tree} tree
@return {Tree} Test Support file tree
*/
treeForTestSupport(tree) {
return tree;
},
/**
Returns the tree for all public files
@public
@method treeForPublic
@param {Tree} tree
@return {Tree} Public file tree
*/
treeForPublic(tree) {
if (!tree) {
return tree;
}
return new Funnel(tree, {
srcDir: '/',
destDir: `/${this.moduleName()}`,
annotation: `Addon#treeForPublic (${this.name})`,
});
},
/**
Returns the tree for all test files namespaced to a given addon.
@public
@method treeForAddonTestSupport
@param {Tree} tree
@return {Tree}
*/
treeForAddonTestSupport(tree) {
if (!tree) {
return tree;
}
let namespacedTree = new Funnel(tree, {
srcDir: '/',
destDir: `/${this.moduleName()}/test-support`,
annotation: `Addon#treeForTestSupport (${this.name})`,
});
if (registryHasPreprocessor(this.registry, 'js')) {
return this.preprocessJs(namespacedTree, '/', this.name, {
registry: this.registry,
treeType: 'addon-test-support',
});
} else {
this._warn(
`Addon test support files were detected in \`${this._treePathFor('addon-test-support')}\`, but no JavaScript ` +
`preprocessors were found for \`${this.name}\`. Please make sure to add a preprocessor ` +
`(most likely \`ember-cli-babel\`) to \`dependencies\` (NOT \`devDependencies\`) in ` +
`\`${this.name}\`'s \`package.json\`.`
);
return processModulesOnly(namespacedTree, `Babel Fallback - Addon#treeForAddonTestSupport (${this.name})`);
}
},
/**
Runs the styles tree through preprocessors.
@private
@method compileStyles
@param {Tree} addonStylesTree Styles file tree
@return {Tree} Compiled styles tree
*/
compileStyles(addonStylesTree) {
if (addonStylesTree) {
let preprocessedStylesTree = this._addonPreprocessTree('css', addonStylesTree);
let processedStylesTree = preprocessCss(preprocessedStylesTree, '/', '/', {
outputPaths: { addon: `${this.name}.css` },
registry: this.registry,
treeType: 'addon-styles',
});
processedStylesTree = new Funnel(processedStylesTree, {
destDir: `${this.name}/__COMPILED_STYLES__`,
});
return this._addonPostprocessTree('css', processedStylesTree);
}
},
/**
Looks in the addon/ and addon/templates trees to determine if template files
exist that need to be precompiled.
This is executed once when building, but not on rebuilds.
@private
@method shouldCompileTemplates
@return {Boolean} indicates if templates need to be compiled for this addon
*/
shouldCompileTemplates() {
return this._fileSystemInfo().hasTemplates;
},
/**