-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathtransform.rs
More file actions
5142 lines (4554 loc) · 194 KB
/
transform.rs
File metadata and controls
5142 lines (4554 loc) · 194 KB
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
//! Angular file transformation.
//!
//! This module provides the main entry point for transforming TypeScript files
//! containing Angular components into compiled JavaScript.
use std::collections::HashMap;
use oxc_allocator::{Allocator, Vec as OxcVec};
use oxc_ast::ast::{
Declaration, ExportDefaultDeclarationKind, ImportDeclarationSpecifier, ImportOrExportKind,
Statement,
};
use oxc_diagnostics::OxcDiagnostic;
use oxc_parser::Parser;
use oxc_span::{Atom, SourceType, Span};
use rustc_hash::FxHashMap;
#[cfg(feature = "cross_file_elision")]
use super::cross_file_elision::CrossFileAnalyzer;
use super::decorator::{
collect_constructor_decorator_spans, collect_member_decorator_spans,
extract_component_metadata, find_component_decorator, find_component_decorator_span,
};
use super::definition::{const_value_to_expression, generate_component_definitions};
use super::import_elision::{ImportElisionAnalyzer, filter_imports};
use super::metadata::{AngularVersion, ComponentMetadata, HostMetadata};
use super::namespace_registry::NamespaceRegistry;
use crate::ast::expression::{BindingType, ParsedEventType};
use crate::ast::r3::{R3BoundAttribute, R3BoundEvent, SecurityContext};
use crate::class_metadata::{
R3ClassMetadata, build_ctor_params_metadata, build_decorator_metadata_array,
build_prop_decorators_metadata, compile_class_metadata,
};
use crate::directive::{
R3QueryMetadata, create_content_queries_function, create_view_queries_function,
extract_content_queries, extract_directive_metadata, extract_view_queries,
find_directive_decorator_span, generate_directive_definitions,
};
use crate::injectable::{
extract_injectable_metadata, find_injectable_decorator_span,
generate_injectable_definition_from_decorator,
};
use crate::ng_module::{
extract_ng_module_metadata, find_ng_module_decorator_span, generate_full_ng_module_definition,
};
use crate::output::ast::{
DeclareFunctionStmt, FunctionExpr, OutputExpression, OutputStatement, ReadPropExpr,
ReadVarExpr, StmtModifier,
};
use crate::output::emitter::JsEmitter;
use crate::parser::ParseTemplateOptions;
use crate::parser::expression::BindingParser;
use crate::parser::html::{HtmlParser, remove_whitespaces};
use crate::pipe::{
extract_pipe_metadata, find_pipe_decorator_span, generate_full_pipe_definition_from_decorator,
};
use crate::pipeline::compilation::{DeferBlockDepsEmitMode, TemplateCompilationMode};
use crate::pipeline::emit::{
HostBindingCompilationResult, compile_host_bindings, compile_template,
};
use crate::pipeline::ingest::{
HostBindingInput, IngestOptions, ingest_component, ingest_component_with_options,
ingest_host_binding,
};
use crate::transform::HtmlToR3Transform;
use crate::transform::html_to_r3::TransformOptions as R3TransformOptions;
/// Options for Angular file transformation.
#[derive(Debug, Clone)]
pub struct TransformOptions {
/// Generate source maps.
pub sourcemap: bool,
/// Enable JIT (Just-In-Time) compilation mode.
/// When true, generates code compatible with JIT compilation.
pub jit: bool,
/// Enable HMR (Hot Module Replacement) support.
/// When true, generates HMR initialization and update code.
pub hmr: bool,
/// Enable advanced optimizations.
/// When true, applies additional optimizations like constant folding.
pub advanced_optimizations: bool,
/// i18n message ID strategy.
///
/// When true (default), uses external message IDs for Closure Compiler
/// variable naming (MSG_EXTERNAL_abc123$$SUFFIX).
/// When false, uses file-based naming (MSG_SUFFIX_0).
pub i18n_use_external_ids: bool,
/// Angular core version for version-conditional behavior.
///
/// When set, used to determine defaults like:
/// - `standalone`: defaults to `false` for v18 and earlier, `true` for v19+
///
/// When `None`, assumes latest Angular version (v19+ behavior).
pub angular_version: Option<AngularVersion>,
// Component metadata overrides for template-only compilation.
// These allow the build tool to pass component metadata when compiling
// templates in isolation (e.g., for testing or compare tool).
/// Override the CSS selector for the component.
pub selector: Option<String>,
/// Override the standalone flag for the component.
pub standalone: Option<bool>,
/// Override the view encapsulation mode.
pub encapsulation: Option<super::metadata::ViewEncapsulation>,
/// Override the change detection strategy.
pub change_detection: Option<super::metadata::ChangeDetectionStrategy>,
/// Override the preserve whitespaces setting.
pub preserve_whitespaces: Option<bool>,
/// Host bindings metadata for the component.
/// Contains property bindings, attribute bindings, and event listeners.
pub host: Option<HostMetadataInput>,
/// Enable cross-file import elision analysis.
///
/// When true, resolves imports to source files to check if exports are type-only.
/// This improves import elision accuracy by detecting interfaces and type aliases
/// in external files.
///
/// **Note**: This is intended for compare tests only. In production, bundlers
/// like rolldown handle import elision as part of their tree-shaking process.
#[cfg(feature = "cross_file_elision")]
pub cross_file_elision: bool,
/// Base directory for module resolution.
///
/// Used when `cross_file_elision` is enabled to resolve relative imports.
/// Defaults to the directory containing the source file if not specified.
#[cfg(feature = "cross_file_elision")]
pub base_dir: Option<std::path::PathBuf>,
/// Path to tsconfig.json for path aliases.
///
/// Used when `cross_file_elision` is enabled to resolve path aliases
/// defined in tsconfig.json (e.g., `@app/*` -> `src/app/*`).
#[cfg(feature = "cross_file_elision")]
pub tsconfig_path: Option<std::path::PathBuf>,
/// Resolved import paths for host directives and other imports.
///
/// Maps local identifier name (e.g., "AriaDisableDirective") to the resolved
/// module path (e.g., "../a11y/aria-disable.directive").
///
/// This is used to override barrel export paths with actual file paths.
/// When an identifier is found in this map, the resolved path is used
/// instead of the original import declaration's source.
///
/// Example:
/// ```text
/// // Original import uses barrel export:
/// import { AriaDisableDirective } from '../a11y';
///
/// // resolved_imports maps to actual file:
/// { "AriaDisableDirective": "../a11y/aria-disable.directive" }
/// ```
pub resolved_imports: Option<HashMap<String, String>>,
/// Emit setClassMetadata() calls for TestBed support.
///
/// When true, generates `ɵɵsetClassMetadata()` calls wrapped in a dev-mode guard.
/// This preserves original decorator information for TestBed's recompilation APIs.
///
/// Default: false (metadata is dev-only and usually stripped in production)
pub emit_class_metadata: bool,
}
/// Input for host metadata when passed via TransformOptions.
/// Uses owned String types for easier NAPI interop.
#[derive(Debug, Clone, Default)]
pub struct HostMetadataInput {
/// Host property bindings: `{ "[class.active]": "isActive" }`
pub properties: Vec<(String, String)>,
/// Host attribute bindings: `{ "role": "button" }`
pub attributes: Vec<(String, String)>,
/// Host event listeners: `{ "(click)": "onClick()" }`
pub listeners: Vec<(String, String)>,
/// Special attribute for static class binding.
pub class_attr: Option<String>,
/// Special attribute for static style binding.
pub style_attr: Option<String>,
}
impl Default for TransformOptions {
fn default() -> Self {
Self {
sourcemap: false,
jit: false,
hmr: false,
advanced_optimizations: false,
i18n_use_external_ids: true, // Angular's JIT default
angular_version: None, // None means assume latest (v19+ behavior)
// Metadata overrides default to None (use extracted/default values)
selector: None,
standalone: None,
encapsulation: None,
change_detection: None,
preserve_whitespaces: None,
host: None,
// Cross-file elision options (feature-gated)
#[cfg(feature = "cross_file_elision")]
cross_file_elision: false,
#[cfg(feature = "cross_file_elision")]
base_dir: None,
#[cfg(feature = "cross_file_elision")]
tsconfig_path: None,
// Resolved imports for host directives
resolved_imports: None,
// Class metadata for TestBed support (disabled by default)
emit_class_metadata: false,
}
}
}
impl TransformOptions {
/// Compute the implicit standalone value based on the Angular version.
///
/// - Returns `true` for Angular v19+ or when version is unknown (None)
/// - Returns `false` for Angular v18 and earlier
pub fn implicit_standalone(&self) -> bool {
self.angular_version.map(|v| v.supports_implicit_standalone()).unwrap_or(true) // Default to true when version is unknown
}
}
/// Pre-resolved external resources for component transformation.
///
/// The build tool (e.g., Vite) resolves `templateUrl` and `styleUrls` before
/// calling the Rust compiler, since file I/O and preprocessing (SCSS, etc.)
/// needs to happen in JavaScript.
#[derive(Debug, Default)]
pub struct ResolvedResources {
/// Map from templateUrl path to resolved template content.
pub templates: HashMap<String, String>,
/// Map from styleUrl path to resolved (preprocessed) style content.
pub styles: HashMap<String, Vec<String>>,
}
/// Result of transforming an Angular file.
#[derive(Debug, Default)]
pub struct TransformResult {
/// The transformed code.
pub code: String,
/// Source map (if sourcemap option was enabled).
pub map: Option<String>,
/// Files this file depends on (for watch mode).
/// Includes template URLs and style URLs.
pub dependencies: Vec<String>,
/// Template updates for HMR.
/// Maps component ID (path@ClassName) to compiled template function.
pub template_updates: HashMap<String, String>,
/// Style updates for HMR.
/// Maps component ID to list of styles.
pub style_updates: HashMap<String, Vec<String>>,
/// Compilation diagnostics (errors and warnings).
pub diagnostics: Vec<OxcDiagnostic>,
/// Number of components found in the file.
pub component_count: usize,
}
impl TransformResult {
/// Create a new empty transform result.
pub fn new() -> Self {
Self::default()
}
/// Check if there are any errors.
pub fn has_errors(&self) -> bool {
use miette::Diagnostic;
use oxc_diagnostics::Severity;
self.diagnostics
.iter()
.any(|d| d.severity() == Some(Severity::Error) || d.severity().is_none())
}
/// Check if there are any warnings.
pub fn has_warnings(&self) -> bool {
use miette::Diagnostic;
use oxc_diagnostics::Severity;
self.diagnostics.iter().any(|d| d.severity() == Some(Severity::Warning))
}
}
/// Result of compiling a template to JavaScript.
#[derive(Debug, Default)]
pub struct TemplateCompileOutput {
/// The compiled template function as JavaScript code.
pub code: String,
/// Source map (if sourcemap option was enabled).
pub map: Option<oxc_sourcemap::SourceMap>,
}
impl TemplateCompileOutput {
/// Create a new template compile output with just code.
pub fn new(code: String) -> Self {
Self { code, map: None }
}
/// Create a new template compile output with code and source map.
pub fn with_source_map(code: String, map: Option<oxc_sourcemap::SourceMap>) -> Self {
Self { code, map }
}
}
/// Output from compiling a template for HMR.
/// Includes the template function, constant declarations, extracted styles, and consts array.
#[derive(Debug)]
pub struct HmrTemplateCompileOutput {
/// The compiled template function as JavaScript code.
pub template_js: String,
/// Constant declarations (child view functions, pooled constants) as JavaScript code.
/// These need to be included in the HMR update module before the component definition.
pub declarations_js: String,
/// Styles extracted from `<style>` tags in the template.
/// These must be included in the HMR update module to avoid constant pool mismatches.
pub styles: std::vec::Vec<String>,
/// The consts array as JavaScript code.
/// This must be included in the HMR update module to match the template function's
/// constant references. Without this, the template may reference indices that don't
/// exist in the old component definition's consts array.
pub consts_js: Option<String>,
}
/// Compiled component information.
#[derive(Debug)]
pub struct CompiledComponent<'a> {
/// Component metadata.
pub metadata: ComponentMetadata<'a>,
/// Compiled template function.
pub template_fn: Option<FunctionExpr<'a>>,
/// Compiled template as JavaScript string.
pub template_js: Option<String>,
}
/// Map from imported identifier name to its source module path.
///
/// This is used to track where constructor dependency tokens come from,
/// enabling proper namespace aliasing in the compiled output.
///
/// Example:
/// ```typescript
/// import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
/// import { ServiceA, ServiceB } from "./services";
/// ```
/// Results in:
/// ```text
/// {
/// "AuthService" -> "@bitwarden/common/auth/abstractions/auth.service",
/// "ServiceA" -> "./services",
/// "ServiceB" -> "./services"
/// }
/// ```
/// Information about an imported symbol.
#[derive(Debug, Clone)]
pub struct ImportInfo<'a> {
/// The source module path (e.g., "@angular/core", "./services").
pub source_module: Atom<'a>,
/// Whether this is a named import that can be reused with bare name.
/// True for: `import { AuthService } from "module"`
/// False for: `import * as core from "module"` (namespace imports)
pub is_named_import: bool,
/// Whether this is a type-only import (`import type { X }` or `import { type X }`).
/// Type-only imports are erased at runtime and should not generate namespace
/// imports for `setClassMetadata()` type references.
pub is_type_only: bool,
}
/// Map from local identifier name to its import information.
///
/// Used to look up where a constructor dependency token was imported from
/// and whether it can be reused with a bare name or requires namespace prefix.
pub type ImportMap<'a> = FxHashMap<Atom<'a>, ImportInfo<'a>>;
/// Build an import map from the program's import declarations.
///
/// Extracts all imports and maps the local identifier name to the
/// source module path and import type. This enables:
/// - Looking up where a constructor dependency token was imported from
/// - Determining if the import can be reused with bare name (named import)
/// or requires namespace prefix (namespace import)
///
/// # Arguments
///
/// * `allocator` - Memory allocator for creating new Atoms
/// * `program_body` - The program's statement list
/// * `resolved_imports` - Optional map of identifier names to resolved module paths.
/// When provided, these paths override the source module from the import declaration.
/// This is used to resolve barrel exports to actual file paths.
///
/// Handles:
/// - Named imports: `import { AuthService } from "@angular/core"`
/// -> `is_named_import: true` (can use bare `AuthService`)
/// - Named imports with alias: `import { AuthService as Auth } from "@angular/core"`
/// -> `is_named_import: true` (can use bare `Auth`)
/// - Default imports: `import DefaultService from "@bitwarden/common"`
/// -> `is_named_import: true` (can use bare `DefaultService`)
/// - Namespace imports: `import * as core from "@angular/core"`
/// -> `is_named_import: false` (need namespace prefix)
pub fn build_import_map<'a>(
allocator: &'a Allocator,
program_body: &[Statement<'a>],
resolved_imports: Option<&HashMap<String, String>>,
) -> ImportMap<'a> {
let mut import_map = ImportMap::default();
for stmt in program_body {
let Statement::ImportDeclaration(import_decl) = stmt else {
continue;
};
let default_source_module = import_decl.source.value.clone();
// `import type { ... }` makes all specifiers type-only
let decl_is_type_only = import_decl.import_kind == ImportOrExportKind::Type;
// Process all specifiers
let Some(specifiers) = &import_decl.specifiers else {
// Side-effect import: `import 'foo'` - no identifiers to map
continue;
};
for specifier in specifiers {
match specifier {
ImportDeclarationSpecifier::ImportSpecifier(spec) => {
// Named import: `import { AuthService } from "module"`
// or aliased: `import { AuthService as Auth } from "module"`
// We use the local name as the key
// Named imports CAN be reused with bare name
let local_name: Atom<'a> = spec.local.name.clone().into();
// Type-only if the declaration is `import type { ... }` or the specifier
// is `import { type X }` (inline type specifier)
let is_type_only =
decl_is_type_only || spec.import_kind == ImportOrExportKind::Type;
// Check if we have a resolved path for this identifier
let source_module = resolved_imports
.and_then(|m| m.get(local_name.as_str()))
.map(|resolved| Atom::from(allocator.alloc_str(resolved)))
.unwrap_or_else(|| default_source_module.clone());
import_map.insert(
local_name,
ImportInfo { source_module, is_named_import: true, is_type_only },
);
}
ImportDeclarationSpecifier::ImportDefaultSpecifier(spec) => {
// Default import: `import DefaultService from "module"`
// Default imports CAN be reused with bare name
let local_name: Atom<'a> = spec.local.name.clone().into();
// Check if we have a resolved path for this identifier
let source_module = resolved_imports
.and_then(|m| m.get(local_name.as_str()))
.map(|resolved| Atom::from(allocator.alloc_str(resolved)))
.unwrap_or_else(|| default_source_module.clone());
import_map.insert(
local_name,
ImportInfo {
source_module,
is_named_import: true,
is_type_only: decl_is_type_only,
},
);
}
ImportDeclarationSpecifier::ImportNamespaceSpecifier(spec) => {
// Namespace import: `import * as core from "module"`
// Namespace imports CANNOT be reused with bare name for individual symbols
let local_name: Atom<'a> = spec.local.name.clone().into();
// Check if we have a resolved path for this identifier
let source_module = resolved_imports
.and_then(|m| m.get(local_name.as_str()))
.map(|resolved| Atom::from(allocator.alloc_str(resolved)))
.unwrap_or_else(|| default_source_module.clone());
import_map.insert(
local_name,
ImportInfo {
source_module,
is_named_import: false,
is_type_only: decl_is_type_only,
},
);
}
}
}
}
import_map
}
/// Find the byte position (in the source) just after the last import statement.
///
/// Resolve namespace imports for factory dependency tokens.
///
/// The import elision phase removes type-only imports (e.g., `import { Store } from '@ngrx/store'`)
/// because constructor parameter types are considered type-only. However, the factory function
/// needs to reference these types at runtime (e.g., `i0.ɵɵinject(Store)`).
///
/// This function replaces bare `ReadVar` tokens with namespace-prefixed `ReadProp` references
/// (e.g., `Store` → `i1.Store`) for any token that has a corresponding import in the import map.
/// This ensures the factory works correctly even after import elision.
fn resolve_factory_dep_namespaces<'a>(
allocator: &'a Allocator,
deps: &mut oxc_allocator::Vec<'a, crate::factory::R3DependencyMetadata<'a>>,
import_map: &ImportMap<'a>,
namespace_registry: &mut NamespaceRegistry<'a>,
) {
for dep in deps.iter_mut() {
let Some(ref token) = dep.token else { continue };
// Only process bare variable references (ReadVar)
let OutputExpression::ReadVar(var) = token else { continue };
let name = &var.name;
// Look up this identifier in the import map
let Some(import_info) = import_map.get(name) else { continue };
// Replace with namespace-prefixed reference: i1.Store instead of Store
let namespace = namespace_registry.get_or_assign(&import_info.source_module);
dep.token = Some(OutputExpression::ReadProp(oxc_allocator::Box::new_in(
ReadPropExpr {
receiver: oxc_allocator::Box::new_in(
OutputExpression::ReadVar(oxc_allocator::Box::new_in(
ReadVarExpr { name: namespace, source_span: None },
allocator,
)),
allocator,
),
name: name.clone(),
optional: false,
source_span: None,
},
allocator,
)));
}
}
/// Resolves namespace imports for host directive references in `R3HostDirectiveMetadata`.
///
/// Replaces bare `ReadVar("X")` references with namespace-prefixed `ReadProp(ReadVar("i1"), "X")`
/// for any host directive that has a corresponding import in the import map.
/// This ensures the compiled output works correctly even after import elision.
fn resolve_host_directive_namespaces<'a>(
allocator: &'a Allocator,
host_directives: &mut oxc_allocator::Vec<'a, crate::R3HostDirectiveMetadata<'a>>,
import_map: &ImportMap<'a>,
namespace_registry: &mut NamespaceRegistry<'a>,
) {
for hd in host_directives.iter_mut() {
// Only process bare variable references (ReadVar)
let OutputExpression::ReadVar(ref var) = hd.directive else { continue };
let name = &var.name;
// Look up this identifier in the import map
let Some(import_info) = import_map.get(name) else { continue };
// Replace with namespace-prefixed reference: i1.BrnTooltipTrigger instead of BrnTooltipTrigger
let namespace = namespace_registry.get_or_assign(&import_info.source_module);
hd.directive = OutputExpression::ReadProp(oxc_allocator::Box::new_in(
ReadPropExpr {
receiver: oxc_allocator::Box::new_in(
OutputExpression::ReadVar(oxc_allocator::Box::new_in(
ReadVarExpr { name: namespace, source_span: None },
allocator,
)),
allocator,
),
name: name.clone(),
optional: false,
source_span: None,
},
allocator,
));
}
}
/// This is used to determine where to insert namespace imports so they appear
/// AFTER existing imports but BEFORE other code (like class declarations).
///
/// Returns `Some(position)` if imports were found, or `None` if no imports exist.
fn find_last_import_end(program_body: &[Statement<'_>]) -> Option<usize> {
let mut last_import_end: Option<u32> = None;
for stmt in program_body {
// Check for import declarations and import equals declarations
// These are the import statement types that Angular's TypeScript transform considers
// See: packages/compiler-cli/src/ngtsc/translator/src/import_manager/import_typescript_transform.ts
let span_end = match stmt {
Statement::ImportDeclaration(import_decl) => Some(import_decl.span.end),
// Note: TypeScript import equals (import x = require()) are not common in Angular
// but we handle them for completeness
_ => None,
};
if let Some(end) = span_end {
last_import_end = Some(last_import_end.map_or(end, |prev| prev.max(end)));
}
}
last_import_end.map(|pos| pos as usize)
}
/// Transform an Angular TypeScript file.
///
/// This function:
/// 1. Parses the TypeScript file using oxc_parser
/// 2. Finds all @Component decorated classes
/// 3. Extracts and compiles templates
/// 4. Generates HMR code if enabled
/// 5. Returns the transformed code
///
/// # Arguments
///
/// * `allocator` - Memory allocator for AST nodes
/// * `path` - File path (used for error messages and HMR IDs)
/// * `source` - Source code content
/// * `options` - Transformation options
/// * `resolved_resources` - Pre-resolved external templates and styles
///
/// # Returns
///
/// A `TransformResult` containing the transformed code and metadata.
pub fn transform_angular_file(
allocator: &Allocator,
path: &str,
source: &str,
options: &TransformOptions,
resolved_resources: Option<&ResolvedResources>,
) -> TransformResult {
let mut result = TransformResult::new();
// 1. Parse the TypeScript file
let source_type = SourceType::from_path(path).unwrap_or_default();
let parser_ret = Parser::new(allocator, source, source_type).parse();
// Collect parse errors
if !parser_ret.errors.is_empty() {
for error in parser_ret.errors {
result.diagnostics.push(OxcDiagnostic::error(error.to_string()));
}
// Still continue to try to generate output for partial results
}
// Run import elision analysis on the original program.
// This identifies type-only imports that can be removed.
// Must run BEFORE transformation to capture correct type vs value references.
let import_elision = ImportElisionAnalyzer::analyze(&parser_ret.program);
// Collect class definitions by class name.
// Each entry is (class_name, static_definitions_to_insert, external_declarations)
// The external_declarations are things like _c0 constants and child view functions that
// go outside the class.
// We track by name because positions shift after import filtering.
// (property_assignments, decls_before_class, decls_after_class)
let mut class_definitions: HashMap<String, (String, String, String)> = HashMap::new();
let mut decorator_spans_to_remove: Vec<Span> = Vec::new();
// File-level namespace registry to collect all module imports
let mut file_namespace_registry = NamespaceRegistry::new(allocator);
// Shared constant pool index across all components in this file.
// This ensures constant names (_c0, _c1, etc.) don't conflict when
// multiple components are compiled in the same file.
// TypeScript Angular uses ONE file-level constant pool; we simulate this
// by tracking the next index and passing it to each component.
let mut shared_pool_index: u32 = 0;
// When cross_file_elision is enabled, collect type-only information for each import
// by checking if the exported symbol is an interface or type alias. This is separate
// from barrel resolution to avoid changing namespace import paths.
#[cfg(feature = "cross_file_elision")]
let cross_file_type_only: FxHashMap<String, bool> = if options.cross_file_elision {
let file_path = std::path::Path::new(path);
let base_dir = options.base_dir.as_deref().or_else(|| file_path.parent());
if let Some(base) = base_dir {
let mut analyzer = CrossFileAnalyzer::new(base, options.tsconfig_path.as_deref());
let mut type_only: FxHashMap<String, bool> = FxHashMap::default();
for stmt in &parser_ret.program.body {
let Statement::ImportDeclaration(import_decl) = stmt else {
continue;
};
let source = import_decl.source.value.as_str();
let Some(specifiers) = &import_decl.specifiers else {
continue;
};
for specifier in specifiers {
if let ImportDeclarationSpecifier::ImportSpecifier(spec) = specifier {
let local_name = spec.local.name.as_str();
let imported_name = spec.imported.name().as_str();
// Check if this import is type-only using the original import path.
// Resolves the file and checks if the exported symbol is an interface
// or type alias. Unresolvable imports return false (conservative).
if analyzer.is_type_only_import(source, imported_name, file_path) {
type_only.insert(local_name.to_string(), true);
}
}
}
}
type_only
} else {
FxHashMap::default()
}
} else {
FxHashMap::default()
};
// Build import map from import declarations using ORIGINAL import paths.
// Only externally-provided resolved_imports (e.g., for host directives) override paths.
// Barrel-resolved paths are NOT used here to avoid changing namespace import paths
// from what Angular's compiler would produce.
#[cfg(not(feature = "cross_file_elision"))]
let import_map =
build_import_map(allocator, &parser_ret.program.body, options.resolved_imports.as_ref());
#[cfg(feature = "cross_file_elision")]
let mut import_map =
build_import_map(allocator, &parser_ret.program.body, options.resolved_imports.as_ref());
// Apply cross-file type-only information to the import_map.
// This marks imports that resolve to interfaces or type aliases as type-only,
// even when they don't use `import type` syntax. This is needed because many
// codebases import interfaces with regular `import { X }` syntax, and without
// a TypeScript type checker we cannot otherwise distinguish interfaces from classes.
#[cfg(feature = "cross_file_elision")]
for (name, is_type_only) in &cross_file_type_only {
if let Some(info) = import_map.get_mut(name.as_str()) {
if *is_type_only {
info.is_type_only = true;
}
}
}
// 2. Walk AST to find @Component decorated classes and extract metadata
for stmt in &parser_ret.program.body {
let class = match stmt {
Statement::ClassDeclaration(class) => Some(class.as_ref()),
Statement::ExportDefaultDeclaration(export) => match &export.declaration {
ExportDefaultDeclarationKind::ClassDeclaration(class) => Some(class.as_ref()),
_ => None,
},
Statement::ExportNamedDeclaration(export) => match &export.declaration {
Some(Declaration::ClassDeclaration(class)) => Some(class.as_ref()),
_ => None,
},
_ => None,
};
if let Some(class) = class {
// Compute implicit_standalone based on Angular version
let implicit_standalone = options.implicit_standalone();
if let Some(mut metadata) =
extract_component_metadata(allocator, class, implicit_standalone, &import_map)
{
// 3. Resolve external styles and merge into metadata
resolve_styles(allocator, &mut metadata, resolved_resources);
// 4. Resolve template from inline or external source
let template_source = resolve_template(&metadata, resolved_resources);
let class_name = metadata.class_name.to_string();
if let Some(template_string) = template_source {
// Allocate template in arena so it has the allocator's lifetime.
// This is needed because namespace_registry outlives the template_source.
let template = allocator.alloc_str(&template_string);
// 4.5 Extract view queries from the class (for @ViewChild/@ViewChildren)
// These need to be passed to compile_component_full so predicates can be pooled
let view_queries = extract_view_queries(allocator, class);
// 4.6 Extract content queries from the class (for @ContentChild/@ContentChildren)
// Signal-based queries (contentChild(), contentChildren()) are also detected here
let content_queries = extract_content_queries(allocator, class);
// 4. Compile the template and generate ɵcmp/ɵfac
// Pass the shared pool index to ensure unique constant names
// Pass the file-level namespace registry to ensure consistent namespace assignments
match compile_component_full(
allocator,
template,
&mut metadata,
path,
options,
view_queries,
content_queries,
shared_pool_index,
&mut file_namespace_registry,
) {
Ok(compilation_result) => {
// Update the shared pool index for the next component
shared_pool_index = compilation_result.next_pool_index;
let component_id = format!("{}@{}", path, class_name);
// Store for HMR if enabled
if options.hmr {
result.template_updates.insert(
component_id.clone(),
compilation_result.template_js.clone(),
);
}
// Track the decorator span to remove
if let Some(span) = find_component_decorator_span(class) {
decorator_spans_to_remove.push(span);
}
// Collect constructor parameter decorators (@Optional, @Inject, etc.)
collect_constructor_decorator_spans(
class,
&mut decorator_spans_to_remove,
);
// Collect member decorators (@Input, @Output, @HostBinding, etc.)
collect_member_decorator_spans(class, &mut decorator_spans_to_remove);
// Store the ɵfac/ɵcmp definitions.
// Order: ɵfac BEFORE ɵcmp (Angular convention).
// External declarations (child view functions, constants) go BEFORE the class.
// Note: The /*@__PURE__*/ annotation is already included in cmp_js by the emitter.
// ES2022 style: static fields INSIDE the class body
let mut property_assignments = format!(
"static ɵfac = {};\nstatic ɵcmp = {};",
compilation_result.fac_js, compilation_result.cmp_js
);
// Check if the class also has an @Injectable decorator.
// @Injectable is SHARED precedence and can coexist with @Component.
if let Some(injectable_metadata) =
extract_injectable_metadata(allocator, class)
{
if let Some(span) = find_injectable_decorator_span(class) {
decorator_spans_to_remove.push(span);
}
if let Some(inj_def) = generate_injectable_definition_from_decorator(
allocator,
&injectable_metadata,
) {
let emitter = JsEmitter::new();
property_assignments.push_str(&format!(
"\nstatic ɵprov = {};",
emitter.emit_expression(&inj_def.prov_definition)
));
}
}
// Split declarations into two groups:
// 1. decls_before_class: child view functions, constants (needed BEFORE class)
// 2. decls_after_class: debug info, metadata, HMR code (references class, needs AFTER)
let decls_before_class = compilation_result.declarations_js.clone();
let mut decls_after_class = String::new();
// Add class debug info (before class metadata, following Angular's order)
if let Some(debug_info_js) = &compilation_result.class_debug_info_js {
if !decls_after_class.is_empty() {
decls_after_class.push('\n');
}
decls_after_class.push_str(debug_info_js);
decls_after_class.push(';');
}
// Add class metadata for TestBed support (after debug info, before HMR)
// Only emit when enabled and not in advanced optimizations mode
if options.emit_class_metadata && !options.advanced_optimizations {
if let Some(decorator) = find_component_decorator(&class.decorators)
{
let emitter = JsEmitter::new();
// Build the type expression: reference to the class
let type_expr = crate::output::ast::OutputExpression::ReadVar(
oxc_allocator::Box::new_in(
ReadVarExpr {
name: Atom::from(class_name.as_str()),
source_span: None,
},
allocator,
),
);
// Build metadata from the class AST
// Pass constructor deps and namespace registry so that
// imported types get namespace-prefixed references
// (e.g., i1.SomeService instead of bare SomeService)
let ctor_deps_slice =
metadata.constructor_deps.as_ref().map(|v| v.as_slice());
let class_metadata = R3ClassMetadata {
r#type: type_expr,
decorators: build_decorator_metadata_array(
allocator,
&[decorator],
),
ctor_parameters: build_ctor_params_metadata(
allocator,
class,
ctor_deps_slice,
&mut file_namespace_registry,
&import_map,
),
prop_decorators: build_prop_decorators_metadata(
allocator, class,
),
};
// Compile to the wrapped IIFE expression
let metadata_expr =
compile_class_metadata(allocator, &class_metadata);
let metadata_js = emitter.emit_expression(&metadata_expr);
if !decls_after_class.is_empty() {
decls_after_class.push('\n');
}
decls_after_class.push_str(&metadata_js);
decls_after_class.push(';');
}
}
// Add HMR initializer last
if let Some(hmr_js) = &compilation_result.hmr_initializer_js {
if !decls_after_class.is_empty() {
decls_after_class.push('\n');
}
decls_after_class.push_str(hmr_js);
decls_after_class.push(';');
}
// Track definitions by class name (position is recalculated later)
class_definitions.insert(
class_name.clone(),
(property_assignments, decls_before_class, decls_after_class),
);
// Track external dependencies
if let Some(template_url) = &metadata.template_url {
result.dependencies.push(template_url.to_string());
}
for style_url in &metadata.style_urls {
result.dependencies.push(style_url.to_string());
}
result.component_count += 1;
}
Err(diags) => {
result.diagnostics.extend(diags);
}
}
} else if let Some(template_url) = &metadata.template_url {
// External template not resolved - add warning
result.diagnostics.push(OxcDiagnostic::warn(format!(
"Template URL '{}' not found in resolved resources",
template_url
)));
}
} else {
// Not a @Component - check if it's a @Directive
// We need to compile @Directive classes properly to generate ɵdir/ɵfac
// definitions. This prevents Angular's JIT runtime from processing
// the directive and creating conflicting property definitions (like
// ɵfac getters) that interfere with the AOT-compiled assignments.
if let Some(mut directive_metadata) =
extract_directive_metadata(allocator, class, implicit_standalone)
{
// Track decorator span for removal
if let Some(span) = find_directive_decorator_span(class) {
decorator_spans_to_remove.push(span);
}
// Collect constructor parameter decorators (@Optional, @Inject, etc.)
collect_constructor_decorator_spans(class, &mut decorator_spans_to_remove);
// Collect member decorators (@Input, @Output, @HostBinding, etc.)
collect_member_decorator_spans(class, &mut decorator_spans_to_remove);
// Resolve namespace imports for directive constructor deps.
// Directives can inject services from other modules (e.g., Store from @ngrx/store),
// so factory deps must use namespace-prefixed references (e.g., i1.Store).
if let Some(ref mut deps) = directive_metadata.deps {
resolve_factory_dep_namespaces(