Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions crates/oxc_angular_compiler/src/class_metadata/builders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ use crate::output::ast::{
ArrowFunctionBody, ArrowFunctionExpr, LiteralArrayExpr, LiteralExpr, LiteralMapEntry,
LiteralMapExpr, LiteralValue, OutputExpression, ReadPropExpr, ReadVarExpr,
};
use crate::output::oxc_converter::convert_oxc_expression;
use crate::output::oxc_converter::{
convert_oxc_expression, convert_plain_properties, is_plain_property,
};

/// Build the decorators metadata array expression.
///
Expand Down Expand Up @@ -101,7 +103,20 @@ pub fn build_decorator_metadata_array<'a>(
let mut args = AllocVec::new_in(&allocator);
for (arg_idx, arg) in call.arguments.iter().enumerate() {
let expr = arg.to_expression();
if let Some(mut converted) = convert_oxc_expression(allocator, expr, source_text) {
let converted = match expr {
// ngtsc rebuilds the metadata from its plain properties when it
// inlines resources, so methods and accessors are dropped.
Expression::ObjectExpression(obj)
if is_component_decorator
&& decorator_idx == 0
&& arg_idx == 0
&& has_resource_property(obj) =>
{
convert_plain_properties(allocator, obj, source_text)
}
_ => convert_oxc_expression(allocator, expr, source_text),
};
if let Some(mut converted) = converted {
// Inline resolved templates/styles into the first arg of the
// first @Component decorator. Other decorators / other args
// are left alone.
Expand Down Expand Up @@ -154,6 +169,18 @@ pub fn build_decorator_metadata_array<'a>(
))
}

/// Whether a `@Component` metadata object has a resource field that ngtsc
/// inlines: `templateUrl`, `styleUrl`, `styleUrls` or `styles`.
fn has_resource_property(obj: &oxc_ast::ast::ObjectExpression<'_>) -> bool {
obj.properties.iter().any(|prop| {
let ObjectPropertyKind::ObjectProperty(prop) = prop else { return false };
is_plain_property(prop)
&& get_property_key_name(&prop.key).is_some_and(|name| {
matches!(name.as_str(), "templateUrl" | "styleUrl" | "styleUrls" | "styles")
})
})
}

/// Rewrite the `@Component` config map so external resource references are
/// inlined into the `setClassMetadata` args.
///
Expand Down
13 changes: 10 additions & 3 deletions crates/oxc_angular_compiler/src/component/decorator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use crate::directive::{
extract_output_metadata_in, merge_by_class_property, parse_decorator_io,
};
use crate::output::oxc_converter::convert_oxc_expression;
use crate::util::is_metadata_property;

/// Extract component metadata from a class with decorators.
///
Expand Down Expand Up @@ -81,7 +82,9 @@ pub fn extract_component_metadata<'a>(

// Parse each property in the config object
for prop in &config_obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
let key_name = get_property_key_name(&prop.key, consts)?;

match key_name.as_str() {
Expand Down Expand Up @@ -493,7 +496,9 @@ fn extract_host_metadata<'a>(
};

for prop in &obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
let Some(key_name) = get_property_key_name(&prop.key, consts) else {
continue;
};
Expand Down Expand Up @@ -595,7 +600,9 @@ fn extract_single_host_directive<'a>(
let mut is_forward_reference = false;

for prop in &obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
let Some(key_name) = get_property_key_name(&prop.key, consts) else {
continue;
};
Expand Down
13 changes: 10 additions & 3 deletions crates/oxc_angular_compiler/src/directive/decorator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use super::metadata::{
use crate::factory::R3DependencyMetadata;
use crate::output::ast::{OutputAstBuilder, OutputExpression, ReadVarExpr};
use crate::output::oxc_converter::convert_oxc_expression;
use crate::util::is_metadata_property;

/// Find the @Directive decorator in a list of decorators. With the file's
/// `consts`, only Angular's (imported from `@angular/core`, see
Expand Down Expand Up @@ -130,7 +131,9 @@ pub fn extract_directive_metadata<'a>(
// Parse each property in the config object (if present)
if let Some(config_obj) = config_obj {
for prop in &config_obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
let Some(key_name) = get_property_key_name(&prop.key, consts) else {
continue;
};
Expand Down Expand Up @@ -1396,7 +1399,9 @@ fn extract_host_metadata<'a>(
let mut host = R3HostMetadata::new(allocator);

for prop in &obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
let Some(key_name) = get_property_key_name(&prop.key, consts) else {
continue;
};
Expand Down Expand Up @@ -1486,7 +1491,9 @@ fn extract_single_host_directive<'a>(
let mut is_forward_reference = false;

for prop in &obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
let Some(key_name) = get_property_key_name(&prop.key, consts) else {
continue;
};
Expand Down
14 changes: 11 additions & 3 deletions crates/oxc_angular_compiler/src/directive/property_decorators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use super::evaluator::{Evaluator, Value};
use super::metadata::{QueryPredicate, R3InputMetadata, R3QueryMetadata};
use crate::output::ast::OutputExpression;
use crate::output::oxc_converter::convert_oxc_expression;
use crate::util::is_metadata_property;

// ============================================================================
// Helper Functions
Expand Down Expand Up @@ -372,7 +373,9 @@ fn parse_literal_input_config<'a>(
let mut config = InputConfig::default();

for prop in &obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
let Some(key_name) = get_property_key_name(&prop.key) else {
continue;
};
Expand Down Expand Up @@ -463,6 +466,7 @@ fn options_alias<'a>(options: Option<&Argument<'a>>) -> Option<Ident<'a>> {
let mut alias = None;
for prop in &obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
&& get_property_key_name(&prop.key).is_some_and(|key| key == "alias")
{
alias = extract_string_value(&prop.value);
Expand Down Expand Up @@ -948,7 +952,9 @@ fn parse_query_config<'a>(
if let Some(second_arg) = call.arguments.get(1) {
if let Argument::ObjectExpression(obj) = second_arg {
for prop in &obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
let Some(key_name) = get_property_key_name(&prop.key) else {
continue;
};
Expand Down Expand Up @@ -1071,7 +1077,9 @@ fn try_parse_signal_query<'a>(
if let Some(second_arg) = call_expr.arguments.get(1) {
if let Argument::ObjectExpression(obj) = second_arg {
for prop in &obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
let Some(key_name) = get_property_key_name(&prop.key) else {
continue;
};
Expand Down
25 changes: 19 additions & 6 deletions crates/oxc_angular_compiler/src/injectable/decorator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use crate::directive::StringConsts;
use crate::factory::R3DependencyMetadata;
use crate::output::ast::{OutputExpression, ReadVarExpr};
use crate::output::oxc_converter::convert_oxc_expression;
use crate::util::is_metadata_property;

/// Extracted injectable metadata from a `@Injectable` decorator.
#[derive(Debug)]
Expand Down Expand Up @@ -342,7 +343,9 @@ fn extract_provided_in<'a>(
source_text: Option<&'a str>,
) -> Option<ProvidedInValue<'a>> {
for prop in &config_obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
if let Some(key_name) = get_property_key_name(&prop.key) {
if key_name.as_str() == "providedIn" {
return parse_provided_in_value(allocator, &prop.value, source_text);
Expand Down Expand Up @@ -381,7 +384,9 @@ fn extract_use_class<'a>(
source_text: Option<&'a str>,
) -> Option<UseClassMetadata<'a>> {
for prop in &config_obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
if let Some(key_name) = get_property_key_name(&prop.key) {
if key_name.as_str() == "useClass" {
let (class_expr, is_forward_ref) =
Expand All @@ -401,7 +406,9 @@ fn extract_use_factory<'a>(
source_text: Option<&'a str>,
) -> Option<UseFactoryMetadata<'a>> {
for prop in &config_obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
if let Some(key_name) = get_property_key_name(&prop.key) {
if key_name.as_str() == "useFactory" {
let factory = convert_oxc_expression(allocator, &prop.value, source_text)?;
Expand All @@ -420,7 +427,9 @@ fn extract_use_value<'a>(
source_text: Option<&'a str>,
) -> Option<OutputExpression<'a>> {
for prop in &config_obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
if let Some(key_name) = get_property_key_name(&prop.key) {
if key_name.as_str() == "useValue" {
return convert_oxc_expression(allocator, &prop.value, source_text);
Expand All @@ -437,7 +446,9 @@ fn extract_use_existing<'a>(
source_text: Option<&'a str>,
) -> Option<UseExistingMetadata<'a>> {
for prop in &config_obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
if let Some(key_name) = get_property_key_name(&prop.key) {
if key_name.as_str() == "useExisting" {
let (existing, is_forward_ref) =
Expand Down Expand Up @@ -485,7 +496,9 @@ fn extract_deps_from_config<'a>(
let mut deps = Vec::new_in(&allocator);

for prop in &config_obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
if let Some(key_name) = get_property_key_name(&prop.key) {
if key_name.as_str() == "deps" {
if let Expression::ArrayExpression(arr) = &prop.value {
Expand Down
5 changes: 4 additions & 1 deletion crates/oxc_angular_compiler/src/ng_module/decorator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use crate::directive::StringConsts;
use crate::factory::R3DependencyMetadata;
use crate::output::ast::{OutputExpression, ReadVarExpr};
use crate::output::oxc_converter::convert_oxc_expression;
use crate::util::is_metadata_property;

/// Extracted NgModule metadata from a `@NgModule` decorator.
///
Expand Down Expand Up @@ -225,7 +226,9 @@ pub(crate) fn extract_ng_module_metadata_in<'a>(

// Parse each property in the config object
for prop in &config_obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if let ObjectPropertyKind::ObjectProperty(prop) = prop
&& is_metadata_property(prop)
{
let Some(key_name) = get_property_key_name(&prop.key) else {
continue;
};
Expand Down
7 changes: 6 additions & 1 deletion crates/oxc_angular_compiler/src/output/emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -776,7 +776,12 @@ impl JsEmitter {
OutputExpression::Parenthesized(p) => p.expr.as_ref(),
other => other,
};
let is_object_literal = matches!(inner, OutputExpression::LiteralMap(_));
// Objects the converter keeps as written arrive as raw source.
let is_object_literal = match inner {
OutputExpression::LiteralMap(_) => true,
OutputExpression::RawSource(raw) => raw.source.starts_with('{'),
_ => false,
};
if is_object_literal {
ctx.print("(");
}
Expand Down
68 changes: 60 additions & 8 deletions crates/oxc_angular_compiler/src/output/oxc_converter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
use oxc_allocator::{Allocator, Box, Vec as OxcVec};
use oxc_ast::ast::{
Argument, ArrayExpressionElement, BindingPattern, Expression, ObjectPropertyKind, PropertyKey,
UnaryOperator as OxcUnaryOperator,
PropertyKind, UnaryOperator as OxcUnaryOperator,
};
use oxc_span::Span;
use oxc_str::Ident;
Expand Down Expand Up @@ -300,25 +300,57 @@ fn convert_object_expression<'a>(
allocator: &'a Allocator,
obj: &oxc_ast::ast::ObjectExpression<'a>,
source_text: Option<&'a str>,
) -> Option<OutputExpression<'a>> {
// A `LiteralMap` entry is a plain `key: value` pair, so methods (`a() {}`),
// accessors (`get a() {}`), computed keys (`[a]: 1`) and other key kinds
// cannot be represented. Keep such objects as written rather than emitting
// an altered object.
if obj
.properties
.iter()
.any(|prop| matches!(prop, ObjectPropertyKind::ObjectProperty(p) if !is_plain_property(p)))
{
return make_raw_source(allocator, source_text, obj.span);
}
convert_plain_properties(allocator, obj, source_text)
}

/// Whether a property is a `key: value` pair with an identifier, string or number key.
pub fn is_plain_property(p: &oxc_ast::ast::ObjectProperty<'_>) -> bool {
!p.method
&& !p.computed
&& p.kind == PropertyKind::Init
&& matches!(
p.key,
PropertyKey::StaticIdentifier(_)
| PropertyKey::StringLiteral(_)
| PropertyKey::NumericLiteral(_)
)
}

/// Convert an object expression, keeping only its plain `key: value` pairs and
/// spreads. ngtsc rebuilds a component's metadata the same way when it inlines
/// resources (`transformDecoratorResources`).
pub fn convert_plain_properties<'a>(
allocator: &'a Allocator,
obj: &oxc_ast::ast::ObjectExpression<'a>,
source_text: Option<&'a str>,
) -> Option<OutputExpression<'a>> {
let mut entries = OxcVec::with_capacity_in(obj.properties.len(), &allocator);

for prop in &obj.properties {
match prop {
ObjectPropertyKind::ObjectProperty(p) => {
// Get the property key
if !is_plain_property(p) {
continue;
}
let (key, quoted) = match &p.key {
PropertyKey::StaticIdentifier(id) => (id.name.clone().into(), false),
PropertyKey::StringLiteral(lit) => (lit.value.clone().into(), true),
PropertyKey::NumericLiteral(lit) => {
(Ident::from(allocator.alloc_str(&lit.value.to_string())), true)
}
PropertyKey::PrivateIdentifier(_) => return None, // Private fields not supported
_ => {
// Computed property key - try to convert it
// For now, skip computed properties
continue;
}
_ => continue,
};

// Convert the value
Expand Down Expand Up @@ -760,6 +792,10 @@ fn strip_expression_types(expr_source: &str) -> String {
return inner.to_string();
}
}
// Codegen drops parentheses it doesn't need, e.g. "0, { a() {} };"
if let Some(inner) = code.strip_prefix("0, ").and_then(|rest| rest.strip_suffix(';')) {
return inner.to_string();
}

// Fallback: return original
expr_source.to_string()
Expand Down Expand Up @@ -1151,4 +1187,20 @@ mod tests {
assert!(!result.contains(": number"), "Should strip type annotation. Got: {result}");
assert!(result.contains("=> x + 1"), "Should preserve expression. Got: {result}");
}

#[test]
fn test_object_with_method_falls_back_to_raw_source_without_types() {
let allocator = Allocator::default();
let source = "{ attach(x: string): string { return x; }, [key]: 1 }";
let expr = Parser::new(&allocator, source, SourceType::ts())
.parse_expression()
.expect("Failed to parse expression");
let result = convert_oxc_expression(&allocator, &expr, Some(source));
let Some(OutputExpression::RawSource(raw)) = result else {
panic!("Expected RawSource expression, got {result:?}");
};
let raw = raw.source.as_str();
assert!(!raw.contains(": string"), "Should strip type annotations. Got: {raw}");
assert!(raw.contains("attach(x)") && raw.contains("[key]: 1"), "Got: {raw}");
}
}
Loading
Loading