-
Notifications
You must be signed in to change notification settings - Fork 142
/
Copy pathresolver-transform.ts
1163 lines (1060 loc) · 37.8 KB
/
resolver-transform.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 { ASTv1, ASTPlugin, ASTPluginBuilder, ASTPluginEnvironment, WalkerPath } from '@glimmer/syntax';
import type {
PreprocessedComponentRule,
ActivePackageRules,
ComponentRules,
PackageRules,
ModuleRules,
} from './dependency-rules';
import { preprocessComponentRule, appTreeRulesDir } from './dependency-rules';
import { Memoize } from 'typescript-memoize';
import type { WithJSUtils } from 'babel-plugin-ember-template-compilation';
import assertNever from 'assert-never';
import { join, sep } from 'path';
import { readJSONSync } from 'fs-extra';
import { dasherize, snippetToDasherizedName } from './dasherize-component-name';
import type { ResolverOptions as CoreResolverOptions } from '@embroider/core';
import { Resolver, cleanUrl, locateEmbroiderWorkingDir } from '@embroider/core';
import type CompatOptions from './options';
import type { AuditMessage, Loc } from './audit';
import { camelCase, mergeWith } from 'lodash';
import { satisfies } from 'semver';
type Env = WithJSUtils<ASTPluginEnvironment> & {
filename: string;
contents: string;
strictMode?: boolean;
locals?: string[];
};
// this is a subset of the full Options. We care about serializability, and we
// only needs parts that are easily serializable, which is why we don't keep the
// whole thing.
type UserConfig = Pick<
Required<CompatOptions>,
'staticHelpers' | 'staticModifiers' | 'staticComponents' | 'allowUnsafeDynamicComponents'
>;
export interface CompatResolverOptions extends CoreResolverOptions {
activePackageRules: ActivePackageRules[];
options: UserConfig;
}
export interface Options {
appRoot: string;
emberVersion: string;
}
type BuiltIn = {
importableHelper?: [string, string];
importableComponent?: [string, string];
importableModifier?: [string, string];
};
function builtInKeywords(emberVersion: string): Record<string, BuiltIn | undefined> {
const builtInKeywords: Record<string, BuiltIn | undefined> = {
'-get-dynamic-var': {},
'-in-element': {},
'-with-dynamic-vars': {},
action: {},
array: {
importableHelper: ['array', '@ember/helper'],
},
component: {},
concat: {
importableHelper: ['concat', '@ember/helper'],
},
debugger: {},
'each-in': {},
each: {},
fn: {
importableHelper: ['fn', '@ember/helper'],
},
get: {
importableHelper: ['get', '@ember/helper'],
},
'has-block-params': {},
'has-block': {},
hasBlock: {},
hasBlockParams: {},
hash: {
importableHelper: ['hash', '@ember/helper'],
},
helper: {},
if: {},
'in-element': {},
input: {
importableComponent: ['Input', '@ember/component'],
},
let: {},
'link-to': {
importableComponent: ['LinkTo', '@ember/routing'],
},
loc: {},
log: {},
modifier: {},
mount: {},
mut: {},
on: {
importableModifier: ['on', '@ember/modifier'],
},
outlet: {},
partial: {},
'query-params': {},
readonly: {},
textarea: {
importableComponent: ['Textarea', '@ember/component'],
},
unbound: {},
'unique-id': {},
unless: {},
with: {},
yield: {},
};
if (satisfies(emberVersion, '>=5.2')) {
builtInKeywords['unique-id'] = {
importableHelper: ['uniqueId', '@ember/helper'],
};
}
return builtInKeywords;
}
interface ComponentResolution {
type: 'component';
specifier: string;
importedName: string;
yieldsComponents: Required<ComponentRules>['yieldsSafeComponents'];
yieldsArguments: Required<ComponentRules>['yieldsArguments'];
argumentsAreComponents: string[];
nameHint: string;
}
type HelperResolution = {
type: 'helper';
nameHint: string;
specifier: string;
importedName: string;
};
type ModifierResolution = {
type: 'modifier';
specifier: string;
importedName: string;
nameHint: string;
};
type ResolutionResult = ComponentResolution | HelperResolution | ModifierResolution;
interface ResolutionFail {
type: 'error';
message: string;
detail: string;
loc: Loc;
}
type Resolution = ResolutionResult | ResolutionFail;
type ComponentLocator =
| {
type: 'literal';
path: string;
}
| {
type: 'path';
path: string;
}
| {
type: 'other';
};
class TemplateResolver implements ASTPlugin {
readonly name = 'embroider-build-time-resolver';
private auditHandler: undefined | ((msg: AuditMessage) => void);
private scopeStack = new ScopeStack();
private moduleResolver: Resolver;
constructor(
private env: Env,
private config: CompatResolverOptions,
private builtInsForEmberVersion: ReturnType<typeof builtInKeywords>
) {
this.moduleResolver = new Resolver(config);
if ((globalThis as any).embroider_audit) {
this.auditHandler = (globalThis as any).embroider_audit;
}
}
private emit<Target extends WalkerPath<ASTv1.Node>>(
parentPath: Target,
resolution: Resolution | null,
setter: (target: Target['node'], newIdentifier: ASTv1.PathExpression) => void
) {
switch (resolution?.type) {
case 'error':
this.reportError(resolution);
return;
case 'component':
case 'modifier':
case 'helper': {
let name = this.env.meta.jsutils.bindImport(resolution.specifier, resolution.importedName, parentPath, {
nameHint: resolution.nameHint,
});
setter(parentPath.node, this.env.syntax.builders.path(name));
return;
}
case undefined:
return;
default:
assertNever(resolution);
}
}
private reportError(dep: ResolutionFail) {
if (!this.auditHandler && !this.config.options.allowUnsafeDynamicComponents) {
let e: any = new Error(`${dep.message}: ${dep.detail} in ${this.humanReadableFile(this.env.filename)}`);
e.isTemplateResolverError = true;
e.loc = dep.loc;
e.moduleName = this.env.filename;
throw e;
}
if (this.auditHandler) {
this.auditHandler({
message: dep.message,
filename: this.env.filename,
detail: dep.detail,
loc: dep.loc,
source: this.env.contents,
});
}
}
private humanReadableFile(file: string) {
let { appRoot } = this.config;
if (!appRoot.endsWith(sep)) {
appRoot += sep;
}
if (file.startsWith(appRoot)) {
return file.slice(appRoot.length);
}
return file;
}
private handleComponentHelper(
param: ASTv1.Node,
impliedBecause?: { componentName: string; argumentName: string }
): ComponentResolution | ResolutionFail | null {
let locator: ComponentLocator;
switch (param.type) {
case 'StringLiteral':
locator = { type: 'literal', path: param.value };
break;
case 'PathExpression':
locator = { type: 'path', path: param.original };
break;
case 'MustacheStatement':
if (param.hash.pairs.length === 0 && param.params.length === 0) {
return this.handleComponentHelper(param.path, impliedBecause);
} else if (param.path.type === 'PathExpression' && param.path.original === 'component') {
// safe because we will handle this inner `{{component ...}}` mustache on its own
return null;
} else {
locator = { type: 'other' };
}
break;
case 'TextNode':
locator = { type: 'literal', path: param.chars };
break;
case 'SubExpression':
if (param.path.type === 'PathExpression' && param.path.original === 'component') {
// safe because we will handle this inner `(component ...)` subexpression on its own
return null;
}
if (param.path.type === 'PathExpression' && param.path.original === 'ensure-safe-component') {
// safe because we trust ensure-safe-component
return null;
}
locator = { type: 'other' };
break;
default:
locator = { type: 'other' };
}
if (locator.type === 'path' && this.scopeStack.safeComponentInScope(locator.path)) {
return null;
}
return this.targetComponentHelper(locator, param.loc, impliedBecause);
}
private handleDynamicComponentArguments(
componentName: string,
argumentsAreComponents: string[],
attributes: WalkerPath<ASTv1.AttrNode | ASTv1.HashPair>[]
) {
for (let name of argumentsAreComponents) {
let attr = attributes.find(attr => {
if (attr.node.type === 'AttrNode') {
return attr.node.name === '@' + name;
} else {
return attr.node.key === name;
}
});
if (attr) {
let resolution = this.handleComponentHelper(attr.node.value, {
componentName,
argumentName: name,
});
this.emit(attr, resolution, (node, newId) => {
if (node.type === 'AttrNode') {
node.value = this.env.syntax.builders.mustache(newId);
} else {
node.value = newId;
}
});
}
}
}
private get staticComponentsEnabled(): boolean {
return this.config.options.staticComponents || Boolean(this.auditHandler);
}
private get staticHelpersEnabled(): boolean {
return this.config.options.staticHelpers || Boolean(this.auditHandler);
}
private get staticModifiersEnabled(): boolean {
return this.config.options.staticModifiers || Boolean(this.auditHandler);
}
private isIgnoredComponent(dasherizedName: string) {
return this.rules.components.get(dasherizedName)?.safeToIgnore;
}
@Memoize()
private get rules() {
// rules that are keyed by the filename they're talking about
let files: Map<string, PreprocessedComponentRule> = new Map();
// rules that are keyed by our dasherized interpretation of the component's name
let components: Map<string, PreprocessedComponentRule> = new Map();
// we're not responsible for filtering out rules for inactive packages here,
// that is done before getting to us. So we should assume these are all in
// force.
for (let rule of this.config.activePackageRules) {
if (rule.components) {
for (let [snippet, rules] of Object.entries(rule.components)) {
let processedRules = preprocessComponentRule(rules);
let dasherizedName = this.standardDasherize(snippet, rule);
components.set(dasherizedName, processedRules);
if (rules.layout) {
for (let root of rule.roots) {
if (rules.layout.addonPath) {
files.set(join(root, rules.layout.addonPath), processedRules);
}
if (rules.layout.appPath) {
files.set(join(root, rules.layout.appPath), processedRules);
}
}
}
}
}
if (rule.appTemplates) {
for (let [path, templateRules] of Object.entries(rule.appTemplates)) {
let processedRules = preprocessComponentRule(templateRules);
for (let root of rule.roots) {
files.set(join(appTreeRulesDir(root, this.moduleResolver), path), processedRules);
}
}
}
if (rule.addonTemplates) {
for (let [path, templateRules] of Object.entries(rule.addonTemplates)) {
let processedRules = preprocessComponentRule(templateRules);
for (let root of rule.roots) {
files.set(join(root, path), processedRules);
}
}
}
}
return { files, components };
}
private findRules(absPath: string): PreprocessedComponentRule | undefined {
// when babel is invoked by vite our filenames can have query params still
// hanging off them. That would break rule matching.
absPath = cleanUrl(absPath, true);
let fileRules = this.rules.files.get(absPath);
let componentRules: PreprocessedComponentRule | undefined;
let componentName = this.moduleResolver.reverseComponentLookup(absPath);
if (componentName) {
componentRules = this.rules.components.get(componentName);
}
if (fileRules && componentRules) {
return mergeWith(fileRules, componentRules, appendArrays);
}
return fileRules ?? componentRules;
}
private standardDasherize(snippet: string, rule: PackageRules | ModuleRules): string {
let name = snippetToDasherizedName(snippet);
if (name == null) {
throw new Error(`unable to parse component snippet "${snippet}" from rule ${JSON.stringify(rule, null, 2)}`);
}
return name;
}
private targetComponent(name: string): ComponentResolution | null {
if (!this.staticComponentsEnabled) {
return null;
}
const builtIn = this.builtInsForEmberVersion[name];
if (builtIn?.importableComponent) {
let [importedName, specifier] = builtIn.importableComponent;
return {
type: 'component',
specifier,
importedName,
yieldsComponents: [],
yieldsArguments: [],
argumentsAreComponents: [],
nameHint: importedName,
};
}
if (builtIn) {
return null;
}
if (this.isIgnoredComponent(name)) {
return null;
}
let componentRules = this.rules.components.get(name);
return {
type: 'component',
specifier: `#embroider_compat/components/${name}`,
importedName: 'default',
yieldsComponents: componentRules ? componentRules.yieldsSafeComponents : [],
yieldsArguments: componentRules ? componentRules.yieldsArguments : [],
argumentsAreComponents: componentRules ? componentRules.argumentsAreComponents : [],
nameHint: this.nameHint(name),
};
}
private targetComponentHelper(
component: ComponentLocator,
loc: Loc,
impliedBecause?: { componentName: string; argumentName: string }
): ComponentResolution | ResolutionFail | null {
if (!this.staticComponentsEnabled) {
return null;
}
let message;
if (impliedBecause) {
message = `argument "${impliedBecause.argumentName}" to component "${impliedBecause.componentName}" is treated as a component, but the value you're passing is dynamic`;
} else {
message = `Unsafe dynamic component`;
}
if (component.type === 'other') {
return {
type: 'error',
message,
detail: `cannot statically analyze this expression`,
loc,
};
}
if (component.type === 'path') {
let ownComponentRules = this.findRules(this.env.filename);
if (ownComponentRules && ownComponentRules.safeInteriorPaths.includes(component.path)) {
return null;
}
return {
type: 'error',
message,
detail: component.path,
loc,
};
}
return this.targetComponent(component.path);
}
private targetHelper(path: string): HelperResolution | null {
if (!this.staticHelpersEnabled) {
return null;
}
// people are not allowed to override the built-in helpers with their own
// globally-named helpers. It throws an error. So it's fine for us to
// prioritize the builtIns here without bothering to resolve a user helper
// of the same name.
const builtIn = this.builtInsForEmberVersion[path];
if (builtIn?.importableHelper) {
let [importedName, specifier] = builtIn.importableHelper;
return {
type: 'helper',
specifier,
importedName,
nameHint: importedName,
};
}
if (builtIn) {
return null;
}
return {
type: 'helper',
specifier: `#embroider_compat/helpers/${path}`,
importedName: 'default',
nameHint: this.nameHint(path),
};
}
private targetHelperOrComponent(
path: string,
loc: Loc,
hasArgs: boolean
): ComponentResolution | HelperResolution | null {
/*
In earlier embroider versions we would do a bunch of module resolution right
here inside the ast transform to try to resolve the ambiguity of this case
and if we didn't find anything, leave the template unchanged. But that leads
to both a lot of extra build-time expense (since we are attempting
resolution for lots of things that may in fact be just some data and not a
component invocation at all, and also since we are pre-resolving modules
that will get resolved a second time by the final stage packager).
Now, we're going to be less forgiving, because it streamlines the build for
everyone who's not still using these *extremely* old patterns.
The problematic case is:
1. In a non-strict template (because this whole resolver-transform.ts is a
no-op on strict handlebars).
2. Have a mustache statement like: `{{something}}`, where `something` is:
a. Not a variable in scope (for example, there's no preceeding line
like `<Parent as |something|>`)
b. Does not start with `@` because that must be an argument from outside this template.
c. Does not contain a dot, like `some.thing` (because that case is classically
never a global component resolution that we would need to handle)
d. Does not start with `this` (this rule is mostly redundant with the previous rule,
but even a standalone `this` is never a component invocation).
e. Does not have any arguments. If there are argument like `{{something a=b}}`,
there is still ambiguity between helper vs component, but there is no longer
the possibility that this was just rendering some data.
f. Does not take a block, like `{{#something}}{{/something}}` (because that is
always a component, no ambiguity.)
We can't tell if this problematic case is really:
1. A helper invocation with no arguments that is being directly rendered.
Out-of-the-box, ember already generates [a lint
error](https://github.com/ember-template-lint/ember-template-lint/blob/master/docs/rule/no-curly-component-invocation.md)
for this, although it tells you to whitelist your helper when IMO it
should tell you to use an unambiguous syntax like `{{ (something) }}`
instead.
2. A component invocation, which you could have written `<Something />`
instead. Angle-bracket invocation has been available and easy-to-adopt
for a very long time.
3. Property-this-fallback for `{{this.something}}`. Property-this-fallback
is eliminated at Ember 4.0, so people have been heavily pushed to get
it out of their addons.
*/
// first, bail out on all the stuff we can obviously ignore
if ((!this.staticHelpersEnabled && !this.staticComponentsEnabled) || this.isIgnoredComponent(path)) {
return null;
}
let builtIn = this.builtInsForEmberVersion[path];
if (builtIn?.importableComponent) {
let [importedName, specifier] = builtIn.importableComponent;
return {
type: 'component',
specifier,
importedName,
yieldsComponents: [],
yieldsArguments: [],
argumentsAreComponents: [],
nameHint: importedName,
};
}
if (builtIn?.importableHelper) {
let [importedName, specifier] = builtIn.importableHelper;
return {
type: 'helper',
specifier,
importedName,
nameHint: importedName,
};
}
if (builtIn) {
return null;
}
let ownComponentRules = this.findRules(this.env.filename);
if (ownComponentRules?.disambiguate[path]) {
switch (ownComponentRules.disambiguate[path]) {
case 'component':
return this.targetComponent(path);
case 'helper':
return this.targetHelper(path);
case 'data':
return null;
}
}
if (!hasArgs && !path.includes('/') && !path.includes('@')) {
// this is the case that could also be property-this-fallback. We're going
// to force people to disambiguate, because letting a potential component
// or helper invocation lurk inside every bit of data you render is not
// ok.
this.reportError({
type: 'error',
message: 'unsupported ambiguous syntax',
detail: `"{{${path}}}" is ambiguous and could mean "{{this.${path}}}" or component "<${capitalize(
camelCase(path)
)} />" or helper "{{ (${path}) }}". Change it to one of those unambigous forms, or use a "disambiguate" packageRule to work around the problem if its in third-party code you cannot easily fix.`,
loc,
});
return null;
}
// Above we already bailed out if both of these were disabled, so we know at
// least one is turned on. If both aren't turned on, we're stuck, because we
// can't even tell if this *is* a component vs a helper.
if (!this.staticHelpersEnabled || !this.staticComponentsEnabled) {
this.reportError({
type: 'error',
message: 'unsupported ambiguity between helper and component',
detail: `this use of "{{${path}}}" could be helper "{{ (${path}) }}" or component "<${capitalize(
camelCase(path)
)} />", and your settings for staticHelpers and staticComponents do not agree. Either switch to one of the unambiguous forms, or make staticHelpers and staticComponents agree, or use a "disambiguate" packageRule to work around the problem if its in third-party code you cannot easily fix.`,
loc,
});
return null;
}
let componentRules = this.rules.components.get(path);
return {
type: 'component',
specifier: `#embroider_compat/ambiguous/${path}`,
importedName: 'default',
yieldsComponents: componentRules ? componentRules.yieldsSafeComponents : [],
yieldsArguments: componentRules ? componentRules.yieldsArguments : [],
argumentsAreComponents: componentRules ? componentRules.argumentsAreComponents : [],
nameHint: this.nameHint(path),
};
}
private targetElementModifier(path: string): ModifierResolution | null {
if (!this.staticModifiersEnabled) {
return null;
}
const builtIn = this.builtInsForEmberVersion[path];
if (builtIn?.importableModifier) {
let [importedName, specifier] = builtIn.importableModifier;
return {
type: 'modifier',
specifier,
importedName,
nameHint: importedName,
};
}
if (builtIn) {
return null;
}
return {
type: 'modifier',
specifier: `#embroider_compat/modifiers/${path}`,
importedName: 'default',
nameHint: this.nameHint(path),
};
}
targetDynamicModifier(modifier: ComponentLocator, loc: Loc): ModifierResolution | ResolutionFail | null {
if (!this.staticModifiersEnabled) {
return null;
}
if (modifier.type === 'literal') {
return this.targetElementModifier(modifier.path);
} else {
return {
type: 'error',
message: 'Unsafe dynamic modifier',
detail: `cannot statically analyze this expression`,
loc,
};
}
}
private targetDynamicHelper(helper: ComponentLocator): HelperResolution | null {
if (!this.staticHelpersEnabled) {
return null;
}
if (helper.type === 'literal') {
return this.targetHelper(helper.path);
}
// we don't have to manage any errors in this case because ember itself
// considers it an error to pass anything but a string literal to the
// `helper` helper.
return null;
}
private nameHint(path: string) {
let parts = path.split('@');
// the extra underscore here guarantees that we will never collide with an
// HTML element.
return parts[parts.length - 1] + '_';
}
private handleDynamicModifier(param: ASTv1.Expression): ModifierResolution | ResolutionFail | null {
if (param.type === 'StringLiteral') {
return this.targetDynamicModifier({ type: 'literal', path: param.value }, param.loc);
}
// we don't have to manage any errors in this case because ember itself
// considers it an error to pass anything but a string literal to the
// modifier helper.
return null;
}
private handleDynamicHelper(param: ASTv1.Expression): HelperResolution | ResolutionFail | null {
// We only need to handle StringLiterals since Ember already throws an error if unsupported values
// are passed to the helper keyword.
// If a helper reference is passed in we don't need to do anything since it's either the result of a previous
// helper keyword invocation, or a helper reference that was imported somewhere.
if (param.type === 'StringLiteral') {
return this.targetDynamicHelper({ type: 'literal', path: param.value });
}
return null;
}
visitor: ASTPlugin['visitor'] = {
Template: {
enter: () => {
if (this.env.locals) {
this.scopeStack.pushMustacheBlock(this.env.locals);
}
},
exit: () => {
if (this.env.locals) {
this.scopeStack.pop();
}
},
},
Block: {
enter: node => {
this.scopeStack.pushMustacheBlock(node.blockParams);
},
exit: () => {
this.scopeStack.pop();
},
},
BlockStatement: (node, path) => {
if (node.path.type !== 'PathExpression') {
return;
}
let rootName = node.path.parts[0];
if (this.scopeStack.inScope(rootName, path)) {
return;
}
if (node.path.this === true) {
return;
}
if (node.path.parts.length > 1) {
// paths with a dot in them (which therefore split into more than
// one "part") are classically understood by ember to be contextual
// components, which means there's nothing to resolve at this
// location.
return;
}
if (node.path.original === 'component' && node.params.length > 0) {
let resolution = this.handleComponentHelper(node.params[0]);
this.emit(path, resolution, (node, newIdentifier) => {
node.params[0] = newIdentifier;
});
return;
}
let resolution = this.targetComponent(node.path.original);
this.emit(path, resolution, (node, newId) => {
node.path = newId;
});
if (resolution?.type === 'component') {
this.scopeStack.enteringComponentBlock(resolution, ({ argumentsAreComponents }) => {
this.handleDynamicComponentArguments(
rootName,
argumentsAreComponents,
extendPath(extendPath(path, 'hash'), 'pairs')
);
});
}
},
SubExpression: (node, path) => {
if (node.path.type !== 'PathExpression') {
return;
}
if (node.path.this === true) {
return;
}
if (this.scopeStack.inScope(node.path.parts[0], path)) {
return;
}
if (node.path.original === 'component' && node.params.length > 0) {
let resolution = this.handleComponentHelper(node.params[0]);
this.emit(path, resolution, (node, newId) => {
node.params[0] = newId;
});
return;
}
if (node.path.original === 'helper' && node.params.length > 0) {
let resolution = this.handleDynamicHelper(node.params[0]);
this.emit(path, resolution, (node, newId) => {
node.params[0] = newId;
});
return;
}
if (node.path.original === 'modifier' && node.params.length > 0) {
let resolution = this.handleDynamicModifier(node.params[0]);
this.emit(path, resolution, (node, newId) => {
node.params[0] = newId;
});
return;
}
if (node.path.tail.length === 0 && node.path.head.type === 'VarHead') {
let resolution = this.targetHelper(node.path.original);
this.emit(path, resolution, (node, newId) => {
node.path = newId;
});
}
},
MustacheStatement: {
enter: (node, path) => {
if (node.path.type !== 'PathExpression') {
return;
}
let rootName = node.path.parts[0];
if (this.scopeStack.inScope(rootName, path)) {
return;
}
if (node.path.this === true) {
return;
}
if (node.path.parts.length > 1) {
// paths with a dot in them (which therefore split into more than
// one "part") are classically understood by ember to be contextual
// components, which means there's nothing to resolve at this
// location.
return;
}
if (node.path.original.startsWith('@')) {
// similarly, global resolution of helpers and components never
// happens with argument paths (it could still be an invocation, but
// it would be a lexically-scoped invocation, not one we need to
// adjust)
return;
}
if (node.path.original === 'component' && node.params.length > 0) {
let resolution = this.handleComponentHelper(node.params[0]);
this.emit(path, resolution, (node, newId) => {
node.params[0] = newId;
});
return;
}
if (node.path.original === 'helper' && node.params.length > 0) {
let resolution = this.handleDynamicHelper(node.params[0]);
this.emit(path, resolution, (node, newIdentifier) => {
node.params[0] = newIdentifier;
});
return;
}
if (path.parent?.node.type === 'AttrNode') {
// this mustache is the value of an attribute. Components aren't
// allowed here, so we're not ambiguous, so resolve a helper.
let resolution = this.targetHelper(node.path.original);
this.emit(path, resolution, (node, newIdentifier) => {
node.path = newIdentifier;
});
return;
}
let hasArgs = node.params.length > 0 || node.hash.pairs.length > 0;
let resolution = this.targetHelperOrComponent(node.path.original, node.path.loc, hasArgs);
this.emit(path, resolution, (node, newIdentifier) => {
node.path = newIdentifier;
});
if (resolution?.type === 'component') {
this.handleDynamicComponentArguments(
node.path.original,
resolution.argumentsAreComponents,
extendPath(extendPath(path, 'hash'), 'pairs')
);
}
},
},
ElementModifierStatement: (node, path) => {
if (node.path.type !== 'PathExpression') {
return;
}
if (this.scopeStack.inScope(node.path.parts[0], path)) {
return;
}
if (node.path.this === true) {
return;
}
if (node.path.data === true) {
return;
}
if (node.path.parts.length > 1) {
// paths with a dot in them (which therefore split into more than
// one "part") are classically understood by ember to be contextual
// components. With the introduction of `Template strict mode` in Ember 3.25
// it is also possible to pass modifiers this way which means there's nothing
// to resolve at this location.
return;
}
let resolution = this.targetElementModifier(node.path.original);
this.emit(path, resolution, (node, newId) => {
node.path = newId;
});
},
ElementNode: {
enter: (node, path) => {
let rootName = node.tag.split('.')[0];
if (!this.scopeStack.inScope(rootName, path)) {
let resolution: ComponentResolution | null = null;
// if it starts with lower case, it can't be a component we need to
// globally resolve
if (node.tag[0] !== node.tag[0].toLowerCase()) {
resolution = this.targetComponent(dasherize(node.tag));
}
this.emit(path, resolution, (node, newId) => {
node.tag = newId.original;
});
if (resolution?.type === 'component') {
this.scopeStack.enteringComponentBlock(resolution, ({ argumentsAreComponents }) => {
this.handleDynamicComponentArguments(node.tag, argumentsAreComponents, extendPath(path, 'attributes'));
});
}
}
this.scopeStack.pushElementBlock(node.blockParams, node);
},
exit: () => {
this.scopeStack.pop();
},
},
};
}
// This is the AST transform that resolves components, helpers and modifiers at build time
export default function makeResolverTransform({ appRoot, emberVersion }: Options) {
let config: CompatResolverOptions = readJSONSync(join(locateEmbroiderWorkingDir(appRoot), 'resolver.json'));
const resolverTransform: ASTPluginBuilder<Env> = env => {
if (env.strictMode) {
return {
name: 'embroider-build-time-resolver-strict-noop',
visitor: {},
};
}
return new TemplateResolver(env, config, builtInKeywords(emberVersion));
};
(resolverTransform as any).parallelBabel = {
requireFile: __filename,
buildUsing: 'makeResolverTransform',
params: { appRoot: appRoot },
};
return resolverTransform;
}
interface ComponentBlockMarker {
type: 'componentBlockMarker';
resolution: ComponentResolution;
argumentsAreComponents: string[];