-
Notifications
You must be signed in to change notification settings - Fork 137
/
compat-app-builder.ts
1596 lines (1422 loc) · 53.3 KB
/
compat-app-builder.ts
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
import type { Node as BroccoliNode } from 'broccoli-node-api';
import type {
OutputPaths,
Asset,
EmberAsset,
AddonPackage,
Engine,
AppMeta,
TemplateColocationPluginOptions,
} from '@embroider/core';
import {
explicitRelative,
extensionsPattern,
debug,
warn,
jsHandlebarsCompile,
templateColocationPluginPath,
cacheBustingPluginVersion,
cacheBustingPluginPath,
Resolver,
locateEmbroiderWorkingDir,
} from '@embroider/core';
import walkSync from 'walk-sync';
import { resolve as resolvePath, posix } from 'path';
import type { JSDOM } from 'jsdom';
import type Options from './options';
import type { CompatResolverOptions } from './resolver-transform';
import type { PackageRules } from './dependency-rules';
import { activePackageRules } from './dependency-rules';
import flatMap from 'lodash/flatMap';
import sortBy from 'lodash/sortBy';
import flatten from 'lodash/flatten';
import partition from 'lodash/partition';
import mergeWith from 'lodash/mergeWith';
import cloneDeep from 'lodash/cloneDeep';
import { sync as resolveSync } from 'resolve';
import bind from 'bind-decorator';
import { outputJSONSync, readJSONSync, rmSync, statSync, unlinkSync, writeFileSync, realpathSync } from 'fs-extra';
import type { Options as EtcOptions } from 'babel-plugin-ember-template-compilation';
import type { Options as ResolverTransformOptions } from './resolver-transform';
import type { Options as AdjustImportsOptions } from './babel-plugin-adjust-imports';
import { PreparedEmberHTML } from '@embroider/core/src/ember-html';
import type { InMemoryAsset, OnDiskAsset, ImplicitAssetPaths } from '@embroider/core/src/asset';
import { makePortable } from '@embroider/core/src/portable-babel-config';
import type { RouteFiles } from '@embroider/core/src/app-files';
import { AppFiles } from '@embroider/core/src/app-files';
import type { PortableHint } from '@embroider/core/src/portable';
import { maybeNodeModuleVersion } from '@embroider/core/src/portable';
import assertNever from 'assert-never';
import { Memoize } from 'typescript-memoize';
import { join, dirname } from 'path';
import resolve from 'resolve';
import type { V1Config } from './v1-config';
import type { AddonMeta, Package, PackageInfo } from '@embroider/core';
import { ensureDirSync, copySync, readdirSync, pathExistsSync } from 'fs-extra';
import type { TransformOptions } from '@babel/core';
import { MacrosConfig } from '@embroider/macros/src/node';
import SourceMapConcat from 'fast-sourcemap-concat';
import escapeRegExp from 'escape-string-regexp';
import type CompatApp from './compat-app';
import { SyncDir } from './sync-dir';
// This exists during the actual broccoli build step. As opposed to CompatApp,
// which also exists during pipeline-construction time.
export class CompatAppBuilder {
// for each relativePath, an Asset we have already emitted
private assets: Map<string, InternalAsset> = new Map();
constructor(
private root: string,
private origAppPackage: Package,
private appPackageWithMovedDeps: Package,
private options: Required<Options>,
private compatApp: CompatApp,
private configTree: V1Config,
private synthVendor: Package,
private synthStyles: Package
) {}
@Memoize()
private fastbootJSSrcDir() {
let target = join(this.compatApp.root, 'fastboot');
if (pathExistsSync(target)) {
return target;
}
}
private extractAssets(treePaths: OutputPaths<TreeNames>): Asset[] {
let assets: Asset[] = [];
// Everything in our traditional public tree is an on-disk asset
if (treePaths.publicTree) {
walkSync
.entries(treePaths.publicTree, {
directories: false,
})
.forEach(entry => {
assets.push({
kind: 'on-disk',
relativePath: entry.relativePath,
sourcePath: entry.fullPath,
mtime: entry.mtime as unknown as number, // https://github.com/joliss/node-walk-sync/pull/38
size: entry.size,
});
});
}
// ember-cli traditionally outputs a dummy testem.js file to prevent
// spurious errors when running tests under "ember s".
if (this.compatApp.shouldBuildTests) {
let testemAsset = this.findTestemAsset();
if (testemAsset) {
assets.push(testemAsset);
}
}
for (let asset of this.emberEntrypoints(treePaths.htmlTree)) {
assets.push(asset);
}
return assets;
}
@Memoize()
private findTestemAsset(): Asset | undefined {
let sourcePath;
try {
sourcePath = resolveSync('ember-cli/lib/broccoli/testem.js', { basedir: this.root });
} catch (err) {}
if (sourcePath) {
let stat = statSync(sourcePath);
return {
kind: 'on-disk',
relativePath: 'testem.js',
sourcePath,
mtime: stat.mtime.getTime(),
size: stat.size,
};
}
}
private activeAddonChildren(pkg: Package): AddonPackage[] {
let result = (pkg.dependencies.filter(this.isActiveAddon) as AddonPackage[]).filter(
// When looking for child addons, we want to ignore 'peerDependencies' of
// a given package, to align with how ember-cli resolves addons. So here
// we only include dependencies that are definitely active due to one of
// the other sections.
addon => pkg.categorizeDependency(addon.name) !== 'peerDependencies'
);
if (pkg === this.appPackageWithMovedDeps) {
let extras = [this.synthVendor, this.synthStyles].filter(this.isActiveAddon) as AddonPackage[];
result = [...result, ...extras];
}
return result.sort(this.orderAddons);
}
@Memoize()
private get allActiveAddons(): AddonPackage[] {
let result = this.appPackageWithMovedDeps.findDescendants(this.isActiveAddon) as AddonPackage[];
let extras = [this.synthVendor, this.synthStyles].filter(this.isActiveAddon) as AddonPackage[];
let extraDescendants = flatMap(extras, dep => dep.findDescendants(this.isActiveAddon)) as AddonPackage[];
result = [...result, ...extras, ...extraDescendants];
return result.sort(this.orderAddons);
}
@bind
private isActiveAddon(pkg: Package): boolean {
// stage1 already took care of converting everything that's actually active
// into v2 addons. If it's not a v2 addon, we don't want it.
//
// We can encounter v1 addons here when there is inactive stuff floating
// around in the node_modules that accidentally satisfy something like an
// optional peer dep.
return pkg.isV2Addon();
}
@bind
private orderAddons(depA: Package, depB: Package): number {
let depAIdx = 0;
let depBIdx = 0;
if (depA && depA.meta && depA.isV2Addon()) {
depAIdx = depA.meta['order-index'] || 0;
}
if (depB && depB.meta && depB.isV2Addon()) {
depBIdx = depB.meta['order-index'] || 0;
}
return depAIdx - depBIdx;
}
private resolvableExtensions(): string[] {
// webpack's default is ['.wasm', '.mjs', '.js', '.json']. Keeping that
// subset in that order is sensible, since many third-party libraries will
// expect it to work that way.
//
// For TS, we defer to ember-cli-babel, and the setting for
// "enableTypescriptTransform" can be set with and without
// ember-cli-typescript
return ['.wasm', '.mjs', '.js', '.json', '.ts', '.hbs', '.hbs.js'];
}
private *emberEntrypoints(htmlTreePath: string): IterableIterator<Asset> {
let classicEntrypoints = [
{ entrypoint: 'index.html', includeTests: false },
{ entrypoint: 'tests/index.html', includeTests: true },
];
if (!this.compatApp.shouldBuildTests) {
classicEntrypoints.pop();
}
for (let { entrypoint, includeTests } of classicEntrypoints) {
let sourcePath = join(htmlTreePath, entrypoint);
let stats = statSync(sourcePath);
let asset: EmberAsset = {
kind: 'ember',
relativePath: entrypoint,
includeTests,
sourcePath,
mtime: stats.mtime.getTime(),
size: stats.size,
rootURL: this.rootURL(),
prepare: (dom: JSDOM) => {
let scripts = [...dom.window.document.querySelectorAll('script')];
let styles = [...dom.window.document.querySelectorAll('link[rel*="stylesheet"]')] as HTMLLinkElement[];
return {
javascript: this.compatApp.findAppScript(scripts, entrypoint),
styles: this.compatApp.findAppStyles(styles, entrypoint),
implicitScripts: this.compatApp.findVendorScript(scripts, entrypoint),
implicitStyles: this.compatApp.findVendorStyles(styles, entrypoint),
testJavascript: this.compatApp.findTestScript(scripts),
implicitTestScripts: this.compatApp.findTestSupportScript(scripts),
implicitTestStyles: this.compatApp.findTestSupportStyles(styles),
};
},
};
yield asset;
}
}
private modulePrefix(): string {
return this.configTree.readConfig().modulePrefix;
}
private podModulePrefix(): string | undefined {
return this.configTree.readConfig().podModulePrefix;
}
private rootURL(): string {
return this.configTree.readConfig().rootURL;
}
@Memoize()
private activeRules() {
return activePackageRules(this.options.packageRules.concat(defaultAddonPackageRules()), [
{ name: this.origAppPackage.name, version: this.origAppPackage.version, root: this.root },
...this.allActiveAddons.filter(p => p.meta['auto-upgraded']),
]);
}
private resolverConfig(engines: AppFiles[]): CompatResolverOptions {
let renamePackages = Object.assign({}, ...this.allActiveAddons.map(dep => dep.meta['renamed-packages']));
let renameModules = Object.assign({}, ...this.allActiveAddons.map(dep => dep.meta['renamed-modules']));
let activeAddons: CompatResolverOptions['activeAddons'] = {};
for (let addon of this.allActiveAddons) {
activeAddons[addon.name] = addon.root;
}
let options: CompatResolverOptions['options'] = {
staticHelpers: this.options.staticHelpers,
staticModifiers: this.options.staticModifiers,
staticComponents: this.options.staticComponents,
allowUnsafeDynamicComponents: this.options.allowUnsafeDynamicComponents,
};
let config: CompatResolverOptions = {
// this part is the base ModuleResolverOptions as required by @embroider/core
activeAddons,
renameModules,
renamePackages,
resolvableExtensions: this.resolvableExtensions(),
appRoot: this.origAppPackage.root,
engines: engines.map((appFiles, index) => ({
packageName: appFiles.engine.package.name,
// first engine is the app, which has been relocated to this.root
// we need to use the real path here because webpack requests always use the real path i.e. follow symlinks
root: realpathSync(index === 0 ? this.root : appFiles.engine.package.root),
fastbootFiles: appFiles.fastbootFiles,
activeAddons: [...appFiles.engine.addons]
.map(a => ({
name: a.name,
root: a.root,
}))
// the traditional order is the order in which addons will run, such
// that the last one wins. Our resolver's order is the order to
// search, so first one wins.
.reverse(),
})),
amdCompatibility: this.options.amdCompatibility,
// this is the additional stufff that @embroider/compat adds on top to do
// global template resolving
modulePrefix: this.modulePrefix(),
podModulePrefix: this.podModulePrefix(),
activePackageRules: this.activeRules(),
options,
};
return config;
}
private scriptPriority(pkg: Package) {
switch (pkg.name) {
case 'loader.js':
return 0;
case 'ember-source':
return 10;
default:
return 1000;
}
}
@Memoize()
private get resolvableExtensionsPattern(): RegExp {
return extensionsPattern(this.resolvableExtensions());
}
private impliedAssets(
type: keyof ImplicitAssetPaths,
engine: AppFiles,
emberENV?: EmberENV
): (OnDiskAsset | InMemoryAsset)[] {
let result: (OnDiskAsset | InMemoryAsset)[] = this.impliedAddonAssets(type, engine).map(
(sourcePath: string): OnDiskAsset => {
let stats = statSync(sourcePath);
return {
kind: 'on-disk',
relativePath: explicitRelative(this.root, sourcePath),
sourcePath,
mtime: stats.mtimeMs,
size: stats.size,
};
}
);
if (type === 'implicit-scripts') {
result.unshift({
kind: 'in-memory',
relativePath: '_testing_prefix_.js',
source: `var runningTests=false;`,
});
result.unshift({
kind: 'in-memory',
relativePath: '_ember_env_.js',
source: `window.EmberENV={ ...(window.EmberENV || {}), ...${JSON.stringify(emberENV, null, 2)} };`,
});
result.push({
kind: 'in-memory',
relativePath: '_loader_.js',
source: `loader.makeDefaultExport=false;`,
});
}
if (type === 'implicit-test-scripts') {
// this is the traditional test-support-suffix.js
result.push({
kind: 'in-memory',
relativePath: '_testing_suffix_.js',
source: `
var runningTests=true;
if (typeof Testem !== 'undefined' && (typeof QUnit !== 'undefined' || typeof Mocha !== 'undefined')) {
Testem.hookIntoTestFramework();
}`,
});
// whether or not anybody was actually using @embroider/macros
// explicitly as an addon, we ensure its test-support file is always
// present.
if (!result.find(s => s.kind === 'on-disk' && s.sourcePath.endsWith('embroider-macros-test-support.js'))) {
result.unshift({
kind: 'on-disk',
sourcePath: require.resolve('@embroider/macros/src/vendor/embroider-macros-test-support'),
mtime: 0,
size: 0,
relativePath: 'embroider-macros-test-support.js',
});
}
}
return result;
}
private impliedAddonAssets(type: keyof ImplicitAssetPaths, { engine }: AppFiles): string[] {
let result: Array<string> = [];
for (let addon of sortBy(Array.from(engine.addons), this.scriptPriority.bind(this))) {
let implicitScripts = addon.meta[type];
if (implicitScripts) {
let styles = [];
let options = { basedir: addon.root };
for (let mod of implicitScripts) {
if (type === 'implicit-styles') {
// exclude engines because they will handle their own css importation
if (!addon.isLazyEngine()) {
styles.push(resolve.sync(mod, options));
}
} else {
result.push(resolve.sync(mod, options));
}
}
if (styles.length) {
result = [...styles, ...result];
}
}
}
return result;
}
@Memoize()
private babelConfig(resolverConfig: CompatResolverOptions) {
let babel = cloneDeep(this.compatApp.babelConfig());
if (!babel.plugins) {
babel.plugins = [];
}
// Our stage3 code is always allowed to use dynamic import. We may emit it
// ourself when splitting routes.
babel.plugins.push(require.resolve('@babel/plugin-syntax-dynamic-import'));
// https://github.com/webpack/webpack/issues/12154
babel.plugins.push(require.resolve('./rename-require-plugin'));
babel.plugins.push([require.resolve('babel-plugin-ember-template-compilation'), this.etcOptions(resolverConfig)]);
// this is @embroider/macros configured for full stage3 resolution
babel.plugins.push(...this.compatApp.macrosConfig.babelPluginConfig());
let colocationOptions: TemplateColocationPluginOptions = {
appRoot: this.origAppPackage.root,
// This extra weirdness is a compromise in favor of build performance.
//
// 1. When auto-upgrading an addon from v1 to v2, we definitely want to
// run any custom AST transforms in stage1.
//
// 2. In general case, AST transforms are allowed to manipulate Javascript
// scope. This means that running transforms -- even when we're doing
// source-to-source compilation that emits handlebars and not wire
// format -- implies changing .hbs files into .js files.
//
// 3. So stage1 may need to rewrite .hbs to .hbs.js (to avoid colliding
// with an existing co-located .js file).
//
// 4. But stage1 doesn't necessarily want to run babel over the
// corresponding JS file. Most of the time, that's just an
// unnecessarily expensive second parse. (We only run it in stage1 to
// eliminate an addon's custom babel plugins, and many addons don't
// have any.)
//
// 5. Therefore, the work of template-colocation gets defered until here,
// and it may see co-located templates named `.hbs.js` instead of the
// usual `.hbs.
templateExtensions: ['.hbs', '.hbs.js'],
// All of the above only applies to auto-upgraded packages that were
// authored in v1. V2 packages don't get any of this complexity, they're
// supposed to take care of colocating their own templates explicitly.
packageGuard: true,
};
babel.plugins.push([templateColocationPluginPath, colocationOptions]);
babel.plugins.push([
require.resolve('./babel-plugin-adjust-imports'),
(() => {
let pluginConfig: AdjustImportsOptions = {
appRoot: resolverConfig.appRoot,
};
return pluginConfig;
})(),
]);
// we can use globally shared babel runtime by default
babel.plugins.push([
require.resolve('@babel/plugin-transform-runtime'),
{ absoluteRuntime: __dirname, useESModules: true, regenerator: false },
]);
const portable = makePortable(babel, { basedir: this.root }, this.portableHints);
addCachablePlugin(portable.config);
return portable;
}
private insertEmberApp(
asset: ParsedEmberAsset,
appFiles: AppFiles[],
prepared: Map<string, InternalAsset>,
emberENV: EmberENV
) {
let html = asset.html;
if (this.fastbootConfig) {
// ignore scripts like ember-cli-livereload.js which are not really associated with
// "the app".
let ignoreScripts = html.dom.window.document.querySelectorAll('script');
ignoreScripts.forEach(script => {
script.setAttribute('data-fastboot-ignore', '');
});
}
// our tests entrypoint already includes a correct module dependency on the
// app, so we only insert the app when we're not inserting tests
if (!asset.fileAsset.includeTests) {
let appJS = this.topAppJSAsset(appFiles, prepared);
html.insertScriptTag(html.javascript, appJS.relativePath, { type: 'module' });
}
if (this.fastbootConfig) {
// any extra fastboot app files get inserted into our html.javascript
// section, after the app has been inserted.
for (let script of this.fastbootConfig.extraAppFiles) {
html.insertScriptTag(html.javascript, script, { tag: 'fastboot-script' });
}
}
html.insertStyleLink(html.styles, `assets/${this.origAppPackage.name}.css`);
const parentEngine = appFiles.find(e => !e.engine.parent)!;
let vendorJS = this.implicitScriptsAsset(prepared, parentEngine, emberENV);
if (vendorJS) {
html.insertScriptTag(html.implicitScripts, vendorJS.relativePath);
}
if (this.fastbootConfig) {
// any extra fastboot vendor files get inserted into our
// html.implicitScripts section, after the regular implicit script
// (vendor.js) have been inserted.
for (let script of this.fastbootConfig.extraVendorFiles) {
html.insertScriptTag(html.implicitScripts, script, { tag: 'fastboot-script' });
}
}
let implicitStyles = this.implicitStylesAsset(prepared, parentEngine);
if (implicitStyles) {
html.insertStyleLink(html.implicitStyles, implicitStyles.relativePath);
}
if (!asset.fileAsset.includeTests) {
return;
}
// Test-related assets happen below this point
let testJS = this.testJSEntrypoint(appFiles, prepared);
html.insertScriptTag(html.testJavascript, testJS.relativePath, { type: 'module' });
let implicitTestScriptsAsset = this.implicitTestScriptsAsset(prepared, parentEngine);
if (implicitTestScriptsAsset) {
html.insertScriptTag(html.implicitTestScripts, implicitTestScriptsAsset.relativePath);
}
let implicitTestStylesAsset = this.implicitTestStylesAsset(prepared, parentEngine);
if (implicitTestStylesAsset) {
html.insertStyleLink(html.implicitTestStyles, implicitTestStylesAsset.relativePath);
}
}
private implicitScriptsAsset(
prepared: Map<string, InternalAsset>,
application: AppFiles,
emberENV: EmberENV
): InternalAsset | undefined {
let asset = prepared.get('assets/vendor.js');
if (!asset) {
let implicitScripts = this.impliedAssets('implicit-scripts', application, emberENV);
if (implicitScripts.length > 0) {
asset = new ConcatenatedAsset('assets/vendor.js', implicitScripts, this.resolvableExtensionsPattern);
prepared.set(asset.relativePath, asset);
}
}
return asset;
}
private implicitStylesAsset(prepared: Map<string, InternalAsset>, application: AppFiles): InternalAsset | undefined {
let asset = prepared.get('assets/vendor.css');
if (!asset) {
let implicitStyles = this.impliedAssets('implicit-styles', application);
if (implicitStyles.length > 0) {
// we reverse because we want the synthetic vendor style at the top
asset = new ConcatenatedAsset('assets/vendor.css', implicitStyles.reverse(), this.resolvableExtensionsPattern);
prepared.set(asset.relativePath, asset);
}
}
return asset;
}
private implicitTestScriptsAsset(
prepared: Map<string, InternalAsset>,
application: AppFiles
): InternalAsset | undefined {
let testSupportJS = prepared.get('assets/test-support.js');
if (!testSupportJS) {
let implicitTestScripts = this.impliedAssets('implicit-test-scripts', application);
if (implicitTestScripts.length > 0) {
testSupportJS = new ConcatenatedAsset(
'assets/test-support.js',
implicitTestScripts,
this.resolvableExtensionsPattern
);
prepared.set(testSupportJS.relativePath, testSupportJS);
}
}
return testSupportJS;
}
private implicitTestStylesAsset(
prepared: Map<string, InternalAsset>,
application: AppFiles
): InternalAsset | undefined {
let asset = prepared.get('assets/test-support.css');
if (!asset) {
let implicitTestStyles = this.impliedAssets('implicit-test-styles', application);
if (implicitTestStyles.length > 0) {
asset = new ConcatenatedAsset('assets/test-support.css', implicitTestStyles, this.resolvableExtensionsPattern);
prepared.set(asset.relativePath, asset);
}
}
return asset;
}
// recurse to find all active addons that don't cross an engine boundary.
// Inner engines themselves will be returned, but not those engines' children.
// The output set's insertion order is the proper ember-cli compatible
// ordering of the addons.
private findActiveAddons(pkg: Package, engine: Engine, isChild = false): void {
for (let child of this.activeAddonChildren(pkg)) {
if (!child.isEngine()) {
this.findActiveAddons(child, engine, true);
}
engine.addons.add(child);
}
// ensure addons are applied in the correct order, if set (via @embroider/compat/v1-addon)
if (!isChild) {
engine.addons = new Set(
[...engine.addons].sort((a, b) => {
return (a.meta['order-index'] || 0) - (b.meta['order-index'] || 0);
})
);
}
}
private partitionEngines(appJSPath: string): Engine[] {
let queue: Engine[] = [
{
package: this.appPackageWithMovedDeps,
addons: new Set(),
parent: undefined,
sourcePath: appJSPath,
modulePrefix: this.modulePrefix(),
appRelativePath: '.',
},
];
let done: Engine[] = [];
let seenEngines: Set<Package> = new Set();
while (true) {
let current = queue.shift();
if (!current) {
break;
}
this.findActiveAddons(current.package, current);
for (let addon of current.addons) {
if (addon.isEngine() && !seenEngines.has(addon)) {
seenEngines.add(addon);
queue.push({
package: addon,
addons: new Set(),
parent: current,
sourcePath: addon.root,
modulePrefix: addon.name,
appRelativePath: explicitRelative(this.root, addon.root),
});
}
}
done.push(current);
}
return done;
}
@Memoize()
private get activeFastboot() {
return this.activeAddonChildren(this.appPackageWithMovedDeps).find(a => a.name === 'ember-cli-fastboot');
}
@Memoize()
private get fastbootConfig():
| { packageJSON: PackageInfo; extraAppFiles: string[]; extraVendorFiles: string[] }
| undefined {
if (this.activeFastboot) {
// this is relying on work done in stage1 by @embroider/compat/src/compat-adapters/ember-cli-fastboot.ts
let packageJSON = readJSONSync(join(this.activeFastboot.root, '_fastboot_', 'package.json'));
let { extraAppFiles, extraVendorFiles } = packageJSON['embroider-fastboot'];
delete packageJSON['embroider-fastboot'];
extraVendorFiles.push('assets/embroider_macros_fastboot_init.js');
return { packageJSON, extraAppFiles, extraVendorFiles };
}
}
private engines: { engine: Engine; appSync: SyncDir; fastbootSync: SyncDir | undefined }[] | undefined;
private updateAppJS(appJSPath: string): AppFiles[] {
if (!this.engines) {
this.engines = this.partitionEngines(appJSPath).map(engine => {
if (engine.sourcePath === appJSPath) {
// this is the app. We have more to do for the app than for other
// engines.
let fastbootSync: SyncDir | undefined;
if (this.activeFastboot) {
let fastbootDir = this.fastbootJSSrcDir();
if (fastbootDir) {
fastbootSync = new SyncDir(fastbootDir, resolvePath(this.root, '_fastboot_'));
}
}
return {
engine,
appSync: new SyncDir(appJSPath, this.root),
fastbootSync,
};
} else {
// this is not the app, so it's some other engine. Engines are already
// built by stage1 like all other addons, so we only need to observe
// their files, not doing any actual copying or building.
return {
engine,
appSync: new SyncDir(engine.sourcePath, undefined),
// AFAIK, we've never supported a fastboot overlay directory in an
// engine. But if we do need that, it would go here.
fastbootSync: undefined,
};
}
});
}
for (let engine of this.engines) {
engine.appSync.update();
engine.fastbootSync?.update();
}
return this.engines.map(
({ engine, appSync, fastbootSync }) =>
new AppFiles(
engine,
appSync.files,
fastbootSync?.files ?? new Set(),
this.resolvableExtensionsPattern,
this.podModulePrefix()
)
);
}
private prepareAsset(asset: Asset, appFiles: AppFiles[], prepared: Map<string, InternalAsset>, emberENV: EmberENV) {
if (asset.kind === 'ember') {
let prior = this.assets.get(asset.relativePath);
let parsed: ParsedEmberAsset;
if (prior && prior.kind === 'built-ember' && prior.parsedAsset.validFor(asset)) {
// we can reuse the parsed html
parsed = prior.parsedAsset;
parsed.html.clear();
} else {
parsed = new ParsedEmberAsset(asset);
}
this.insertEmberApp(parsed, appFiles, prepared, emberENV);
prepared.set(asset.relativePath, new BuiltEmberAsset(parsed));
} else {
prepared.set(asset.relativePath, asset);
}
}
private prepareAssets(
requestedAssets: Asset[],
appFiles: AppFiles[],
emberENV: EmberENV
): Map<string, InternalAsset> {
let prepared: Map<string, InternalAsset> = new Map();
for (let asset of requestedAssets) {
this.prepareAsset(asset, appFiles, prepared, emberENV);
}
return prepared;
}
private assetIsValid(asset: InternalAsset, prior: InternalAsset | undefined): boolean {
if (!prior) {
return false;
}
switch (asset.kind) {
case 'on-disk':
return prior.kind === 'on-disk' && prior.size === asset.size && prior.mtime === asset.mtime;
case 'in-memory':
return prior.kind === 'in-memory' && stringOrBufferEqual(prior.source, asset.source);
case 'built-ember':
return prior.kind === 'built-ember' && prior.source === asset.source;
case 'concatenated-asset':
return (
prior.kind === 'concatenated-asset' &&
prior.sources.length === asset.sources.length &&
prior.sources.every((priorFile, index) => {
let newFile = asset.sources[index];
return this.assetIsValid(newFile, priorFile);
})
);
}
}
private updateOnDiskAsset(asset: OnDiskAsset) {
let destination = join(this.root, asset.relativePath);
ensureDirSync(dirname(destination));
copySync(asset.sourcePath, destination, { dereference: true });
}
private updateInMemoryAsset(asset: InMemoryAsset) {
let destination = join(this.root, asset.relativePath);
ensureDirSync(dirname(destination));
writeFileSync(destination, asset.source, 'utf8');
}
private updateBuiltEmberAsset(asset: BuiltEmberAsset) {
let destination = join(this.root, asset.relativePath);
ensureDirSync(dirname(destination));
writeFileSync(destination, asset.source, 'utf8');
}
private async updateConcatenatedAsset(asset: ConcatenatedAsset) {
let concat = new SourceMapConcat({
outputFile: join(this.root, asset.relativePath),
mapCommentType: asset.relativePath.endsWith('.js') ? 'line' : 'block',
baseDir: this.root,
});
if (process.env.EMBROIDER_CONCAT_STATS) {
let MeasureConcat = (await import('@embroider/core/src/measure-concat')).default;
concat = new MeasureConcat(asset.relativePath, concat, this.root);
}
for (let source of asset.sources) {
switch (source.kind) {
case 'on-disk':
concat.addFile(explicitRelative(this.root, source.sourcePath));
break;
case 'in-memory':
if (typeof source.source !== 'string') {
throw new Error(`attempted to concatenated a Buffer-backed in-memory asset`);
}
concat.addSpace(source.source);
break;
default:
assertNever(source);
}
}
await concat.end();
}
private async updateAssets(requestedAssets: Asset[], appFiles: AppFiles[], emberENV: EmberENV) {
let assets = this.prepareAssets(requestedAssets, appFiles, emberENV);
for (let asset of assets.values()) {
if (this.assetIsValid(asset, this.assets.get(asset.relativePath))) {
continue;
}
debug('rebuilding %s', asset.relativePath);
switch (asset.kind) {
case 'on-disk':
this.updateOnDiskAsset(asset);
break;
case 'in-memory':
this.updateInMemoryAsset(asset);
break;
case 'built-ember':
this.updateBuiltEmberAsset(asset);
break;
case 'concatenated-asset':
await this.updateConcatenatedAsset(asset);
break;
default:
assertNever(asset);
}
}
for (let oldAsset of this.assets.values()) {
if (!assets.has(oldAsset.relativePath)) {
unlinkSync(join(this.root, oldAsset.relativePath));
}
}
this.assets = assets;
return [...assets.values()];
}
private gatherAssets(inputPaths: OutputPaths<TreeNames>): Asset[] {
// first gather all the assets out of addons
let assets: Asset[] = [];
for (let pkg of this.allActiveAddons) {
if (pkg.meta['public-assets']) {
for (let [filename, appRelativeURL] of Object.entries(pkg.meta['public-assets'] || {})) {
let sourcePath = resolvePath(pkg.root, filename);
let stats = statSync(sourcePath);
assets.push({
kind: 'on-disk',
sourcePath,
relativePath: appRelativeURL,
mtime: stats.mtimeMs,
size: stats.size,
});
}
}
}
if (this.activeFastboot) {
const source = `
(function(){
var key = '_embroider_macros_runtime_config';
if (!window[key]){ window[key] = [];}
window[key].push(function(m) {
m.setGlobalConfig('fastboot', Object.assign({}, m.getGlobalConfig().fastboot, { isRunning: true }));
});
}())`;
assets.push({
kind: 'in-memory',
source,
relativePath: 'assets/embroider_macros_fastboot_init.js',
});
}
// and finally tack on the ones from our app itself
return assets.concat(this.extractAssets(inputPaths));
}
private firstBuild = true;
async build(inputPaths: OutputPaths<TreeNames>) {
// on the first build, we lock down the macros config. on subsequent builds,
// this doesn't do anything anyway because it's idempotent.
this.compatApp.macrosConfig.finalize();
// on first build, clear the output directory completely
if (this.firstBuild) {
rmSync(this.root, { recursive: true, force: true });
this.firstBuild = false;
}
let appFiles = this.updateAppJS(inputPaths.appJS);
let emberENV = this.configTree.readConfig().EmberENV;
let assets = this.gatherAssets(inputPaths);
let finalAssets = await this.updateAssets(assets, appFiles, emberENV);
let assetPaths = assets.map(asset => asset.relativePath);
if (this.activeFastboot) {
// when using fastboot, our own package.json needs to be in the output so fastboot can read it.
assetPaths.push('package.json');
}
for (let asset of finalAssets) {
// our concatenated assets all have map files that ride along. Here we're
// telling the final stage packager to be sure and serve the map files
// too.
if (asset.kind === 'concatenated-asset') {
assetPaths.push(asset.sourcemapPath);
}
}
let meta: AppMeta = {
type: 'app',
version: 2,
assets: assetPaths,
babel: {
filename: '_babel_config_.js',
isParallelSafe: true, // TODO
majorVersion: this.compatApp.babelMajorVersion(),
fileFilter: '_babel_filter_.js',
},
'root-url': this.rootURL(),
};
// all compat apps are auto-upgraded, there's no v2 app format here
meta['auto-upgraded'] = true;
let pkg = this.combinePackageJSON(meta);
writeFileSync(join(this.root, 'package.json'), JSON.stringify(pkg, null, 2), 'utf8');
let resolverConfig = this.resolverConfig(appFiles);
this.addResolverConfig(resolverConfig);
let babelConfig = this.babelConfig(resolverConfig);
this.addBabelConfig(babelConfig);
}
private combinePackageJSON(meta: AppMeta): object {
let pkgLayers: any[] = [this.origAppPackage.packageJSON];
let fastbootConfig = this.fastbootConfig;
if (fastbootConfig) {
// fastboot-specific package.json output is allowed to add to our original package.json
pkgLayers.push(fastbootConfig.packageJSON);