use ecow::eco_format;
use typst_syntax::Spanned;
use crate::diag::{At, SourceResult};
use crate::engine::Engine;
use crate::foundations::{func, scope, Str, Value};
use crate::loading::{DataSource, Load, Readable};
#[func(scope, title = "YAML")]
pub fn yaml(
engine: &mut Engine,
source: Spanned<DataSource>,
) -> SourceResult<Value> {
let data = source.load(engine.world)?;
serde_yaml::from_slice(data.as_slice())
.map_err(|err| eco_format!("failed to parse YAML ({err})"))
.at(source.span)
}
#[scope]
impl yaml {
#[func(title = "Decode YAML")]
#[deprecated = "`yaml.decode` is deprecated, directly pass bytes to `yaml` instead"]
pub fn decode(
engine: &mut Engine,
data: Spanned<Readable>,
) -> SourceResult<Value> {
yaml(engine, data.map(Readable::into_source))
}
#[func(title = "Encode YAML")]
pub fn encode(
value: Spanned<Value>,
) -> SourceResult<Str> {
let Spanned { v: value, span } = value;
serde_yaml::to_string(&value)
.map(|v| v.into())
.map_err(|err| eco_format!("failed to encode value as YAML ({err})"))
.at(span)
}
}