forked from embroider-build/embroider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolver.ts
893 lines (805 loc) · 26.6 KB
/
resolver.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
import {
ActivePackageRules,
ComponentRules,
ModuleRules,
PackageRules,
PreprocessedComponentRule,
preprocessComponentRule,
} from './dependency-rules';
import {
Package,
PackageCache,
Resolver,
TemplateCompiler,
explicitRelative,
extensionsPattern,
} from '@embroider/core';
import { dirname, join, relative, sep } from 'path';
import { Options as AdjustImportsOptions } from '@embroider/core/src/babel-plugin-adjust-imports';
import { Memoize } from 'typescript-memoize';
import Options from './options';
import { ResolvedDep } from '@embroider/core/src/resolver';
import { dasherize } from './dasherize-component-name';
import { makeResolverTransform } from './resolver-transform';
import { pathExistsSync } from 'fs-extra';
import resolve from 'resolve';
import type { ASTv1 } from '@glimmer/syntax';
export interface ComponentResolution {
type: 'component';
modules: ResolvedDep[];
yieldsComponents: Required<ComponentRules>['yieldsSafeComponents'];
yieldsArguments: Required<ComponentRules>['yieldsArguments'];
argumentsAreComponents: string[];
}
export interface HelperResolution {
type: 'helper';
modules: ResolvedDep[];
}
export interface ModifierResolution {
type: 'modifier';
modules: ResolvedDep[];
}
export type ResolutionResult = ComponentResolution | HelperResolution | ModifierResolution;
export interface ResolutionFail {
type: 'error';
message: string;
detail: string;
loc: Loc;
}
interface ResolverDependencyError extends Error {
isTemplateResolverError?: boolean;
loc?: Loc;
moduleName?: string;
}
export type Resolution = ResolutionResult | ResolutionFail;
export interface Loc {
start: { line: number; column: number };
end: { line: number; column: number };
}
// TODO: this depends on the ember version. And it's probably missing some
// private-but-used values.
const builtInHelpers = [
'-get-dynamic-var',
'-in-element',
'in-element',
'-with-dynamic-vars',
'action',
'array',
'component',
'concat',
'debugger',
'each',
'each-in',
'fn',
'get',
'has-block',
'has-block-params',
'hasBlock',
'hasBlockParams',
'hash',
'helper',
'if',
'input',
'let',
'link-to',
'loc',
'log',
// 'modifier',
'mount',
'mut',
'on',
'outlet',
'partial',
'query-params',
'readonly',
'textarea',
'unbound',
'unless',
'with',
'yield',
];
const builtInComponents = ['input', 'link-to', 'textarea'];
const builtInModifiers = ['action', 'on'];
// 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 ResolverOptions = Pick<
Required<Options>,
'staticHelpers' | 'staticModifiers' | 'staticComponents' | 'allowUnsafeDynamicComponents'
>;
function extractOptions(options: Required<Options> | ResolverOptions): ResolverOptions {
return {
staticHelpers: options.staticHelpers,
staticModifiers: options.staticModifiers,
staticComponents: options.staticComponents,
allowUnsafeDynamicComponents: options.allowUnsafeDynamicComponents,
};
}
interface RehydrationParamsBase {
root: string;
modulePrefix: string;
podModulePrefix?: string;
options: ResolverOptions;
activePackageRules: ActivePackageRules[];
}
interface RehydrationParamsWithFile extends RehydrationParamsBase {
adjustImportsOptionsPath: string;
}
interface RehydrationParamsWithOptions extends RehydrationParamsBase {
adjustImportsOptions: AdjustImportsOptions;
}
type RehydrationParams = RehydrationParamsWithFile | RehydrationParamsWithOptions;
export function rehydrate(params: RehydrationParams) {
return new CompatResolver(params);
}
export default class CompatResolver implements Resolver {
private dependencies: Map<string, Resolution[]> = new Map();
private templateCompiler: TemplateCompiler | undefined;
private auditMode = false;
_parallelBabel: {
requireFile: string;
buildUsing: string;
params: RehydrationParams;
};
constructor(private params: RehydrationParams) {
this.params.options = extractOptions(this.params.options);
this._parallelBabel = {
requireFile: __filename,
buildUsing: 'rehydrate',
params,
};
}
enter(moduleName: string) {
let rules = this.findComponentRules(moduleName);
let deps: Resolution[];
if (rules?.dependsOnComponents) {
deps = rules.dependsOnComponents.map(snippet => this.resolveComponentSnippet(snippet, rules!, moduleName));
} else {
deps = [];
}
this.dependencies.set(moduleName, deps);
}
private add(resolution: Resolution, from: string) {
// this "!" is safe because we always `enter()` a module before hitting this
this.dependencies.get(from)!.push(resolution);
return resolution;
}
private findComponentRules(absPath: string): PreprocessedComponentRule | undefined {
let rules = this.rules.components.get(absPath);
if (rules) {
return rules;
}
// co-located templates aren't visible to the resolver, because they never
// get resolved from a template (they are always handled directly by the
// corresponding JS module, which the resolver *does* see). This means their
// paths won't ever be in `this.rules.components`. But we do want them to
// "inherit" the rules that are attached to their corresonding JS module.
if (absPath.endsWith('.hbs')) {
let stem = absPath.slice(0, -4);
for (let ext of this.adjustImportsOptions.resolvableExtensions) {
if (ext !== '.hbs') {
let rules = this.rules.components.get(stem + ext);
if (rules) {
return rules;
}
}
}
}
return undefined;
}
private isIgnoredComponent(dasherizedName: string) {
return this.rules.ignoredComponents.includes(dasherizedName);
}
@Memoize()
get adjustImportsOptions(): AdjustImportsOptions {
const { params } = this;
return 'adjustImportsOptionsPath' in params
? // eslint-disable-next-line @typescript-eslint/no-require-imports
require(params.adjustImportsOptionsPath)
: params.adjustImportsOptions;
}
@Memoize()
private get rules() {
if (!this.templateCompiler) {
throw new Error(
`Bug: Resolver needs to get linked into a TemplateCompiler before it can understand packageRules`
);
}
// keyed by their first resolved dependency's runtimeName.
let components: Map<string, PreprocessedComponentRule> = new Map();
// keyed by our own dasherized interpretation of the component's name.
let ignoredComponents: string[] = [];
// 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.params.activePackageRules) {
if (rule.components) {
for (let [snippet, componentRules] of Object.entries(rule.components)) {
if (componentRules.safeToIgnore) {
ignoredComponents.push(this.standardDasherize(snippet, rule));
continue;
}
let resolvedDep = this.resolveComponentSnippet(snippet, rule).modules[0];
let processedRules = preprocessComponentRule(componentRules);
// we always register our rules on the component's own first resolved
// module, which must be a module in the app's module namespace.
components.set(resolvedDep.absPath, processedRules);
// if there's a custom layout, we also need to register our rules on
// those templates.
if (componentRules.layout) {
if (componentRules.layout.appPath) {
components.set(join(this.params.root, componentRules.layout.appPath), processedRules);
} else if (componentRules.layout.addonPath) {
for (let root of rule.roots) {
components.set(join(root, componentRules.layout.addonPath), processedRules);
}
} else {
throw new Error(
`layout property in component rule must contain either appPath or addonPath: ${JSON.stringify(
rule,
null,
2
)}`
);
}
}
}
}
if (rule.appTemplates) {
for (let [path, templateRules] of Object.entries(rule.appTemplates)) {
let processedRules = preprocessComponentRule(templateRules);
components.set(join(this.params.root, path), processedRules);
}
}
if (rule.addonTemplates) {
for (let [path, templateRules] of Object.entries(rule.addonTemplates)) {
let processedRules = preprocessComponentRule(templateRules);
for (let root of rule.roots) {
components.set(join(root, path), processedRules);
}
}
}
}
return { components, ignoredComponents };
}
resolveComponentSnippet(
snippet: string,
rule: PackageRules | ModuleRules,
from = 'rule-snippet.hbs'
): ResolutionResult & { type: 'component' } {
if (!this.templateCompiler) {
throw new Error(`bug: tried to use resolveComponentSnippet without a templateCompiler`);
}
let name = this.standardDasherize(snippet, rule);
let found = this.tryComponent(name, from, false);
if (found && found.type === 'component') {
return found;
}
throw new Error(`unable to locate component ${snippet} referred to in rule ${JSON.stringify(rule, null, 2)}`);
}
private standardDasherize(snippet: string, rule: PackageRules | ModuleRules): string {
if (!this.templateCompiler) {
throw new Error(`bug: tried to use resolveComponentSnippet without a templateCompiler`);
}
let ast: ASTv1.Template | ASTv1.Program;
try {
ast = this.templateCompiler.parse('snippet.hbs', snippet) as unknown as ASTv1.Template | ASTv1.Program;
} catch (err) {
throw new Error(`unable to parse component snippet "${snippet}" from rule ${JSON.stringify(rule, null, 2)}`);
}
if ((ast.type === 'Program' || ast.type === 'Template') && ast.body.length > 0) {
let first = ast.body[0];
const isMustachePath = first.type === 'MustacheStatement' && first.path.type === 'PathExpression';
const isComponent =
isMustachePath && ((first as ASTv1.MustacheStatement).path as ASTv1.PathExpression).original === 'component';
const hasStringParam =
isComponent &&
Array.isArray((first as ASTv1.MustacheStatement).params) &&
(first as ASTv1.MustacheStatement).params[0].type === 'StringLiteral';
if (isMustachePath && isComponent && hasStringParam) {
return ((first as ASTv1.MustacheStatement).params[0] as ASTv1.StringLiteral).value;
}
if (isMustachePath) {
return ((first as ASTv1.MustacheStatement).path as ASTv1.PathExpression).original;
}
if (first.type === 'ElementNode') {
return dasherize(first.tag);
}
}
throw new Error(`cannot identify a component in rule snippet: "${snippet}"`);
}
astTransformer(templateCompiler: TemplateCompiler): unknown {
this.templateCompiler = templateCompiler;
if (this.staticComponentsEnabled || this.staticHelpersEnabled || this.staticModifiersEnabled) {
return makeResolverTransform(this);
}
}
// called by our audit tool. Forces staticComponents, staticHelpers and staticModifiers
// to activate so we can audit their behavior, while making their errors silent
// until we can gather them up at the end of the build for the audit results.
enableAuditMode() {
this.auditMode = true;
}
errorsIn(moduleName: string): ResolutionFail[] {
let deps = this.dependencies.get(moduleName);
if (deps) {
return deps.filter(d => d.type === 'error') as ResolutionFail[];
} else {
return [];
}
}
dependenciesOf(moduleName: string): ResolvedDep[] {
let flatDeps: Map<string, ResolvedDep> = new Map();
let deps = this.dependencies.get(moduleName);
if (deps) {
for (let dep of deps) {
if (dep.type === 'error') {
if (!this.auditMode && !this.params.options.allowUnsafeDynamicComponents) {
let e: ResolverDependencyError = new Error(
`${dep.message}: ${dep.detail} in ${humanReadableFile(this.params.root, moduleName)}`
);
e.isTemplateResolverError = true;
e.loc = dep.loc;
e.moduleName = moduleName;
throw e;
}
} else {
for (let entry of dep.modules) {
let { runtimeName } = entry;
flatDeps.set(runtimeName, entry);
}
}
}
}
return [...flatDeps.values()];
}
resolveImport(path: string, from: string): { runtimeName: string; absPath: string } | undefined {
let absPath;
try {
absPath = resolve.sync(path, {
basedir: dirname(from),
extensions: this.adjustImportsOptions.resolvableExtensions,
});
} catch (err) {
return;
}
if (absPath) {
let runtimeName = this.absPathToRuntimeName(absPath);
if (runtimeName) {
return { runtimeName, absPath };
}
}
}
@Memoize()
private get resolvableExtensionsPattern() {
return extensionsPattern(this.adjustImportsOptions.resolvableExtensions);
}
absPathToRuntimePath(absPath: string, owningPackage?: { root: string; name: string }) {
let pkg = owningPackage || PackageCache.shared('embroider-stage3', this.params.root).ownerOfFile(absPath);
if (pkg) {
let packageRuntimeName = pkg.name;
for (let [runtimeName, realName] of Object.entries(this.adjustImportsOptions.renamePackages)) {
if (realName === packageRuntimeName) {
packageRuntimeName = runtimeName;
break;
}
}
return join(packageRuntimeName, relative(pkg.root, absPath)).split(sep).join('/');
} else if (absPath.startsWith(this.params.root)) {
return join(this.params.modulePrefix, relative(this.params.root, absPath)).split(sep).join('/');
} else {
throw new Error(`bug: can't figure out the runtime name for ${absPath}`);
}
}
absPathToRuntimeName(absPath: string, owningPackage?: { root: string; name: string }) {
return this.absPathToRuntimePath(absPath, owningPackage)
.replace(this.resolvableExtensionsPattern, '')
.replace(/\/index$/, '');
}
private get staticComponentsEnabled(): boolean {
return this.params.options.staticComponents || this.auditMode;
}
private get staticHelpersEnabled(): boolean {
return this.params.options.staticHelpers || this.auditMode;
}
private get staticModifiersEnabled(): boolean {
return this.params.options.staticModifiers || this.auditMode;
}
private tryHelper(path: string, from: string): Resolution | null {
let parts = path.split('@');
if (parts.length > 1 && parts[0].length > 0) {
let cache = PackageCache.shared('embroider-stage3', this.params.root);
let packageName = parts[0];
let renamed = this.adjustImportsOptions.renamePackages[packageName];
if (renamed) {
packageName = renamed;
}
return this._tryHelper(parts[1], from, cache.resolve(packageName, cache.ownerOfFile(from)!));
} else {
return this._tryHelper(path, from, this.appPackage);
}
}
private _tryHelper(path: string, from: string, targetPackage: Package | AppPackagePlaceholder): Resolution | null {
for (let extension of this.adjustImportsOptions.resolvableExtensions) {
let absPath = join(targetPackage.root, 'helpers', path) + extension;
if (pathExistsSync(absPath)) {
return {
type: 'helper',
modules: [
{
runtimeName: this.absPathToRuntimeName(absPath, targetPackage),
path: explicitRelative(dirname(from), absPath),
absPath,
},
],
};
}
}
return null;
}
private tryModifier(path: string, from: string): Resolution | null {
let parts = path.split('@');
if (parts.length > 1 && parts[0].length > 0) {
let cache = PackageCache.shared('embroider-stage3', this.params.root);
let packageName = parts[0];
let renamed = this.adjustImportsOptions.renamePackages[packageName];
if (renamed) {
packageName = renamed;
}
return this._tryModifier(parts[1], from, cache.resolve(packageName, cache.ownerOfFile(from)!));
} else {
return this._tryModifier(path, from, this.appPackage);
}
}
private _tryModifier(path: string, from: string, targetPackage: Package | AppPackagePlaceholder): Resolution | null {
for (let extension of this.adjustImportsOptions.resolvableExtensions) {
let absPath = join(targetPackage.root, 'modifiers', path) + extension;
if (pathExistsSync(absPath)) {
return {
type: 'modifier',
modules: [
{
runtimeName: this.absPathToRuntimeName(absPath, targetPackage),
path: explicitRelative(dirname(from), absPath),
absPath,
},
],
};
}
}
return null;
}
@Memoize()
private get appPackage(): AppPackagePlaceholder {
return { root: this.params.root, name: this.params.modulePrefix };
}
private tryComponent(path: string, from: string, withRuleLookup = true): Resolution | null {
let parts = path.split('@');
if (parts.length > 1 && parts[0].length > 0) {
let cache = PackageCache.shared('embroider-stage3', this.params.root);
let packageName = parts[0];
let renamed = this.adjustImportsOptions.renamePackages[packageName];
if (renamed) {
packageName = renamed;
}
return this._tryComponent(parts[1], from, withRuleLookup, cache.resolve(packageName, cache.ownerOfFile(from)!));
} else {
return this._tryComponent(path, from, withRuleLookup, this.appPackage);
}
}
private _tryComponent(
path: string,
from: string,
withRuleLookup: boolean,
targetPackage: Package | AppPackagePlaceholder
): Resolution | null {
// The order here is important! We always put our .hbs paths first here, so
// that if we have an hbs file of our own, that will be the first resolved
// dependency. The first resolved dependency is special because we use that
// as a key into the rules, and we want to be able to find our rules when
// checking from our own template (among other times).
let extensions = ['.hbs', ...this.adjustImportsOptions.resolvableExtensions.filter((e: string) => e !== '.hbs')];
let componentModules = [] as string[];
// first, the various places our template might be
for (let extension of extensions) {
let absPath = join(targetPackage.root, 'templates', 'components', path) + extension;
if (pathExistsSync(absPath)) {
componentModules.push(absPath);
break;
}
absPath = join(targetPackage.root, 'components', path, 'template') + extension;
if (pathExistsSync(absPath)) {
componentModules.push(absPath);
break;
}
if (
typeof this.params.podModulePrefix !== 'undefined' &&
this.params.podModulePrefix !== '' &&
targetPackage === this.appPackage
) {
let podPrefix = this.params.podModulePrefix.replace(this.params.modulePrefix, '');
absPath = join(targetPackage.root, podPrefix, 'components', path, 'template') + extension;
if (pathExistsSync(absPath)) {
componentModules.push(absPath);
break;
}
}
}
// then the various places our javascript might be
for (let extension of extensions) {
if (extension === '.hbs') {
continue;
}
let absPath = join(targetPackage.root, 'components', path, 'index') + extension;
if (pathExistsSync(absPath)) {
componentModules.push(absPath);
break;
}
absPath = join(targetPackage.root, 'components', path) + extension;
if (pathExistsSync(absPath)) {
componentModules.push(absPath);
break;
}
absPath = join(targetPackage.root, 'components', path, 'component') + extension;
if (pathExistsSync(absPath)) {
componentModules.push(absPath);
break;
}
if (
typeof this.params.podModulePrefix !== 'undefined' &&
this.params.podModulePrefix !== '' &&
targetPackage === this.appPackage
) {
let podPrefix = this.params.podModulePrefix.replace(this.params.modulePrefix, '');
absPath = join(targetPackage.root, podPrefix, 'components', path, 'component') + extension;
if (pathExistsSync(absPath)) {
componentModules.push(absPath);
break;
}
}
}
if (componentModules.length > 0) {
let componentRules;
if (withRuleLookup) {
componentRules = this.findComponentRules(componentModules[0]);
}
return {
type: 'component',
modules: componentModules.map(absPath => ({
path: explicitRelative(dirname(from), absPath),
absPath,
runtimeName: this.absPathToRuntimeName(absPath, targetPackage),
})),
yieldsComponents: componentRules ? componentRules.yieldsSafeComponents : [],
yieldsArguments: componentRules ? componentRules.yieldsArguments : [],
argumentsAreComponents: componentRules ? componentRules.argumentsAreComponents : [],
};
}
return null;
}
resolveSubExpression(path: string, from: string, loc: Loc): Resolution | null {
if (!this.staticHelpersEnabled) {
return null;
}
let found = this.tryHelper(path, from);
if (found) {
return this.add(found, from);
}
if (builtInHelpers.includes(path)) {
return null;
}
return this.add(
{
type: 'error',
message: `Missing helper`,
detail: path,
loc,
},
from
);
}
resolveMustache(path: string, hasArgs: boolean, from: string, loc: Loc): Resolution | null {
if (this.staticHelpersEnabled) {
let found = this.tryHelper(path, from);
if (found) {
return this.add(found, from);
}
}
if (this.staticComponentsEnabled) {
let found = this.tryComponent(path, from);
if (found) {
return this.add(found, from);
}
}
if (
hasArgs &&
this.staticComponentsEnabled &&
this.staticHelpersEnabled &&
!builtInHelpers.includes(path) &&
!this.isIgnoredComponent(path)
) {
return this.add(
{
type: 'error',
message: `Missing component or helper`,
detail: path,
loc,
},
from
);
} else {
return null;
}
}
resolveElementModifierStatement(path: string, from: string, loc: Loc): Resolution | null {
if (!this.staticModifiersEnabled) {
return null;
}
let found = this.tryModifier(path, from);
if (found) {
return this.add(found, from);
}
if (builtInModifiers.includes(path)) {
return null;
}
return this.add(
{
type: 'error',
message: `Missing modifier`,
detail: path,
loc,
},
from
);
}
resolveElement(tagName: string, from: string, loc: Loc): Resolution | null {
if (!this.staticComponentsEnabled) {
return null;
}
if (tagName[0] === tagName[0].toLowerCase()) {
// starts with lower case, so this can't be a component we need to
// globally resolve
return null;
}
let dName = dasherize(tagName);
if (builtInComponents.includes(dName)) {
return null;
}
let found = this.tryComponent(dName, from);
if (found) {
return this.add(found, from);
}
if (this.isIgnoredComponent(dName)) {
return null;
}
return this.add(
{
type: 'error',
message: `Missing component`,
detail: tagName,
loc,
},
from
);
}
resolveComponentHelper(
component: ComponentLocator,
from: string,
loc: Loc,
impliedBecause?: { componentName: string; argumentName: string }
): Resolution | 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 this.add(
{
type: 'error',
message,
detail: `cannot statically analyze this expression`,
loc,
},
from
);
}
if (component.type === 'path') {
let ownComponentRules = this.findComponentRules(from);
if (ownComponentRules && ownComponentRules.safeInteriorPaths.includes(component.path)) {
return null;
}
return this.add(
{
type: 'error',
message,
detail: component.path,
loc,
},
from
);
}
if (builtInComponents.includes(component.path)) {
return null;
}
let found = this.tryComponent(component.path, from);
if (found) {
return this.add(found, from);
}
return this.add(
{
type: 'error',
message: `Missing component`,
detail: component.path,
loc,
},
from
);
}
resolveDynamicHelper(helper: ComponentLocator, from: string, loc: Loc): Resolution | null {
if (!this.staticHelpersEnabled) {
return null;
}
if (helper.type === 'literal') {
let helperName = helper.path;
if (builtInHelpers.includes(helperName)) {
return null;
}
let found = this.tryHelper(helperName, from);
if (found) {
return this.add(found, from);
}
return this.add(
{
type: 'error',
message: `Missing helper`,
detail: helperName,
loc,
},
from
);
} else {
return this.add(
{
type: 'error',
message: 'Unsafe dynamic helper',
detail: `cannot statically analyze this expression`,
loc,
},
from
);
}
}
}
function humanReadableFile(root: string, file: string) {
if (!root.endsWith('/')) {
root += '/';
}
if (file.startsWith(root)) {
return file.slice(root.length);
}
return file;
}
// we don't have a real Package for the app itself because the resolver has work
// to do before we have even written out the app's own package.json and
// therefore made it into a fully functional Package.
interface AppPackagePlaceholder {
root: string;
name: string;
}
export type ComponentLocator =
| {
type: 'literal';
path: string;
}
| {
type: 'path';
path: string;
}
| {
type: 'other';
};