use alloc::borrow::ToOwned;
use crate::query::{label_text, pred_ast};
use crate::syntax::builders::export_statement::build_exported_name_node;
use crate::syntax::fields::javascript::{export_specifier, export_statement};
use crate::syntax::readers::javascript::common::strip_quotes;
use crate::syntax::{SyntaxGraphArgs, SyntaxGraphError};
use crate::utilities::text_nodes::node_to_str;
use crate::{CodeGraph, NodeId};
#[expect(
clippy::unnecessary_wraps,
reason = "the signature must match the reader dispatch table"
)]
pub fn reader(
args: &mut SyntaxGraphArgs<'_>,
n_id: NodeId,
) -> Result<Option<NodeId>, SyntaxGraphError> {
let graph = args.ast_graph;
let module_name = pred_ast(graph, n_id, Some(2))
.into_iter()
.find(|id| graph.label_type(*id) == Some("export_statement"))
.and_then(|statement_id| args.optional_field_alt(statement_id, export_statement::SOURCE))
.map(|source_id| strip_quotes(&node_to_str(graph, source_id)));
let name = args
.required_field_alt(n_id, export_specifier::NAME)
.ok()
.and_then(|name_id| label_text(graph, name_id))
.map(ToOwned::to_owned)
.unwrap_or_default();
let alias = args
.optional_field_alt(n_id, export_specifier::ALIAS)
.and_then(|alias_id| label_text(graph, alias_id))
.map_or_else(|| name.clone(), ToOwned::to_owned);
let expression = match module_name {
Some(module_name) => alloc::format!("{module_name}.{name}"),
None => name,
};
Ok(Some(build_exported_name_node(
args,
n_id,
expression,
Some(alias),
)))
}