Skip to main content

alpha2_compose/
template.rs

1//! Templates are compose documents with typed parameters, bound to data into plain specs.
2//!
3//! A template is a compose document with a `template` header and `params`. Binding validates
4//! the data, then replaces `{"$param": name}` values, `{{name}}` in strings, and the `$if`,
5//! `$switch` and `$each` directives, and expands `owner/name` template nodes, leaving a spec
6//! with no `$` left in it. Binding is logic-less and works on the JSON before it is parsed, so
7//! every compose field can be a parameter. One binding makes at most [`MAX_BOUND_VALUES`] values
8//! in template bodies.
9
10use std::collections::{BTreeMap, BTreeSet};
11
12use serde::Serialize;
13use serde_json::{Map, Value, json};
14
15use crate::ComposeError;
16
17/// Template nodes nest at most this deep.
18const MAX_DEPTH: usize = 16;
19
20/// Values one binding may make in template bodies, a string counting one per 64 bytes.
21pub const MAX_BOUND_VALUES: usize = 100_000;
22
23/// Bytes of a string that count as one bound value.
24const STRING_BYTES_PER_VALUE: usize = 64;
25
26/// Keys whose string values are names, not text, so `{{...}}` in them is left alone.
27const NAME_KEYS: [&str; 2] = ["type", "id"];
28
29/// Keys whose string values are text a viewer reads, checked for literal copy in templates.
30const TEXT_KEYS: [&str; 8] = [
31    "text", "subtitle", "title", "name", "role", "label", "cta", "caption",
32];
33
34/// Keys whose string values are files, checked for literal media in templates.
35const FILE_KEYS: [&str; 4] = ["path", "file", "logo", "fit_to"];
36
37/// What binding takes besides the template and its data.
38#[derive(Clone, Debug, Default)]
39pub struct BindOptions {
40    /// A theme for a video template, replacing the one it names.
41    pub theme: Option<Value>,
42    /// Node templates the document may name, by their header ids.
43    pub templates: Vec<Value>,
44}
45
46/// A problem `lint` finds.
47#[derive(Clone, Debug, PartialEq, Serialize)]
48pub struct Issue {
49    /// Where, as a dotted path into the template (`template.params[0]`) or the data (`data.title`).
50    pub path: String,
51    /// A stable code for the kind of problem.
52    pub code: &'static str,
53    /// What is wrong.
54    pub message: String,
55    /// `error` fails binding or compiling; `warning` does not.
56    pub severity: Severity,
57}
58
59/// How serious an [`Issue`] is.
60#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
61#[serde(rename_all = "snake_case")]
62pub enum Severity {
63    /// Binding or compiling fails.
64    Error,
65    /// Allowed, but likely a mistake.
66    Warning,
67}
68
69/// A template's header.
70#[derive(Clone, Debug)]
71struct Header {
72    id: String,
73    version: u64,
74    kind: Kind,
75    title: Option<String>,
76    description: Option<String>,
77}
78
79#[derive(Clone, Copy, Debug, Eq, PartialEq)]
80enum Kind {
81    Video,
82    Node,
83}
84
85/// One declared parameter.
86#[derive(Clone, Debug)]
87struct Param {
88    name: String,
89    kind: ParamKind,
90    title: Option<String>,
91    description: Option<String>,
92    default: Option<Value>,
93    required: bool,
94}
95
96#[derive(Clone, Debug)]
97enum ParamKind {
98    Text {
99        min_chars: Option<u64>,
100        max_chars: Option<u64>,
101        multiline: bool,
102    },
103    Media {
104        accept: Vec<String>,
105        rules: Map<String, Value>,
106    },
107    Audio {
108        rules: Map<String, Value>,
109    },
110    Number {
111        min: Option<f64>,
112        max: Option<f64>,
113    },
114    Bool,
115    Enum(Vec<String>),
116    Color,
117    Font,
118    List {
119        min_items: Option<u64>,
120        max_items: Option<u64>,
121        item: Vec<Param>,
122    },
123    /// A compose node: what a wrapping template (a reveal, a frame) draws its effect on.
124    Node,
125}
126
127impl ParamKind {
128    const fn name(&self) -> &'static str {
129        match self {
130            Self::Text { .. } => "text",
131            Self::Media { .. } => "media",
132            Self::Audio { .. } => "audio",
133            Self::Number { .. } => "number",
134            Self::Bool => "bool",
135            Self::Enum(_) => "enum",
136            Self::Color => "color",
137            Self::Font => "font",
138            Self::List { .. } => "list",
139            Self::Node => "node",
140        }
141    }
142}
143
144fn error(path: &str, message: impl Into<String>) -> ComposeError {
145    ComposeError::new(path, message)
146}
147
148fn header(document: &Value) -> Result<Option<Header>, ComposeError> {
149    let Some(value) = document.get("template") else {
150        return Ok(None);
151    };
152    let path = "template.template";
153    let object = value
154        .as_object()
155        .ok_or_else(|| error(path, "a template header is an object"))?;
156    if let Some(field) = object
157        .keys()
158        .find(|field| !["id", "version", "kind", "title", "description"].contains(&field.as_str()))
159    {
160        return Err(error(
161            &format!("{path}.{field}"),
162            "not a template header field",
163        ));
164    }
165    let id = object
166        .get("id")
167        .and_then(Value::as_str)
168        .ok_or_else(|| error(&format!("{path}.id"), "a template has an `owner/name` id"))?;
169    let parts = id.split('/').collect::<Vec<_>>();
170    let well_named = |part: &&str| {
171        !part.is_empty()
172            && part
173                .chars()
174                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
175    };
176    if parts.len() != 2 || !parts.iter().all(well_named) {
177        return Err(error(
178            &format!("{path}.id"),
179            format!("\"{id}\" is not `owner/name` in lower-case letters, digits, `-` and `_`"),
180        ));
181    }
182    let version = object
183        .get("version")
184        .and_then(Value::as_u64)
185        .filter(|version| *version > 0)
186        .ok_or_else(|| {
187            error(
188                &format!("{path}.version"),
189                "a version is a positive integer",
190            )
191        })?;
192    let kind = match object.get("kind").and_then(Value::as_str) {
193        Some("video") | None => Kind::Video,
194        Some("node") => Kind::Node,
195        Some(other) => {
196            return Err(error(
197                &format!("{path}.kind"),
198                format!("a template is a `video` or a `node`, not \"{other}\""),
199            ));
200        }
201    };
202    let text = |field: &str| object.get(field).and_then(Value::as_str).map(str::to_owned);
203    Ok(Some(Header {
204        id: id.to_owned(),
205        version,
206        kind,
207        title: text("title"),
208        description: text("description"),
209    }))
210}
211
212fn params(value: Option<&Value>, path: &str) -> Result<Vec<Param>, ComposeError> {
213    let Some(value) = value else {
214        return Ok(Vec::new());
215    };
216    let list = value
217        .as_array()
218        .ok_or_else(|| error(path, "`params` is a list"))?;
219    let mut seen = BTreeSet::new();
220    let mut parsed = Vec::with_capacity(list.len());
221    for (index, entry) in list.iter().enumerate() {
222        let at = format!("{path}[{index}]");
223        let param = param(entry, &at)?;
224        if !seen.insert(param.name.clone()) {
225            return Err(error(
226                &format!("{at}.name"),
227                format!("{} is declared twice", param.name),
228            ));
229        }
230        parsed.push(param);
231    }
232    Ok(parsed)
233}
234
235fn param(entry: &Value, path: &str) -> Result<Param, ComposeError> {
236    let object = entry
237        .as_object()
238        .ok_or_else(|| error(path, "a parameter is an object"))?;
239    let name = object
240        .get("name")
241        .and_then(Value::as_str)
242        .filter(|name| {
243            let mut chars = name.chars();
244            chars
245                .next()
246                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
247                && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
248        })
249        .ok_or_else(|| {
250            error(
251                &format!("{path}.name"),
252                "a parameter's name is a letter or `_`, then letters, digits or `_`",
253            )
254        })?
255        .to_owned();
256    let kind = param_kind(object, path)?;
257    let default = object.get("default").cloned();
258    let required = object
259        .get("required")
260        .and_then(Value::as_bool)
261        .unwrap_or(default.is_none());
262    let text = |field: &str| object.get(field).and_then(Value::as_str).map(str::to_owned);
263    let param = Param {
264        name,
265        kind,
266        title: text("title"),
267        description: text("description"),
268        default,
269        required,
270    };
271    if let Some(default) = &param.default {
272        check_value(&param, default, &format!("{path}.default"))?;
273    }
274    Ok(param)
275}
276
277/// A parameter's type and the checks it declares.
278fn param_kind(object: &Map<String, Value>, path: &str) -> Result<ParamKind, ComposeError> {
279    let u64_field = |field: &str| object.get(field).and_then(Value::as_u64);
280    let f64_field = |field: &str| object.get(field).and_then(Value::as_f64);
281    // A minimum no binding can meet is refused here, before sample data is made for it.
282    let minimum = |field: &str| match u64_field(field) {
283        Some(least) if least > MAX_BOUND_VALUES as u64 => Err(error(
284            &format!("{path}.{field}"),
285            format!("{least} is more than a binding makes ({MAX_BOUND_VALUES} values)"),
286        )),
287        least => Ok(least),
288    };
289    Ok(match object.get("type").and_then(Value::as_str) {
290        Some("text") => ParamKind::Text {
291            min_chars: minimum("min_chars")?,
292            max_chars: u64_field("max_chars"),
293            multiline: object
294                .get("multiline")
295                .and_then(Value::as_bool)
296                .unwrap_or(false),
297        },
298        Some("media") => ParamKind::Media {
299            accept: match object.get("accept") {
300                None => vec!["image".to_owned(), "video".to_owned()],
301                Some(Value::Array(kinds)) => kinds
302                    .iter()
303                    .map(|kind| match kind.as_str() {
304                        Some(kind @ ("image" | "video")) => Ok(kind.to_owned()),
305                        _ => Err(error(
306                            &format!("{path}.accept"),
307                            "accept lists `image` and `video`",
308                        )),
309                    })
310                    .collect::<Result<Vec<_>, _>>()?,
311                Some(_) => return Err(error(&format!("{path}.accept"), "accept is a list")),
312            },
313            rules: rules(
314                object,
315                &[
316                    "aspect",
317                    "min_width",
318                    "min_height",
319                    "min_duration",
320                    "max_duration",
321                ],
322            ),
323        },
324        Some("audio") => ParamKind::Audio {
325            rules: rules(object, &["min_duration", "max_duration"]),
326        },
327        Some("number") => ParamKind::Number {
328            min: f64_field("min"),
329            max: f64_field("max"),
330        },
331        Some("bool") => ParamKind::Bool,
332        Some("enum") => {
333            let values = object
334                .get("values")
335                .and_then(Value::as_array)
336                .filter(|values| !values.is_empty())
337                .ok_or_else(|| error(&format!("{path}.values"), "an enum lists its values"))?
338                .iter()
339                .map(|value| {
340                    value
341                        .as_str()
342                        .or_else(|| value.get("value").and_then(Value::as_str))
343                        .map(str::to_owned)
344                        .ok_or_else(|| {
345                            error(
346                                &format!("{path}.values"),
347                                "a value is a string or `{value, title}`",
348                            )
349                        })
350                })
351                .collect::<Result<Vec<_>, _>>()?;
352            ParamKind::Enum(values)
353        }
354        Some("color") => ParamKind::Color,
355        Some("font") => ParamKind::Font,
356        Some("node") => ParamKind::Node,
357        Some("list") => ParamKind::List {
358            min_items: minimum("min_items")?,
359            max_items: u64_field("max_items"),
360            item: params(object.get("item"), &format!("{path}.item"))?,
361        },
362        other => {
363            return Err(error(
364                &format!("{path}.type"),
365                format!(
366                    "{} is not a parameter type; the types are text, media, audio, number, bool, \
367                     enum, color, font, list and node",
368                    other.map_or_else(|| "nothing".to_owned(), |name| format!("\"{name}\""))
369                ),
370            ));
371        }
372    })
373}
374
375fn rules(object: &Map<String, Value>, names: &[&str]) -> Map<String, Value> {
376    object
377        .iter()
378        .filter(|(field, _)| names.contains(&field.as_str()))
379        .map(|(field, value)| (field.clone(), value.clone()))
380        .collect()
381}
382
383/// Checks `value` against `param` where it can be checked without facts about files.
384fn check_value(param: &Param, value: &Value, path: &str) -> Result<(), ComposeError> {
385    let wrong = || {
386        error(
387            path,
388            format!(
389                "{} takes a {} value, not {value}",
390                param.name,
391                param.kind.name()
392            ),
393        )
394    };
395    match &param.kind {
396        ParamKind::Text {
397            min_chars,
398            max_chars,
399            multiline,
400        } => {
401            let text = value.as_str().ok_or_else(wrong)?;
402            let count = text.chars().count() as u64;
403            if min_chars.is_some_and(|min| count < min) || max_chars.is_some_and(|max| count > max)
404            {
405                return Err(error(
406                    path,
407                    format!(
408                        "{} takes {}{} characters, not {count}",
409                        param.name,
410                        min_chars.map_or_else(String::new, |min| format!("at least {min} ")),
411                        max_chars.map_or_else(String::new, |max| format!("at most {max}"))
412                    ),
413                ));
414            }
415            if !multiline && text.contains('\n') {
416                return Err(error(path, format!("{} is one line", param.name)));
417            }
418        }
419        ParamKind::Media { .. } | ParamKind::Audio { .. } | ParamKind::Font => {
420            if value.as_str().is_none_or(str::is_empty) {
421                return Err(wrong());
422            }
423        }
424        ParamKind::Number { min, max } => {
425            let number = value.as_f64().ok_or_else(wrong)?;
426            if min.is_some_and(|min| number < min) || max.is_some_and(|max| number > max) {
427                return Err(error(
428                    path,
429                    format!("{} is out of its range: {number}", param.name),
430                ));
431            }
432        }
433        ParamKind::Bool => {
434            value.as_bool().ok_or_else(wrong)?;
435        }
436        ParamKind::Enum(values) => {
437            let chosen = value.as_str().ok_or_else(wrong)?;
438            if !values.iter().any(|value| value == chosen) {
439                return Err(error(
440                    path,
441                    format!(
442                        "{} is one of {}, not \"{chosen}\"",
443                        param.name,
444                        values.join(", ")
445                    ),
446                ));
447            }
448        }
449        ParamKind::Color => {
450            serde_json::from_value::<crate::spec::SolidColor>(value.clone())
451                .map_err(|_| wrong())?;
452        }
453        ParamKind::Node => {
454            if value.get("type").and_then(Value::as_str).is_none() {
455                return Err(wrong());
456            }
457        }
458        ParamKind::List {
459            min_items,
460            max_items,
461            item,
462        } => {
463            let items = value.as_array().ok_or_else(wrong)?;
464            let count = items.len() as u64;
465            if min_items.is_some_and(|min| count < min) || max_items.is_some_and(|max| count > max)
466            {
467                return Err(error(
468                    path,
469                    format!(
470                        "{} holds a number of items out of its range: {count}",
471                        param.name
472                    ),
473                ));
474            }
475            for (index, entry) in items.iter().enumerate() {
476                resolve(item, entry, &format!("{path}[{index}]"))?;
477            }
478        }
479    }
480    Ok(())
481}
482
483/// The data for `params`: each given value checked, each missing one defaulted, refused when
484/// required, or absent.
485fn resolve(params: &[Param], data: &Value, path: &str) -> Result<Map<String, Value>, ComposeError> {
486    let empty = Map::new();
487    let given = match data {
488        Value::Null => &empty,
489        Value::Object(object) => object,
490        _ => return Err(error(path, "data is an object of parameter values")),
491    };
492    if let Some(unknown) = given
493        .keys()
494        .find(|name| !params.iter().any(|param| &param.name == *name))
495    {
496        let names = params
497            .iter()
498            .map(|param| param.name.as_str())
499            .collect::<Vec<_>>();
500        return Err(error(
501            &format!("{path}.{unknown}"),
502            format!(
503                "{unknown} is not a parameter; they are {}",
504                if names.is_empty() {
505                    "none".to_owned()
506                } else {
507                    names.join(", ")
508                }
509            ),
510        ));
511    }
512    let mut resolved = Map::new();
513    for param in params {
514        let at = format!("{path}.{}", param.name);
515        match given.get(&param.name).filter(|value| !value.is_null()) {
516            Some(value) => {
517                check_value(param, value, &at)?;
518                let value = match &param.kind {
519                    ParamKind::List { item, .. } => Value::Array(
520                        value
521                            .as_array()
522                            .into_iter()
523                            .flatten()
524                            .enumerate()
525                            .map(|(index, entry)| {
526                                resolve(item, entry, &format!("{at}[{index}]")).map(Value::Object)
527                            })
528                            .collect::<Result<Vec<_>, _>>()?,
529                    ),
530                    _ => value.clone(),
531                };
532                resolved.insert(param.name.clone(), value);
533            }
534            None => match &param.default {
535                Some(default) => {
536                    resolved.insert(param.name.clone(), default.clone());
537                }
538                None if param.required => {
539                    return Err(error(&at, format!("{} is required", param.name)));
540                }
541                None => {}
542            },
543        }
544    }
545    Ok(resolved)
546}
547
548/// What evaluating a piece of the template gives.
549enum Eval {
550    Value(Value),
551    Absent,
552    /// Several values, spliced into the list that holds them.
553    Splice(Vec<Value>),
554}
555
556/// The values in scope: parameters at the root, and one `$each` item in each frame over it.
557#[derive(Default)]
558struct Scope<'a> {
559    values: Map<String, Value>,
560    /// An `$each` item: its alias, the item, and its index as `{alias}.$index` reads it.
561    item: Option<(&'a str, &'a Value, Value)>,
562    parent: Option<&'a Scope<'a>>,
563    /// Set inside a template body, the only place directives and `{{name}}` are evaluated.
564    template: bool,
565}
566
567impl Scope<'_> {
568    /// The value at `name`, a dotted path from a parameter or alias.
569    fn lookup(&self, name: &str) -> Option<&Value> {
570        let (first, rest) = name
571            .split_once('.')
572            .map_or((name, None), |(first, rest)| (first, Some(rest)));
573        let mut scope = self;
574        let mut value = loop {
575            if let Some((alias, item, index)) = &scope.item
576                && *alias == first
577            {
578                if rest == Some("$index") && item.is_object() {
579                    return Some(index);
580                }
581                break *item;
582            }
583            match scope.parent {
584                Some(parent) => scope = parent,
585                None => break scope.values.get(first)?,
586            }
587        };
588        for part in rest.into_iter().flat_map(|rest| rest.split('.')) {
589            value = value.get(part)?;
590        }
591        Some(value)
592    }
593}
594
595/// What `value` counts against [`MAX_BOUND_VALUES`], counted no further than `limit`.
596fn cost(value: &Value, limit: usize) -> usize {
597    match value {
598        Value::String(text) => string_cost(text),
599        Value::Array(items) => items.iter().fold(1, |total, item| {
600            if total > limit {
601                total
602            } else {
603                total + cost(item, limit - total)
604            }
605        }),
606        Value::Object(object) => object.values().fold(1, |total, item| {
607            if total > limit {
608                total
609            } else {
610                total + cost(item, limit - total)
611            }
612        }),
613        _ => 1,
614    }
615}
616
617const fn string_cost(text: &str) -> usize {
618    1 + text.len() / STRING_BYTES_PER_VALUE
619}
620
621struct Binder<'a> {
622    templates: BTreeMap<String, &'a Value>,
623    stack: Vec<String>,
624    /// Values made in template bodies so far.
625    made: usize,
626}
627
628impl Binder<'_> {
629    /// Counts `count` more values made at `path`, refused past [`MAX_BOUND_VALUES`].
630    fn make(&mut self, count: usize, path: &str) -> Result<(), ComposeError> {
631        self.made = self.made.saturating_add(count);
632        if self.made > MAX_BOUND_VALUES {
633            return Err(error(
634                path,
635                format!(
636                    "binding makes more than {MAX_BOUND_VALUES} values here (a string counts one \
637                     per {STRING_BYTES_PER_VALUE} bytes)"
638                ),
639            ));
640        }
641        Ok(())
642    }
643
644    fn room(&self) -> usize {
645        MAX_BOUND_VALUES.saturating_sub(self.made)
646    }
647
648    fn eval(
649        &mut self,
650        value: &Value,
651        scope: &Scope<'_>,
652        key: Option<&str>,
653        path: &str,
654    ) -> Result<Eval, ComposeError> {
655        if scope.template && !matches!(value, Value::String(_)) {
656            self.make(1, path)?;
657        }
658        match value {
659            Value::Object(object) => self.eval_object(object, scope, path),
660            Value::Array(items) => {
661                let mut out = Vec::with_capacity(items.len());
662                for (index, item) in items.iter().enumerate() {
663                    match self.eval(item, scope, None, &format!("{path}[{index}]"))? {
664                        Eval::Value(value) => out.push(value),
665                        Eval::Absent => {}
666                        Eval::Splice(values) => out.extend(values),
667                    }
668                }
669                Ok(Eval::Value(Value::Array(out)))
670            }
671            Value::String(text) if scope.template => {
672                let text = if key.is_some_and(|key| NAME_KEYS.contains(&key)) {
673                    text.clone()
674                } else {
675                    interpolate(text, scope, path)?
676                };
677                self.make(string_cost(&text), path)?;
678                Ok(Eval::Value(Value::String(text)))
679            }
680            other => Ok(Eval::Value(other.clone())),
681        }
682    }
683
684    /// A `$param`, `$if`, `$switch` or `$each` object evaluated, or `None` for any other object.
685    fn directive(
686        &mut self,
687        object: &Map<String, Value>,
688        scope: &Scope<'_>,
689        path: &str,
690    ) -> Result<Option<Eval>, ComposeError> {
691        if let Some(name) = object.get("$param") {
692            let name = name
693                .as_str()
694                .ok_or_else(|| error(path, "`$param` names a parameter"))?;
695            if object.len() != 1 {
696                return Err(error(path, "a `$param` object has no other fields"));
697            }
698            return match scope.lookup(name) {
699                None => Ok(Some(Eval::Absent)),
700                Some(value) => {
701                    // The directive object itself was counted as one value.
702                    self.make(cost(value, self.room()).saturating_sub(1), path)?;
703                    Ok(Some(Eval::Value(value.clone())))
704                }
705            };
706        }
707        if let Some(name) = object.get("$if") {
708            let name = name
709                .as_str()
710                .ok_or_else(|| error(path, "`$if` names a parameter"))?;
711            let branch = if is_set(scope.lookup(name)) {
712                "then"
713            } else {
714                "else"
715            };
716            return match object.get(branch) {
717                Some(node) => self
718                    .eval(node, scope, None, &format!("{path}.{branch}"))
719                    .map(Some),
720                None => Ok(Some(Eval::Absent)),
721            };
722        }
723        if let Some(name) = object.get("$switch") {
724            let name = name
725                .as_str()
726                .ok_or_else(|| error(path, "`$switch` names an enum parameter"))?;
727            let chosen = scope.lookup(name).and_then(Value::as_str);
728            let cases = object.get("cases").and_then(Value::as_object);
729            let picked = chosen
730                .and_then(|chosen| {
731                    cases
732                        .and_then(|cases| cases.get(chosen))
733                        .map(|node| (node, format!("{path}.cases.{chosen}")))
734                })
735                .or_else(|| {
736                    object
737                        .get("default")
738                        .map(|node| (node, format!("{path}.default")))
739                });
740            return match picked {
741                Some((node, at)) => self.eval(node, scope, None, &at).map(Some),
742                None => Ok(Some(Eval::Absent)),
743            };
744        }
745        if let Some(name) = object.get("$each") {
746            let name = name
747                .as_str()
748                .ok_or_else(|| error(path, "`$each` names a list parameter"))?;
749            let alias = object
750                .get("as")
751                .and_then(Value::as_str)
752                .ok_or_else(|| error(path, "`$each` names each item with `as`"))?;
753            let node = object
754                .get("node")
755                .ok_or_else(|| error(path, "`$each` repeats a `node`"))?;
756            let items = scope
757                .lookup(name)
758                .and_then(Value::as_array)
759                .map_or(&[][..], Vec::as_slice);
760            let mut out = Vec::with_capacity(items.len());
761            for (index, item) in items.iter().enumerate() {
762                let inner = Scope {
763                    values: Map::new(),
764                    item: Some((alias, item, json!(index))),
765                    parent: Some(scope),
766                    template: scope.template,
767                };
768                match self.eval(node, &inner, None, &format!("{path}.node"))? {
769                    Eval::Value(value) => out.push(value),
770                    Eval::Absent => {}
771                    Eval::Splice(values) => out.extend(values),
772                }
773            }
774            return Ok(Some(Eval::Splice(out)));
775        }
776        Ok(None)
777    }
778
779    fn eval_object(
780        &mut self,
781        object: &Map<String, Value>,
782        scope: &Scope<'_>,
783        path: &str,
784    ) -> Result<Eval, ComposeError> {
785        if scope.template
786            && let Some(eval) = self.directive(object, scope, path)?
787        {
788            return Ok(eval);
789        }
790        if let Some(kind) = object.get("type").and_then(Value::as_str) {
791            if kind.contains('/') {
792                return self.instance(kind, object, scope, path).map(Eval::Value);
793            }
794            if let Some(id) = bare_template(kind) {
795                return self.bare(id, object, scope, path).map(Eval::Value);
796            }
797        }
798        let mut out = Map::with_capacity(object.len());
799        for (field, value) in object {
800            let at = format!("{path}.{field}");
801            match self.eval(value, scope, Some(field), &at)? {
802                Eval::Value(value) => {
803                    out.insert(field.clone(), value);
804                }
805                Eval::Absent => {}
806                Eval::Splice(_) => return Err(error(&at, "`$each` goes in a list")),
807            }
808        }
809        Ok(Eval::Value(Value::Object(out)))
810    }
811
812    /// A node template named by `id`, bound to the reference's `with`, as a stack carrying the
813    /// reference's placement.
814    fn instance(
815        &mut self,
816        id: &str,
817        object: &Map<String, Value>,
818        scope: &Scope<'_>,
819        path: &str,
820    ) -> Result<Value, ComposeError> {
821        self.reference(id, object, scope, &format!("{path}.with"), path)
822    }
823
824    /// Binds a 1st-party template named by its bare type, whose other fields are its data.
825    fn bare(
826        &mut self,
827        id: &str,
828        object: &Map<String, Value>,
829        scope: &Scope<'_>,
830        path: &str,
831    ) -> Result<Value, ComposeError> {
832        let (mut reference, data): (Map<_, _>, Map<_, _>) = object
833            .iter()
834            .filter(|(field, _)| field.as_str() != "type")
835            .map(|(field, value)| (field.clone(), value.clone()))
836            .partition(|(field, _)| PLACEMENT.contains(&field.as_str()));
837        reference.insert("type".to_owned(), json!(id));
838        reference.insert("with".to_owned(), Value::Object(data));
839        self.reference(id, &reference, scope, path, path)
840    }
841
842    /// [`Self::instance`], its data's errors named from `data_path`.
843    fn reference(
844        &mut self,
845        id: &str,
846        object: &Map<String, Value>,
847        scope: &Scope<'_>,
848        data_path: &str,
849        path: &str,
850    ) -> Result<Value, ComposeError> {
851        if let Some(field) = object.keys().find(|field| {
852            !["type", "with", "version"].contains(&field.as_str())
853                && !PLACEMENT.contains(&field.as_str())
854        }) {
855            return Err(error(
856                &format!("{path}.{field}"),
857                "a template node takes `with`, `version` and placement fields",
858            ));
859        }
860        let template = *self.templates.get(id).ok_or_else(|| {
861            error(
862                &format!("{path}.type"),
863                format!("no template \"{id}\" was given"),
864            )
865        })?;
866        let header = header(template)?.expect("templates are indexed by their headers");
867        if header.kind != Kind::Node {
868            return Err(error(
869                &format!("{path}.type"),
870                format!("{id} is a video template, not a node"),
871            ));
872        }
873        if let Some(version) = object.get("version")
874            && version.as_u64() != Some(header.version)
875        {
876            return Err(error(
877                &format!("{path}.version"),
878                format!("{id} is version {}, not {version}", header.version),
879            ));
880        }
881        if self.stack.iter().any(|open| open == id) || self.stack.len() >= MAX_DEPTH {
882            return Err(error(
883                path,
884                format!(
885                    "{id} names itself through its templates, or they nest deeper than {MAX_DEPTH}"
886                ),
887            ));
888        }
889        let data = match object.get("with") {
890            Some(with) => match self.eval(with, scope, None, &format!("{path}.with"))? {
891                Eval::Value(value) => value,
892                _ => Value::Null,
893            },
894            None => Value::Null,
895        };
896        self.stack.push(id.to_owned());
897        let bound = self.bind_body(
898            template,
899            &header,
900            &data,
901            data_path,
902            &format!("{path}<{id}>"),
903        );
904        self.stack.pop();
905        let node = bound?;
906        let mut stack = Map::new();
907        stack.insert("type".to_owned(), json!("stack"));
908        stack.insert("children".to_owned(), json!([node]));
909        for field in PLACEMENT {
910            if let Some(value) = object.get(field)
911                && let Eval::Value(value) =
912                    self.eval(value, scope, Some(field), &format!("{path}.{field}"))?
913            {
914                stack.insert(field.to_owned(), value);
915            }
916        }
917        Ok(Value::Object(stack))
918    }
919
920    /// A template's body bound to `data`: a video template's spec, or a node template's node.
921    fn bind_body(
922        &mut self,
923        template: &Value,
924        header: &Header,
925        data: &Value,
926        data_path: &str,
927        path: &str,
928    ) -> Result<Value, ComposeError> {
929        let params = params(template.get("params"), &format!("{path}.params"))?;
930        let values = resolve(&params, data, data_path)?;
931        let scope = Scope {
932            values,
933            template: true,
934            ..Scope::default()
935        };
936        match header.kind {
937            Kind::Node => {
938                let node = template
939                    .get("node")
940                    .ok_or_else(|| error(path, "a node template has a `node`"))?;
941                match self.eval(node, &scope, None, &format!("{path}.node"))? {
942                    Eval::Value(value) => Ok(value),
943                    _ => Err(error(
944                        &format!("{path}.node"),
945                        "a node template draws one node",
946                    )),
947                }
948            }
949            Kind::Video => {
950                let mut body = template.as_object().cloned().unwrap_or_default();
951                body.remove("template");
952                body.remove("params");
953                match self.eval(&Value::Object(body), &scope, None, path)? {
954                    Eval::Value(value) => Ok(value),
955                    _ => Err(error(path, "a video template is one spec")),
956                }
957            }
958        }
959    }
960}
961
962/// `text` with each `{{name}}` replaced by its parameter's text, number or choice; `{{{{` is a
963/// literal `{{`.
964fn interpolate(text: &str, scope: &Scope<'_>, path: &str) -> Result<String, ComposeError> {
965    if !text.contains("{{") {
966        return Ok(text.to_owned());
967    }
968    let mut out = String::with_capacity(text.len());
969    let mut rest = text;
970    while let Some(start) = rest.find("{{") {
971        out.push_str(&rest[..start]);
972        let after = &rest[start + 2..];
973        if let Some(stripped) = after.strip_prefix("{{") {
974            out.push_str("{{");
975            rest = stripped;
976            continue;
977        }
978        let end = after
979            .find("}}")
980            .ok_or_else(|| error(path, "a `{{` has no `}}`"))?;
981        let name = after[..end].trim();
982        match scope.lookup(name) {
983            None => {}
984            Some(Value::String(value)) => out.push_str(value),
985            Some(Value::Number(number)) => out.push_str(&format_number(number)),
986            Some(Value::Bool(flag)) => out.push_str(if *flag { "true" } else { "false" }),
987            Some(_) => {
988                return Err(error(
989                    path,
990                    format!("{{{{{name}}}}} is not text, a number or a choice"),
991                ));
992            }
993        }
994        rest = &after[end + 2..];
995    }
996    out.push_str(rest);
997    Ok(out)
998}
999
1000/// A number as decimal text: whole numbers without a fraction.
1001fn format_number(number: &serde_json::Number) -> String {
1002    match number.as_f64() {
1003        Some(value) if value.fract() == 0.0 && value.abs() < 1e15 => format!("{value:.0}"),
1004        _ => number.to_string(),
1005    }
1006}
1007
1008fn index(templates: &[Value]) -> Result<BTreeMap<String, &Value>, ComposeError> {
1009    let mut found = BTreeMap::new();
1010    for (position, template) in templates.iter().enumerate() {
1011        let header = header(template)
1012            .map_err(|problem| {
1013                error(
1014                    &format!("templates[{position}].{}", problem.path),
1015                    problem.message,
1016                )
1017            })?
1018            .ok_or_else(|| {
1019                error(
1020                    &format!("templates[{position}]"),
1021                    "a template has a `template` header",
1022                )
1023            })?;
1024        found.insert(header.id, template);
1025    }
1026    for template in crate::library::TEMPLATES.iter() {
1027        let header = header(template)?.expect("a built-in template has a header");
1028        found.entry(header.id).or_insert(template);
1029    }
1030    Ok(found)
1031}
1032
1033/// Binds `document` to `data`: a template's parameters replaced and its template nodes
1034/// expanded, giving a plain spec (or, for a node template, a plain node). A document without a
1035/// header has only its template nodes expanded; directives and `{{name}}` exist only in template
1036/// bodies. Without a header, template nodes or a theme, `bind` returns `document` unchanged.
1037///
1038/// # Errors
1039/// Returns where in the template or data, and why, it does not bind.
1040pub fn bind(document: &Value, data: &Value, options: &BindOptions) -> Result<Value, ComposeError> {
1041    let mut binder = Binder {
1042        templates: index(&options.templates)?,
1043        stack: Vec::new(),
1044        made: 0,
1045    };
1046    let header = header(document)?;
1047    let mut bound = match &header {
1048        Some(header) => {
1049            binder.stack.push(header.id.clone());
1050            binder.bind_body(document, header, data, "data", "template")?
1051        }
1052        None => match binder.eval(document, &Scope::default(), None, "spec")? {
1053            Eval::Value(value) => value,
1054            _ => return Err(error("spec", "a spec is one object")),
1055        },
1056    };
1057    if header
1058        .as_ref()
1059        .is_none_or(|header| header.kind == Kind::Video)
1060        && let Some(theme) = &options.theme
1061        && let Some(object) = bound.as_object_mut()
1062    {
1063        object.insert("theme".to_owned(), theme.clone());
1064    }
1065    Ok(bound)
1066}
1067
1068/// Fields of a template node that place it, beside its template's data.
1069const PLACEMENT: [&str; 6] = ["id", "at", "duration", "inset", "enter", "exit"];
1070
1071/// Node types that name a 1st-party template without its `alpha2/` owner.
1072pub(crate) const BARE: [(&str, &str); 7] = [
1073    ("title", "alpha2/title"),
1074    ("title_card", "alpha2/title-card"),
1075    ("lower_third", "alpha2/lower-third"),
1076    ("end_card", "alpha2/end-card"),
1077    ("logo", "alpha2/logo"),
1078    ("reframe", "alpha2/reframe"),
1079    ("comparison_grid", "alpha2/comparison-grid"),
1080];
1081
1082fn bare_template(kind: &str) -> Option<&'static str> {
1083    BARE.iter()
1084        .find(|(name, _)| *name == kind)
1085        .map(|(_, id)| *id)
1086}
1087
1088/// Whether `$if` takes its `then`, for a true bool or any other value that is given and not empty.
1089fn is_set(value: Option<&Value>) -> bool {
1090    match value {
1091        None | Some(Value::Null) => false,
1092        Some(Value::Bool(value)) => *value,
1093        Some(Value::String(text)) => !text.is_empty(),
1094        Some(Value::Array(items)) => !items.is_empty(),
1095        Some(Value::Object(fields)) => !fields.is_empty(),
1096        Some(Value::Number(_)) => true,
1097    }
1098}
1099
1100/// The JSON Schema (2020-12) of a template's data, with each parameter's title, description,
1101/// default and checks a schema can say; file rules are in `x-alpha2-media`.
1102///
1103/// # Errors
1104/// Returns where the template's header or parameters do not parse.
1105///
1106/// # Panics
1107/// Never; an object schema is always an object.
1108pub fn data_schema(template: &Value) -> Result<Value, ComposeError> {
1109    let header =
1110        header(template)?.ok_or_else(|| error("template", "a template has a `template` header"))?;
1111    let params = params(template.get("params"), "template.params")?;
1112    let mut schema = object_schema(&params);
1113    let object = schema.as_object_mut().expect("an object schema");
1114    object.insert(
1115        "$schema".to_owned(),
1116        json!("https://json-schema.org/draft/2020-12/schema"),
1117    );
1118    if let Some(name) = header.id.strip_prefix("alpha2/") {
1119        object.insert(
1120            "$id".to_owned(),
1121            json!(format!(
1122                "https://alpha2.sh/templates/{name}/v{}/data.json",
1123                header.version
1124            )),
1125        );
1126    }
1127    object.insert("title".to_owned(), json!(header.title.unwrap_or(header.id)));
1128    if let Some(description) = header.description {
1129        object.insert("description".to_owned(), json!(description));
1130    }
1131    Ok(schema)
1132}
1133
1134/// Where a data schema's references to compose types point.
1135#[derive(Clone, Copy)]
1136enum Refs {
1137    /// The published compose schema, for a data schema of its own.
1138    Published,
1139    /// `#/$defs`, inside the compose schema.
1140    #[cfg_attr(not(feature = "schema"), allow(dead_code))]
1141    Local,
1142}
1143
1144impl Refs {
1145    fn to(self, name: &str) -> Value {
1146        match self {
1147            Self::Published => {
1148                json!({"$ref": format!("{}#/$defs/{name}", crate::spec::COMPOSE_SCHEMA_ID)})
1149            }
1150            Self::Local => json!({"$ref": format!("#/$defs/{name}")}),
1151        }
1152    }
1153}
1154
1155/// Compose schema variants for template nodes. Each 1st-party template gets typed variants for
1156/// its `alpha2/` id and bare name, and one variant takes any other `owner/name`.
1157#[cfg(feature = "schema")]
1158pub(crate) fn node_schemas() -> Vec<Value> {
1159    let placement = |properties: &mut Map<String, Value>| {
1160        properties.insert("id".to_owned(), json!({"type": "string", "description": "The node's name, for other nodes to refer to."}));
1161        properties.insert("at".to_owned(), json!({"type": "number", "description": "Seconds from the parent's start (an overlay's: the video's). Ignored in a sequence."}));
1162        properties.insert("duration".to_owned(), json!({"type": "number", "description": "Length in seconds. Default: the template's own, else what its parent gives it."}));
1163        properties.insert("inset".to_owned(), Refs::Local.to("Inset"));
1164        properties.insert("enter".to_owned(), Refs::Local.to("Motion"));
1165        properties.insert("exit".to_owned(), Refs::Local.to("Motion"));
1166    };
1167    let mut variants = Vec::new();
1168    for template in crate::library::TEMPLATES.iter() {
1169        let header = header(template)
1170            .ok()
1171            .flatten()
1172            .expect("a built-in template has a header");
1173        let params = params(template.get("params"), "template.params")
1174            .expect("a built-in template's parameters parse");
1175        let data = object_schema_with(&params, Refs::Local);
1176        let description = header.description.clone().unwrap_or_default();
1177        if let Some((name, _)) = BARE.iter().find(|(_, id)| *id == header.id) {
1178            let mut properties = data["properties"].as_object().cloned().unwrap_or_default();
1179            properties.insert("type".to_owned(), json!({"const": name}));
1180            placement(&mut properties);
1181            let mut required = data["required"].as_array().cloned().unwrap_or_default();
1182            required.insert(0, json!("type"));
1183            variants.push(json!({
1184                "type": "object",
1185                "description": description,
1186                "properties": properties,
1187                "required": required,
1188                "additionalProperties": false,
1189            }));
1190        }
1191        let mut properties = Map::new();
1192        properties.insert("type".to_owned(), json!({"const": header.id}));
1193        properties.insert("version".to_owned(), json!({"const": header.version}));
1194        properties.insert("with".to_owned(), data.clone());
1195        placement(&mut properties);
1196        let required = if data["required"]
1197            .as_array()
1198            .is_some_and(|list| !list.is_empty())
1199        {
1200            json!(["type", "with"])
1201        } else {
1202            json!(["type"])
1203        };
1204        variants.push(json!({
1205            "type": "object",
1206            "description": description,
1207            "properties": properties,
1208            "required": required,
1209            "additionalProperties": false,
1210        }));
1211    }
1212    let mut properties = Map::new();
1213    properties.insert(
1214        "type".to_owned(),
1215        json!({
1216            "type": "string",
1217            "pattern": "^[a-z0-9_-]+/[a-z0-9_-]+$",
1218            "not": {"pattern": "^alpha2/"},
1219            "description": "A template's `owner/name` id; the spec is compiled with it.",
1220        }),
1221    );
1222    properties.insert(
1223        "version".to_owned(),
1224        json!({"type": "integer", "minimum": 1}),
1225    );
1226    properties.insert(
1227        "with".to_owned(),
1228        json!({"type": "object", "description": "The template's data."}),
1229    );
1230    placement(&mut properties);
1231    variants.push(json!({
1232        "type": "object",
1233        "description": "A node template by its id, bound to `with`.",
1234        "properties": properties,
1235        "required": ["type"],
1236        "additionalProperties": false,
1237    }));
1238    variants
1239}
1240
1241fn object_schema(params: &[Param]) -> Value {
1242    object_schema_with(params, Refs::Published)
1243}
1244
1245fn object_schema_with(params: &[Param], refs: Refs) -> Value {
1246    let properties = params
1247        .iter()
1248        .map(|param| (param.name.clone(), param_schema(param, refs)))
1249        .collect::<Map<_, _>>();
1250    let required = params
1251        .iter()
1252        .filter(|param| param.required && param.default.is_none())
1253        .map(|param| json!(param.name))
1254        .collect::<Vec<_>>();
1255    json!({
1256        "type": "object",
1257        "properties": properties,
1258        "required": required,
1259        "additionalProperties": false,
1260    })
1261}
1262
1263fn param_schema(param: &Param, refs: Refs) -> Value {
1264    let mut schema = match &param.kind {
1265        ParamKind::Text {
1266            min_chars,
1267            max_chars,
1268            ..
1269        } => json!({"type": "string", "minLength": min_chars, "maxLength": max_chars}),
1270        ParamKind::Media { accept, rules } => {
1271            let mut media = rules.clone();
1272            media.insert("accept".to_owned(), json!(accept));
1273            json!({"type": "string", "format": "uri-reference", "x-alpha2-media": media})
1274        }
1275        ParamKind::Audio { rules } => {
1276            json!({"type": "string", "format": "uri-reference", "x-alpha2-audio": rules})
1277        }
1278        ParamKind::Number { min, max } => json!({"type": "number", "minimum": min, "maximum": max}),
1279        ParamKind::Bool => json!({"type": "boolean"}),
1280        ParamKind::Enum(values) => json!({"enum": values}),
1281        ParamKind::Color => refs.to("SolidColor"),
1282        ParamKind::Font => json!({"type": "string", "description": "A font family the host has."}),
1283        ParamKind::Node => refs.to("Node"),
1284        ParamKind::List {
1285            min_items,
1286            max_items,
1287            item,
1288        } => json!({
1289            "type": "array",
1290            "items": object_schema_with(item, refs),
1291            "minItems": min_items,
1292            "maxItems": max_items,
1293        }),
1294    };
1295    let object = schema.as_object_mut().expect("an object schema");
1296    object.retain(|_, value| !value.is_null());
1297    if let Some(title) = &param.title {
1298        object.insert("title".to_owned(), json!(title));
1299    }
1300    if let Some(description) = &param.description {
1301        object.insert("description".to_owned(), json!(description));
1302    }
1303    if let Some(default) = &param.default {
1304        object.insert("default".to_owned(), default.clone());
1305    }
1306    schema
1307}
1308
1309/// Problems with a template, and with `data` for it when given: its header and parameters, the
1310/// parameters its body names, literal content a template leaves to its data or theme, and
1311/// whether it binds to a spec that parses. Without data it binds to sample data.
1312#[must_use]
1313pub fn lint(template: &Value, data: Option<&Value>, templates: &[Value]) -> Vec<Issue> {
1314    let mut issues = Vec::new();
1315    let fail = |issues: &mut Vec<Issue>, code, problem: ComposeError| {
1316        issues.push(Issue {
1317            path: problem.path,
1318            code,
1319            message: problem.message,
1320            severity: Severity::Error,
1321        });
1322    };
1323    let header = match header(template) {
1324        Ok(Some(header)) => header,
1325        Ok(None) => {
1326            fail(
1327                &mut issues,
1328                "header",
1329                error("template", "a template has a `template` header"),
1330            );
1331            return issues;
1332        }
1333        Err(problem) => {
1334            fail(&mut issues, "header", problem);
1335            return issues;
1336        }
1337    };
1338    let declared = match params(template.get("params"), "template.params") {
1339        Ok(params) => params,
1340        Err(problem) => {
1341            fail(&mut issues, "params", problem);
1342            return issues;
1343        }
1344    };
1345    let body = match header.kind {
1346        Kind::Node => template.get("node").cloned().unwrap_or(Value::Null),
1347        Kind::Video => {
1348            let mut body = template.as_object().cloned().unwrap_or_default();
1349            body.remove("template");
1350            body.remove("params");
1351            Value::Object(body)
1352        }
1353    };
1354    let mut used = BTreeSet::new();
1355    let mut scope = declared
1356        .iter()
1357        .map(|param| param.name.clone())
1358        .collect::<BTreeSet<_>>();
1359    names(
1360        &body,
1361        &mut scope,
1362        &mut used,
1363        "template",
1364        &mut issues,
1365        &declared,
1366    );
1367    for param in &declared {
1368        if !used.contains(&param.name) {
1369            issues.push(Issue {
1370                path: format!("template.params.{}", param.name),
1371                code: "unused-param",
1372                message: format!("{} is declared but never used", param.name),
1373                severity: Severity::Warning,
1374            });
1375        }
1376    }
1377    content(&body, None, "template", &mut issues);
1378    let sample = match data.cloned().map_or_else(|| least_data(&declared), Ok) {
1379        Ok(sample) => sample,
1380        Err(problem) => {
1381            fail(&mut issues, "bind", problem);
1382            return issues;
1383        }
1384    };
1385    let options = BindOptions {
1386        theme: None,
1387        templates: templates.to_vec(),
1388    };
1389    match bind(template, &sample, &options) {
1390        Err(problem) => fail(&mut issues, "bind", problem),
1391        Ok(bound) => {
1392            let parsed = match header.kind {
1393                Kind::Video => crate::parse_spec(&bound.to_string()).map(|_| ()),
1394                Kind::Node => crate::de::from_value::<crate::spec::Node>(bound)
1395                    .map(|_| ())
1396                    .map_err(|located| {
1397                        error(&crate::de::join("node", &located.path), located.message)
1398                    }),
1399            };
1400            if let Err(problem) = parsed {
1401                fail(&mut issues, "spec", problem);
1402            }
1403        }
1404    }
1405    issues
1406}
1407
1408/// Notes the parameters `value` names, flagging names no parameter or alias has and directives
1409/// on parameters of the wrong type.
1410fn names(
1411    value: &Value,
1412    scope: &mut BTreeSet<String>,
1413    used: &mut BTreeSet<String>,
1414    path: &str,
1415    issues: &mut Vec<Issue>,
1416    declared: &[Param],
1417) {
1418    let mut note = |name: &str, path: &str, want: Option<&str>, issues: &mut Vec<Issue>| {
1419        let root = name.split('.').next().unwrap_or(name);
1420        used.insert(root.to_owned());
1421        if !scope.contains(root) {
1422            issues.push(Issue {
1423                path: path.to_owned(),
1424                code: "unknown-param",
1425                message: format!("{name} is not a parameter"),
1426                severity: Severity::Error,
1427            });
1428        } else if let Some(want) = want
1429            && let Some(param) = declared.iter().find(|param| param.name == root)
1430            && !name.contains('.')
1431            && param.kind.name() != want
1432        {
1433            issues.push(Issue {
1434                path: path.to_owned(),
1435                code: "param-type",
1436                message: format!("{name} is a {} parameter, not a {want}", param.kind.name()),
1437                severity: Severity::Error,
1438            });
1439        }
1440    };
1441    match value {
1442        Value::Object(object) => {
1443            for (directive, want) in [
1444                ("$param", None),
1445                ("$if", None),
1446                ("$switch", Some("enum")),
1447                ("$each", Some("list")),
1448            ] {
1449                if let Some(name) = object.get(directive).and_then(Value::as_str) {
1450                    note(name, path, want, issues);
1451                }
1452            }
1453            let alias = object
1454                .get("$each")
1455                .and(object.get("as"))
1456                .and_then(Value::as_str)
1457                .map(str::to_owned);
1458            let added = alias
1459                .as_ref()
1460                .is_some_and(|alias| scope.insert(alias.clone()));
1461            for (field, inner) in object {
1462                if field.starts_with('$') && field != "$theme" {
1463                    continue;
1464                }
1465                names(
1466                    inner,
1467                    scope,
1468                    used,
1469                    &format!("{path}.{field}"),
1470                    issues,
1471                    declared,
1472                );
1473            }
1474            if let Some(node) = object.get("node").filter(|_| alias.is_some()) {
1475                names(node, scope, used, &format!("{path}.node"), issues, declared);
1476            }
1477            if added && let Some(alias) = alias {
1478                scope.remove(&alias);
1479            }
1480        }
1481        Value::Array(items) => {
1482            for (index, item) in items.iter().enumerate() {
1483                names(
1484                    item,
1485                    scope,
1486                    used,
1487                    &format!("{path}[{index}]"),
1488                    issues,
1489                    declared,
1490                );
1491            }
1492        }
1493        Value::String(text) => {
1494            let mut rest = text.as_str();
1495            while let Some(start) = rest.find("{{") {
1496                let after = &rest[start + 2..];
1497                if let Some(stripped) = after.strip_prefix("{{") {
1498                    rest = stripped;
1499                    continue;
1500                }
1501                let Some(end) = after.find("}}") else { break };
1502                note(after[..end].trim(), path, None, issues);
1503                rest = &after[end + 2..];
1504            }
1505        }
1506        _ => {}
1507    }
1508}
1509
1510/// Flags literal files, colors and copy, which a template takes from its data and theme.
1511fn content(value: &Value, key: Option<&str>, path: &str, issues: &mut Vec<Issue>) {
1512    let mut flag = |code, message: String| {
1513        issues.push(Issue {
1514            path: path.to_owned(),
1515            code,
1516            message,
1517            severity: Severity::Error,
1518        });
1519    };
1520    match value {
1521        Value::Object(object) => {
1522            if object.contains_key("$param") || object.contains_key("$theme") {
1523                return;
1524            }
1525            if let Ok(color) = serde_json::from_value::<alpha2_model::Rgba>(value.clone())
1526                && object.contains_key("red")
1527                && !structural(color)
1528            {
1529                flag(
1530                    "literal-color",
1531                    "a template takes colors from its theme or data".to_owned(),
1532                );
1533                return;
1534            }
1535            for (field, inner) in object {
1536                content(inner, Some(field), &format!("{path}.{field}"), issues);
1537            }
1538        }
1539        Value::Array(items) => {
1540            for (index, item) in items.iter().enumerate() {
1541                content(item, key, &format!("{path}[{index}]"), issues);
1542            }
1543        }
1544        Value::String(text) => {
1545            let key = key.unwrap_or_default();
1546            if FILE_KEYS.contains(&key) {
1547                flag(
1548                    "literal-media",
1549                    format!("a template takes files from its data, not \"{text}\""),
1550                );
1551            } else if text.starts_with('#')
1552                && let Some(color) = alpha2_model::Rgba::from_hex(text)
1553                && !structural(color)
1554            {
1555                flag(
1556                    "literal-color",
1557                    format!("a template takes colors from its theme or data, not {text}"),
1558                );
1559            } else if TEXT_KEYS.contains(&key) && literal_copy(text) {
1560                flag(
1561                    "literal-text",
1562                    format!("a template takes its words from its data, not \"{text}\""),
1563                );
1564            }
1565        }
1566        _ => {}
1567    }
1568}
1569
1570/// Whether `color` is structural: transparent, or black or white at any opacity.
1571#[allow(clippy::float_cmp)]
1572fn structural(color: alpha2_model::Rgba) -> bool {
1573    color.alpha == 0.0
1574        || [color.red, color.green, color.blue]
1575            .iter()
1576            .all(|part| *part == 0.0)
1577        || [color.red, color.green, color.blue]
1578            .iter()
1579            .all(|part| *part == 1.0)
1580}
1581
1582/// Whether `text`, its `{{...}}` taken out, still holds a letter or digit.
1583fn literal_copy(text: &str) -> bool {
1584    let mut rest = text;
1585    let mut plain = String::new();
1586    while let Some(start) = rest.find("{{") {
1587        plain.push_str(&rest[..start]);
1588        match rest[start + 2..].find("}}") {
1589            Some(end) => rest = &rest[start + 2 + end + 2..],
1590            None => {
1591                rest = "";
1592            }
1593        }
1594    }
1595    plain.push_str(rest);
1596    plain.chars().any(char::is_alphanumeric)
1597}
1598
1599/// [`sample_data`] for `params`, or why the least data they take is more than a binding makes.
1600fn least_data(params: &[Param]) -> Result<Value, ComposeError> {
1601    sample_data(params, &mut { MAX_BOUND_VALUES }).ok_or_else(|| {
1602        error(
1603            "template.params",
1604            format!("the least data the parameters take makes more than {MAX_BOUND_VALUES} values"),
1605        )
1606    })
1607}
1608
1609/// Data that satisfies `params`, for checking a template without data of its own, made only
1610/// while it stays within [`MAX_BOUND_VALUES`] (`room` is what is left).
1611fn sample_data(params: &[Param], room: &mut usize) -> Option<Value> {
1612    let mut data = Map::new();
1613    for param in params {
1614        if param.default.is_some() || !param.required {
1615            continue;
1616        }
1617        *room = room.checked_sub(1)?;
1618        let value = match &param.kind {
1619            ParamKind::Text {
1620                min_chars,
1621                max_chars,
1622                ..
1623            } => {
1624                let least = min_chars.unwrap_or(1).max(1);
1625                let length = 4.clamp(least, max_chars.unwrap_or(u64::MAX).max(least));
1626                let length = usize::try_from(length).unwrap_or(4);
1627                *room = room.checked_sub(length / STRING_BYTES_PER_VALUE)?;
1628                json!("x".repeat(length))
1629            }
1630            ParamKind::Media { accept, .. } => {
1631                json!(if accept.iter().any(|kind| kind == "video") {
1632                    "sample.mp4"
1633                } else {
1634                    "sample.png"
1635                })
1636            }
1637            ParamKind::Audio { .. } => json!("sample.m4a"),
1638            ParamKind::Number { min, max } => json!(min.or(*max).unwrap_or(0.0)),
1639            ParamKind::Bool => json!(false),
1640            ParamKind::Enum(values) => json!(values[0]),
1641            ParamKind::Color => json!("#808080"),
1642            ParamKind::Font => json!("sans-serif"),
1643            ParamKind::Node => json!({"type": "color"}),
1644            ParamKind::List {
1645                min_items, item, ..
1646            } => {
1647                let count = usize::try_from(min_items.unwrap_or(1).max(1)).unwrap_or(1);
1648                let mut items = Vec::with_capacity(count.min(*room));
1649                for _ in 0..count {
1650                    *room = room.checked_sub(1)?;
1651                    items.push(sample_data(item, room)?);
1652                }
1653                Value::Array(items)
1654            }
1655        };
1656        data.insert(param.name.clone(), value);
1657    }
1658    Some(Value::Object(data))
1659}
1660
1661#[cfg(test)]
1662mod tests;