Skip to main content

flm_core/stdlib/features/compose/
mod.rs

1//! The feature `compose`: the stages that assemble each output's entry artifact from the
2//! output's regions through a **compose template**, a text with named places for those
3//! regions, and the service slots of the template engines and of the compose templates.
4//!
5//! An output region is one named part of an output's entry artifact (the document's
6//! content, each piece placed beside it, and on HTML the stylesheets, the scripts, the
7//! title and the language), which the backend writes once into the table
8//! `flm.output.<backend>.regions` ([`Regions`]). The entry artifact is the artifact that
9//! represents the output as a whole: the HTML page, the printed text, the recomposed LaTeX
10//! document ([`ArtifactSet`]). The backend's final stage assembles the entry artifact
11//! from those regions in a layout of the backend's own ([`crate::core::region`]). The
12//! feature `compose` is a second way to assemble them: through the compose template that
13//! the settings choose, so that a program chooses what surrounds the document's content.
14//!
15//! # A host registers the feature
16//!
17//! The feature is not among the standard features that
18//! [`stdlib::add_features`](crate::stdlib::add_features) adds. The
19//! composer of an output provides the same capability as the backend's final stage, and
20//! a plan chooses between two stages that provide one capability only by a stage the
21//! plan request prefers or by a capability marked as the default; with neither, the plan
22//! fails ([`PlanError::Contested`](crate::core::plan::PlanError::Contested)). So a host
23//! that registers the feature also prefers the composer of each output it renders
24//! ([`stage_name`]; [`Overrides::prefer`](crate::core::plan::Overrides::prefer)). A
25//! registry without the feature has one stage per output that assembles the entry
26//! artifact, the backend's final stage. Where a host registers the feature but the
27//! settings switch it off, the host leaves it out of the registry, and the backend's
28//! final stage assembles each output.
29//!
30//! # Template engines and compose templates
31//!
32//! The feature declares two service slots, to which any feature of any package may
33//! contribute. A service slot is the declaration, by the feature that owns an
34//! interaction, of a dotted name, the type of the values the slot takes and its arity
35//! ([`crate::core::services`]). A feature of another package contributes to them as a
36//! peer ([`FeatureBuilder::peer_slot`]), so that its registry still builds where
37//! `compose` is switched off.
38//!
39//! - [`ENGINES_SLOT`] (`flm.compose.engines`) takes the **template engines**, each a
40//!   [`TemplateEngine`] with a name. `compose` contributes `content-only`, which places
41//!   the content and the pieces with nothing around them ([`engines`]); a host
42//!   contributes the engines of the template languages it reads.
43//! - [`TEMPLATES_SLOT`] (`flm.compose.templates`) takes the **compose templates**, each a
44//!   [`Template`]: its name, the output it serves, its engine, its text, the pieces it
45//!   accepts and those it requires, and its own settings with their defaults.
46//!   [`Template::from_data`] makes one from a description given as data, whose keys
47//!   `name` and `output` give the compose template's name and the output it serves, and
48//!   whose key `main` gives the path of the file that holds the compose template's text,
49//!   relative to the folder of the description; without `main`, the text is empty.
50//!   `compose` contributes none.
51//!
52//! # The settings of a compose template
53//!
54//! A compose template's own settings are written under the render option
55//! `template_config`, at `template_config.OUTPUT.NAME` ([`ComposeOptions`]). The feature
56//! lets another feature declare the schema of each of these entries
57//! ([`SettingsDecl::open_entries`], [`EntryDecl`](crate::core::settings::EntryDecl)): the
58//! feature that contributes a compose template declares its settings
59//! ([`declare_settings`]), from the JSON Schema of the compose template
60//! ([`Template::settings`]), each of whose `properties` is one setting with its type, its
61//! description, its default and its marks. A source of settings that writes one setting
62//! of a compose template leaves the others as the lower sources write them, and a key that
63//! the schema lacks is left out with a warning; the defaults are the compose template's
64//! ([`Template::config`]).
65//!
66//! # The stage of each output
67//!
68//! The feature registers one stage per output made of output regions, that is, per
69//! output for which a backend contributes a regions output ([`RegionsOutput`]) to the
70//! service slot `flm.output.regions` ([`REGIONS_SLOT`]; [`served_output`]). A regions
71//! output is a backend's statement that its output is made of output regions: which table
72//! holds them and which capability its final stage provides. The stages are registered in
73//! the feature's second round of registration, a [`Finalizer`] that runs once every
74//! feature has registered, so every backend has contributed to that service slot by then.
75//!
76//! The stage of an output, `flm.compose.<output>` ([`stage_name`]), is called the
77//! *composer* in this module. It writes the output's artifact set into the same table as
78//! the backend's final stage and provides the same capability, so a plan can schedule
79//! either one; the host prefers the composer (see [above](self#a-host-registers-the-feature)).
80//!
81//! The composer reads the output's regions and the files that the output's stages write
82//! beside the entry artifact (the style file of the recomposed LaTeX, the copies of
83//! images), applies the compose template that the render option [`ComposeOptions`]
84//! chooses for the output ([`chosen_template`]), and writes the entry artifact and those
85//! files as the output's artifact set ([`ArtifactSet::insert_entry_with`]). It reports a
86//! problem as the Error [`TemplateFailed`]; the output is then not made. It reports each
87//! warning of the template engine as the Warning [`TemplateWarning`]; the output is still
88//! made.
89//!
90//! # What a compose template reads
91//!
92//! | Name | What it is |
93//! |---|---|
94//! | `regions` | every output region, by name, as text: `content`; each piece's name; on HTML `styles`, `scripts`, `title` (the words of the page's title, escaped for HTML: the words of the document's title piece, else the title that the render option `html.title` gives) and `lang` (the language tag, present only when the render option `html.lang` gives one); on the recomposed LaTeX `style-package`, when the output has a style file |
95//! | `pieces` | the regions that are pieces, by name, in the order of the output's regions; each has `text`, `words` (its displayed characters as plain text) and `place` (`before-content` or `after-content`) |
96//! | `metadata` | the document's metadata ([`DocMeta`]): `title`, `author`, `date`, and every other entry the program gives, each value as it is given. `author` is a list with one map per author, a name alone included: `name`, `affiliation` (a list), `email` (where the author has one), `note` (a list) and the author's other keys. The title, the date and an author's name, affiliations and notes are the texts the author wrote, FLM source and not plain text (`A \emph{fine} paper`); a compose template that shows them uses the pieces instead: `pieces["flm.metadata.title"].text` for the HTML, or `.words` for plain words |
97//! | `config` | the compose template's own settings: its defaults, with the values that the render option `template_config` gives for it on the output written over them key by key |
98//! | `artifacts` | the path of each file the compose template ships, by the file's name ([below](self#files-a-compose-template-ships)): `artifacts.style` gives `paper-style.css`; for a folder it ships, the folder's path, with no trailing slash: `artifacts.icons` gives `paper-icons`, and a page writes `{{ artifacts.icons }}/check.svg` |
99//!
100//! A compose template that refers to a value that nothing provides cannot be applied: the
101//! value is not taken as an empty text.
102//!
103//! # Files a compose template ships
104//!
105//! A compose template may ship files of its own, written beside the entry artifact: a
106//! stylesheet, a script, a logo. It ships them in two ways: the files its description
107//! lists, and the files its template engine ships while it applies it
108//! ([below](self#a-file-shipped-while-the-template-is-applied)).
109//!
110//! The files of the description ([`Template::artifacts`], [`TemplateArtifact`]; the key
111//! `artifacts` of its description, [`Template::from_data`]) each have a name, and the
112//! identity of each is `compose:<name>`. The composer asks the program's naming of files (the
113//! service slot `flm.artifacts.namer`, [`ArtifactNamer`]) for the path of each, and gives
114//! the paths to the compose template as the value `artifacts`. A path is relative to the
115//! folder where the program writes the output's files, which is where the entry file lies
116//! under a host's usual naming. A file marked to be applied (the field `apply` of
117//! [`TemplateArtifact::File`]) is applied as a template of the same template engine
118//! ([`TemplateEngine::render_text`]), with the context of the entry artifact, its value
119//! `html` set to whether the file's media type is `text/html`; the result is the file's
120//! content. The composer then adds each file to the output's artifact set, with its media
121//! type and extension, and the entry artifact links to each ([`Artifact::refs`]). A
122//! compose template that ships files cannot be applied where no package in use provides a
123//! naming of files. The composer takes the list from the template engine
124//! ([`TemplateEngine::artifacts`]), once per application and before naming the files.
125//! By default it is the compose template's own list; an engine whose compose templates
126//! choose their files when they are applied gives them there.
127//!
128//! A compose template may also ship a whole folder as one file of this list (the key
129//! `dir` of its description in place of `file`; [`TemplateArtifact::Folder`]): every
130//! file under the folder, at any depth, by its path relative to the folder. The composer
131//! asks the naming of files for the folder's path (a path with no extension,
132//! [`ArtifactRef::folder`]), gives that path to the compose template, with no trailing
133//! slash, and adds a folder artifact ([`Artifact::folder`]) to the output's artifact set;
134//! the program writes each of its files under that folder with its own path. A folder is
135//! never applied as a template, and its files' media types come from their extensions.
136//!
137//! ## A file shipped while the template is applied
138//!
139//! A template engine whose language ships a file, where the compose template names it as
140//! it is applied, hands the file to the composer through the handle [`TemplateShipper`]
141//! that it receives in [`TemplateEngine::render`] and [`TemplateEngine::render_text`]
142//! ([`ShippedFile`]: a stem, an extension, a media type and the bytes), and writes the
143//! path that the handle returns. The composer makes one handle per application, which
144//! serves every call of that application. A file's identity is `compose:<stem>-<digest>`:
145//! its stem, every character other than an ASCII letter, a digit, `-` and `_` written `_`,
146//! and eight hexadecimal digits of a digest of its bytes and its media type, so that the
147//! same file shipped twice is one file, under the one path. Its path is the naming of
148//! files' path for that identity, its media type and its extension. Once the compose
149//! template is applied, the composer adds the shipped files to the output's artifact set,
150//! after the files of the description, in the order in which they were first shipped, and
151//! the entry artifact links to each. Where no package in use provides a naming of files,
152//! the handle refuses the file, and the compose template cannot be applied.
153//!
154//! The template engine also reports a warning through the handle
155//! ([`TemplateShipper::warn`]), which it also receives in [`TemplateEngine::artifacts`],
156//! for example the use of a kept copy of a downloaded file
157//! that could not be downloaded again. The composer reports each distinct warning once
158//! per application as the Warning [`TemplateWarning`], whether the compose template is
159//! applied or not.
160//!
161//! # Files a compose template includes
162//!
163//! A compose template's text, and the text of a file it ships and applies, may include
164//! other files, as its template engine's language provides: a file applied as a template
165//! of the same engine, with the same context, or a file whose text is written as it is.
166//! Each text carries its *place*: the file it was read from, given as a qualified path, a
167//! path with a root such as `ext+NAME:templates/html/page/page.html` or
168//! `std:templates/html/simple/simple.html` ([`Template::source`], the field `source` of
169//! [`TemplateArtifact::File`]). The template engine reads an included file when the
170//! compose template is applied, so that its name may be computed and need not be listed
171//! ahead; a path written without a root is read beside the file of the text that writes it.
172//! This crate reads no file of its own: the template engine reads through the program
173//! that provides it, which records each read.
174//!
175//! # On HTML: one element per region, and the composer's table
176//!
177//! On HTML, the composer writes the content and each piece inside a `<div>` element whose
178//! identifier is derived from the region's name ([`region_id`]: `flm-region-content`,
179//! `flm-region-flm.metadata.title`), before the compose template places it, whichever
180//! compose template is used. The composer also writes the table [`HTML_REGIONS`]
181//! (`flm.compose.html.regions`, a [`ComposedRegions`]), which holds:
182//!
183//! - the HTML that the page holds under the identifier of the content and of each piece;
184//! - the words of the page's title (the region `title`);
185//! - the rest of the page, everything outside those regions (the field `skeleton`): the
186//!   page with exactly what the table holds left out, and everything else kept, namely the
187//!   stylesheets, the scripts, the language, the compose template's own markup, and the
188//!   words of each piece wherever the compose template writes them.
189//!
190//! The table holds what a page can bring up to date by itself: an element found by its
191//! identifier, and the page's title, which has its place in every page. The words of a
192//! piece have no such place, so a change of them is a change of the rest of the page.
193//! The regions in the table and the rest of the page together make up the whole page, so
194//! two builds of one document that differ anywhere differ either in the rest of the page
195//! or in one entry of the table. A live preview can compare two builds this way, to tell
196//! a change of one region, which it applies in place, from a change of the page.
197//!
198//! # Which pieces a render builds
199//!
200//! A piece is a document-level value that a backend places before or after the document's
201//! content, such as the title, the list of footnotes or the bibliography ([`Piece`]). The
202//! pieces that a compose template accepts are the pieces that a render request places on
203//! the backend of the compose template's output: the host sets the library's selection of
204//! pieces for that backend from the chosen compose template ([`accepted_pieces`],
205//! [`select_pieces`]), so that a piece that the compose template does not place is never
206//! built. The pieces that the compose template *requires* ([`Template::requires`]) are
207//! placed although a piece may be declared off by default: [`select_pieces`] includes
208//! them. When the plan is built, the composer declares that it reads each required piece;
209//! a plan in which no stage provides a required piece therefore fails to build, with an
210//! error that gives the piece's name.
211//!
212//! # Map of the items
213//!
214//! - [`ComposeFeature`], [`FEATURE`]: the feature.
215//! - [`ENGINES_SLOT`], [`TemplateEngine`], [`engines`] ([`ContentOnlyEngine`]): the
216//!   template engines.
217//! - [`TEMPLATES_SLOT`], [`Template`], [`Template::from_data`], [`Accepts`],
218//!   [`Delimiters`], [`TemplateArtifact`]: the compose templates.
219//! - [`declare_settings`]: the settings of the compose templates a feature contributes.
220//! - [`TemplateContext`], [`PieceValue`]: what a template engine is given.
221//! - [`TemplateShipper`], [`ShippedFile`]: a file a template engine ships, and a warning it
222//!   reports, while it applies a compose template.
223//! - [`ComposeOptions`], [`TemplateChoice`], [`DEFAULT_TEMPLATE`], [`chosen_template`]:
224//!   choosing a compose template.
225//! - [`served_output`], [`stage_name`], [`accepted_pieces`], [`select_pieces`]: what the
226//!   host calls when it prepares the plan of an output.
227//! - [`HTML_REGIONS`], [`ComposedRegions`], [`ComposedRegion`], [`ComposedKind`],
228//!   [`region_id`], [`REGION_ID_PREFIX`]: the composer's table on HTML.
229//! - [`TemplateFailed`], [`TemplateWarning`]: the conditions of a compose template that
230//!   cannot be applied and of a warning of its template engine.
231
232pub mod engines;
233
234use std::collections::BTreeMap;
235use std::fmt;
236use std::hash::{Hash, Hasher};
237use std::sync::{Arc, Mutex, PoisonError};
238
239use crate::core::artifact::{
240    Artifact, ArtifactId, ArtifactNamer, ArtifactRef, ArtifactSet, NamingScope, RelPath, digest_name, media_type_of,
241    name_safe,
242};
243use crate::core::data::store::StageOut;
244use crate::core::data::table::{PieceClass, ProjectCx, Table, TableHandle, TableName};
245use crate::core::piece::{Piece, PieceDecl};
246use crate::core::plan::PlanCx;
247use crate::core::region::{self, Region, Regions, RegionsOutput};
248use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, Finalizer, FlmFeature, FlmRegistry};
249use crate::core::run::StageCx;
250use crate::core::services::Arity;
251use crate::core::settings::{Mark, SettingsDecl, SettingsError, SettingsErrorKind, rewrite_marked};
252use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
253use crate::lang::{FlmOrigin, FlmSpan};
254use crate::model::digest::Fnv1a64;
255use crate::model::names::Name;
256use crate::model::options::{Bind, OptionKey, hash_value};
257use crate::stdlib::backends::pieces::{self as core_pieces, PiecesRenderOptions};
258use crate::stdlib::backends::html;
259use crate::stdlib::backends::html::escape::escape_attr_into;
260use crate::stdlib::backends::lowering::{NAMER_SLOT, REGIONS_SLOT};
261use crate::stdlib::features::metadata::{
262    AFFILIATION_KEY, AUTHOR_KEY, DocMeta, EMAIL_KEY, MetaAuthor, MetaText, NAME_KEY, NOTE_KEY,
263};
264use crate::techy::error::{Diagnostic, DiagnosticInfo};
265use crate::techy::serialize::SerialValue;
266use crate::techy::source::{Source, SourceSpan};
267use serde_json::{Map, Value};
268
269pub use engines::{CONTENT_ONLY, ContentOnlyEngine};
270
271/// The name under which the feature is registered, `compose`.
272pub const FEATURE: &str = "compose";
273
274/// The name of the service slot `flm.compose.engines`, which takes any number of
275/// template engines ([`TemplateEngine`]), each with a name. Where several engines have
276/// the name a template gives, the engine of the feature placed last in the feature order
277/// applies.
278pub const ENGINES_SLOT: &str = "flm.compose.engines";
279
280/// The name of the service slot `flm.compose.templates`, which takes any number of compose
281/// templates ([`Template`]), each with a name and the output it serves.
282pub const TEMPLATES_SLOT: &str = "flm.compose.templates";
283
284/// The name of the compose template that a render uses when the settings choose none,
285/// `simple`. The feature ships no compose template of that name: a host contributes the
286/// compose templates it offers, and where none of them serves an output under the chosen
287/// name, the composer of that output reports [`TemplateFailed`].
288pub const DEFAULT_TEMPLATE: &str = "simple";
289
290/// The prefix of the identifier of the element that holds a region on HTML, `flm-region-`:
291/// see [`region_id`].
292pub const REGION_ID_PREFIX: &str = "flm-region-";
293
294/// The typed name of the composer's table on HTML, `flm.compose.html.regions`
295/// ([`ComposedRegions`]): the HTML that the page holds under each region's identifier, the
296/// words of the page's title, and the rest of the page. See the [module
297/// documentation](self#on-html-one-element-per-region-and-the-composers-table).
298pub const HTML_REGIONS: TableName<ComposedRegions> = TableName::new("flm.compose.html.regions");
299
300/// Condition `flm.compose.template-failed` (Error): the chosen compose template cannot be
301/// applied. The stage `flm.compose.<output>` reports it when the settings that choose the
302/// compose template cannot be read, when no compose template of the chosen name serves
303/// the output or more than one does, when its template engine is not registered,
304/// when the output's regions, the files written beside the entry artifact or the
305/// document's metadata cannot be read, when its template engine cannot give the files it
306/// ships ([`TemplateEngine::artifacts`]), when it ships files and no package in use
307/// provides a naming of files, when its text or the text of a file it applies does not
308/// compile or refers to a value that nothing provides, or when the output's artifact set
309/// cannot be written. The output is then not made, with one exception: when a file that
310/// the compose template ships cannot be added to the artifact set after the entry artifact
311/// was written, the output is made without that file.
312#[derive(Debug, Clone, PartialEq, Eq)]
313pub struct TemplateFailed {
314    /// The compose template's name; `None` when the settings that choose it cannot be read.
315    pub template: Option<String>,
316    /// The name of the output it was applied for.
317    pub output: String,
318    /// What went wrong, as the template engine, the search for the compose template or the
319    /// failed read states it.
320    pub detail: String,
321}
322
323impl fmt::Display for TemplateFailed {
324    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325        match &self.template {
326            Some(template) => write!(
327                f,
328                "the compose template `{template}` for the output `{}` cannot be applied: {}",
329                self.output, self.detail
330            ),
331            None => write!(f, "the compose template for the output `{}` cannot be chosen: {}", self.output, self.detail),
332        }
333    }
334}
335
336impl DiagnosticInfo for TemplateFailed {
337    const IDENTIFIER: &'static str = "flm.compose.template-failed";
338}
339
340/// Condition `flm.compose.template-warning` (Warning): the template engine reported a
341/// warning while it applied the chosen compose template ([`TemplateShipper::warn`]). The
342/// stage `flm.compose.<output>` reports each distinct warning once per application, in
343/// the order first given; the output is made.
344#[derive(Debug, Clone, PartialEq, Eq)]
345pub struct TemplateWarning {
346    /// The compose template's name.
347    pub template: String,
348    /// The name of the output it was applied for.
349    pub output: String,
350    /// What is wrong, as the template engine states it.
351    pub detail: String,
352}
353
354impl fmt::Display for TemplateWarning {
355    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356        write!(f, "{} (compose template ‘{}’ for the output ‘{}’)", self.detail, self.template, self.output)
357    }
358}
359
360impl DiagnosticInfo for TemplateWarning {
361    const IDENTIFIER: &'static str = "flm.compose.template-warning";
362}
363
364// --- the outputs the composer serves ---------------------------------------------------------
365
366/// Returns what a backend states about the output `output` of `registry` when that output
367/// is made of output regions ([`RegionsOutput`], contributed to the service slot
368/// [`REGIONS_SLOT`]), and `None` otherwise. The composer serves exactly those outputs.
369///
370/// The output is matched by the table of its artifact set: an output of another name
371/// whose artifact set is written to the table of such an output is served as that output,
372/// with that output's compose templates. Where several backends state one table, the
373/// statement of the feature placed last in the feature order applies.
374pub fn served_output<'r>(registry: &'r FlmRegistry, output: &str) -> Option<&'r RegionsOutput> {
375    let table = &registry.output(output)?.def.table;
376    registry
377        .services()
378        .services_by_precedence_named::<RegionsOutput>(REGIONS_SLOT)
379        .find(|served| &served.document == table)
380}
381
382/// Returns whether `output` is written by the HTML backend: a value that a compose template
383/// writes is then escaped for HTML, and every region placed carries its name.
384fn is_html(output: &RegionsOutput) -> bool {
385    output.backend.as_str() == html::BACKEND
386}
387
388/// Returns the name of the composer's stage for the output `output`,
389/// `flm.compose.<output>`.
390pub fn stage_name(output: &str) -> String {
391    format!("flm.compose.{output}")
392}
393
394/// Returns the identifier of the element that holds the region `name` on HTML:
395/// [`REGION_ID_PREFIX`] followed by the name as it is written, dots included (a `.` is
396/// allowed in an HTML identifier). Two distinct names therefore never share an
397/// identifier, and the name is read back from the identifier by removing the prefix. The
398/// identifier is derived from the name alone, so adding a region never changes the
399/// identifier of another.
400///
401/// # Examples
402///
403/// ```
404/// use flm_core::stdlib::features::compose::region_id;
405///
406/// assert_eq!(region_id("content"), "flm-region-content");
407/// assert_eq!(region_id("flm.metadata.title"), "flm-region-flm.metadata.title");
408/// assert_ne!(region_id("a.b-c"), region_id("a-b.c"));
409/// ```
410pub fn region_id(name: &str) -> String {
411    format!("{REGION_ID_PREFIX}{name}")
412}
413
414/// Returns the element that holds a region on HTML, written around `inside`: a `<div>`
415/// whose `id` is [`region_id`] of `name`, escaped as an attribute value.
416fn region_element(name: &str, inside: &str) -> String {
417    let mut id = String::new();
418    escape_attr_into(&mut id, &region_id(name));
419    if inside.is_empty() {
420        format!("<div id=\"{id}\"></div>")
421    } else {
422        format!("<div id=\"{id}\">\n{inside}\n</div>")
423    }
424}
425
426// --- templates and engines ---------------------------------------------------------------------
427
428/// Which pieces a compose template accepts: every piece, or the pieces listed.
429#[derive(Debug, Clone, PartialEq, Eq)]
430pub enum Accepts {
431    /// Every piece that the registry declares.
432    All,
433    /// The pieces listed, and no other.
434    Only(Vec<Name>),
435}
436
437/// The three pairs of delimiters of a compose template written in a Jinja-like template
438/// language (such as the language of a host's `minijinja` engine), for a compose template
439/// whose output itself uses the usual ones (`{% %}`, `{{ }}`, `{# #}`), such as LaTeX. A
440/// template engine that reads no delimiters ignores them.
441#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
442#[serde(deny_unknown_fields)]
443pub struct Delimiters {
444    /// The start and the end of a statement.
445    pub block: (String, String),
446    /// The start and the end of a place for a value.
447    pub variable: (String, String),
448    /// The start and the end of a comment.
449    pub comment: (String, String),
450}
451
452/// A compose template: a text with named places for an output's regions, applied by a
453/// template engine (see the [module documentation](self)).
454///
455/// A feature contributes one to [`TEMPLATES_SLOT`]; [`Template::from_data`] makes one from
456/// a description given as data and the readers of the files it gives.
457#[derive(Debug, Clone, PartialEq)]
458pub struct Template {
459    /// The compose template's name, which the setting `compose.template` gives.
460    /// [`Template::from_data`] reads it from the key `name` of the description.
461    pub name: String,
462    /// The package that ships the compose template, as messages show it (for instance the
463    /// name of a compiled package, or the identity of an extension's package,
464    /// `<identity>#<package>`). A
465    /// problem with two compose templates of the same name gives the packages that ship
466    /// them.
467    pub package: String,
468    /// The name of the output it serves. [`Template::from_data`] reads it from the key
469    /// `output` of the description.
470    pub output: String,
471    /// The name of the template engine that applies it.
472    pub engine: String,
473    /// Its text, in the template engine's language; empty for a template engine that reads
474    /// no text (`content-only`). [`Template::from_data`] reads it from the file that the key
475    /// `main` of the description gives, and leaves it empty without `main`.
476    pub text: String,
477    /// The place of its text: the qualified path of the file that the text was read from
478    /// (`ext+NAME:templates/html/page/page.html`, `std:templates/html/simple/simple.html`;
479    /// see the [module documentation](self#files-a-compose-template-includes)). A template
480    /// engine reads a path written without a root beside that file. `None` for a text that
481    /// no file holds: a compose template made in code, or a description without `main`.
482    pub source: Option<String>,
483    /// The pieces it accepts: the pieces that a render request places on the backend of
484    /// the compose template's output ([`accepted_pieces`]).
485    pub accepts: Accepts,
486    /// The pieces it requires: each is placed although it may be declared off by default
487    /// ([`select_pieces`]), and a plan in which no stage provides one of them fails.
488    pub requires: Vec<Name>,
489    /// Its own settings, with their defaults, which the render option `template_config`
490    /// can change ([`ComposeOptions::template_config`]). [`Template::from_data`] reads them
491    /// from the `default` of each setting of [`settings`](Template::settings). For a
492    /// compose template written as a module of an extension, they are the defaults that
493    /// the module's `describe` returns.
494    pub config: Map<String, Value>,
495    /// The JSON Schema of its own settings: an object schema, each of whose `properties`
496    /// is one setting with its type, its `description`, its `default` and its marks
497    /// ([`Mark`]). The feature that contributes the compose template declares it as the
498    /// entry `template_config.OUTPUT.NAME` of the feature `compose`
499    /// ([`declare_settings`]).
500    ///
501    /// - [`Template::from_data`] reads it from the key `settings` of the description; a
502    ///   description without that key gives a schema with no setting.
503    /// - For a compose template written as a module of an extension, it is the schema
504    ///   that the extension declares for the module, each setting given the default that
505    ///   [`config`](Template::config) holds.
506    /// - It is `None` for a compose template that declares nothing of its settings (one
507    ///   made in code): what is written for it is given to it as written.
508    pub settings: Option<Value>,
509    /// The delimiters of its language, where they differ from the template engine's
510    /// usual ones.
511    pub delimiters: Option<Delimiters>,
512    /// The files it ships, in the order of its description (see the [module
513    /// documentation](self#files-a-compose-template-ships)).
514    pub artifacts: Vec<TemplateArtifact>,
515}
516
517/// A file that a template engine ships while it applies a compose template, which the
518/// composer writes beside the entry artifact (see the [module
519/// documentation](self#files-a-compose-template-ships)).
520#[derive(Debug, Clone, PartialEq, Eq)]
521pub struct ShippedFile {
522    /// The stem of the file's name (`notes` for `notes.css`), with which the name of the
523    /// shipped file begins.
524    pub stem: String,
525    /// The file's extension, without the dot (`css`).
526    pub extension: String,
527    /// The file's media type (`text/css`).
528    pub media_type: String,
529    /// The file's content.
530    pub bytes: Vec<u8>,
531}
532
533/// The handle through which a template engine ships a file, and reports a warning, while it
534/// applies a compose template ([`TemplateEngine::render`], [`TemplateEngine::render_text`];
535/// [`TemplateEngine::artifacts`] reports a warning through it).
536///
537/// The composer makes one per application of a compose template and gives it to every
538/// call of that application.
539pub trait TemplateShipper: Send + Sync {
540    /// Hands the composer the warning `detail`, a text for a person to read that states
541    /// what is wrong (for instance a downloaded file whose kept copy was used past its
542    /// expiry). The compose template is still applied; the composer reports each warning
543    /// as a [`TemplateWarning`], in the order first given. Giving the same text again in
544    /// the same application reports nothing more.
545    fn warn(&self, detail: String);
546
547    /// Hands `file` to the composer, which writes it beside the entry artifact, and
548    /// returns the file's path, as a compose template reads the paths of the files it
549    /// ships ([`TemplateContext::artifacts`]). Shipping the same file again returns the
550    /// same path and ships nothing more.
551    ///
552    /// # Errors
553    ///
554    /// Returns a text, for a person to read, that says why the file cannot be shipped: for
555    /// instance no package in use provides the program's naming of files. A template
556    /// engine reports it as it is, and the compose template cannot be applied.
557    fn ship(&self, file: ShippedFile) -> Result<String, String>;
558}
559
560/// One file, or one folder, a compose template ships, written beside the entry artifact
561/// (see the [module documentation](self#files-a-compose-template-ships)).
562#[derive(Debug, Clone, PartialEq, Eq)]
563pub enum TemplateArtifact {
564    /// One file (the key `file` of the description).
565    File {
566        /// The file's name, by which the compose template reads its path
567        /// (`artifacts.<name>`); its identity is `compose:<name>`.
568        name: String,
569        /// The file's extension, without the dot (`css`).
570        extension: String,
571        /// The file's media type (`text/css`).
572        media_type: String,
573        /// Whether the composer applies the bytes, as text, as a template before writing
574        /// them.
575        apply: bool,
576        /// The file's content, as the compose template's package holds it.
577        bytes: Vec<u8>,
578        /// The place of the file: the qualified path it was read from (see the [module
579        /// documentation](self#files-a-compose-template-includes)), which a template
580        /// engine gives a text it applies ([`TemplateEngine::render_text`]). `None` for a
581        /// content that no file holds.
582        source: Option<String>,
583    },
584    /// A folder (the key `dir` of the description), shipped as one folder artifact
585    /// ([`Artifact::folder`]).
586    Folder {
587        /// The folder's name, by which the compose template reads its path
588        /// (`artifacts.<name>`); its identity is `compose:<name>`.
589        name: String,
590        /// The files of the folder, each by its path relative to the folder (forward
591        /// slashes, no leading slash) and its content, in the order the folder reader of
592        /// [`Template::from_data`] gives them (the lexical order of the paths). It is
593        /// never empty.
594        files: Vec<(String, Vec<u8>)>,
595    },
596}
597
598impl TemplateArtifact {
599    /// Returns the name of the file or folder, by which the compose template reads its
600    /// path (`artifacts.<name>`).
601    pub fn name(&self) -> &str {
602        match self {
603            TemplateArtifact::File { name, .. } | TemplateArtifact::Folder { name, .. } => name,
604        }
605    }
606}
607
608/// The pieces that a description accepts, as written: `all`, or a list of piece names.
609#[derive(serde::Deserialize)]
610#[serde(untagged)]
611enum AcceptsData {
612    All(String),
613    Only(Vec<String>),
614}
615
616/// A compose template's description, as written.
617#[derive(serde::Deserialize)]
618#[serde(deny_unknown_fields)]
619struct Description {
620    name: String,
621    output: String,
622    engine: String,
623    #[serde(default)]
624    main: Option<String>,
625    accepts: AcceptsData,
626    #[serde(default)]
627    requires: Vec<String>,
628    #[serde(default)]
629    settings: Option<Value>,
630    #[serde(default)]
631    delimiters: Option<Delimiters>,
632    #[serde(default)]
633    artifacts: Map<String, Value>,
634}
635
636/// The description of one file or folder a compose template ships, as written.
637#[derive(serde::Deserialize)]
638#[serde(deny_unknown_fields)]
639struct ArtifactDescription {
640    #[serde(default)]
641    file: Option<String>,
642    #[serde(default)]
643    dir: Option<String>,
644    #[serde(default)]
645    template: Option<bool>,
646    #[serde(default)]
647    media_type: Option<String>,
648}
649
650/// Returns the extension of the file `file` (a path whose parts are separated by `/`): what
651/// follows the last `.` of its last part, when that `.` neither begins nor ends the part.
652fn extension_of_file(file: &str) -> Option<&str> {
653    let last = file.rsplit('/').next().unwrap_or(file);
654    match last.rfind('.') {
655        Some(dot) if dot > 0 && dot + 1 < last.len() => Some(&last[dot + 1..]),
656        _ => None,
657    }
658}
659
660/// The reader of the files a description lists, as [`Template::from_data`] takes it.
661type FileReader<'a> = &'a dyn Fn(&str) -> Result<Option<Vec<u8>>, String>;
662
663/// The reader of the folders a description lists, as [`Template::from_data`] takes it.
664type FolderReader<'a> = &'a dyn Fn(&str) -> Result<Option<Vec<(String, Vec<u8>)>>, String>;
665
666/// The place of a file a description lists, as [`Template::from_data`] takes it.
667type PlaceOf<'a> = &'a dyn Fn(&str) -> Option<String>;
668
669/// Returns the schema of the settings of the compose template `template` that its
670/// description gives as `settings` (an object schema with no setting when it gives none),
671/// and the default of each setting.
672fn template_settings(template: &str, settings: Option<Value>) -> Result<(Value, Map<String, Value>), String> {
673    let Some(settings) = settings else {
674        return Ok((serde_json::json!({ "type": "object", "properties": {} }), Map::new()));
675    };
676    let Some(properties) = settings.get("properties").and_then(Value::as_object) else {
677        return Err(format!(
678            "Invalid ‘settings’ of the compose template ‘{template}’: it must be a JSON Schema of an object, with \
679             ‘properties’ giving each setting's schema"
680        ));
681    };
682    let mut config = Map::new();
683    for (key, property) in properties {
684        match property.get("default") {
685            Some(default) => {
686                config.insert(key.clone(), default.clone());
687            }
688            None => return Err(format!("Missing ‘default’ of the setting ‘{key}’ of the compose template ‘{template}’")),
689        }
690    }
691    Ok((settings, config))
692}
693
694/// Returns the file or folder `name` that the description `description` of the compose
695/// template `template` (of template engine `engine`) lists, read through `files` or
696/// `folders`, a file at the place that `place` gives.
697fn template_artifact(
698    template: &str,
699    engine: &str,
700    name: &str,
701    description: Value,
702    files: FileReader<'_>,
703    folders: FolderReader<'_>,
704    place: PlaceOf<'_>,
705) -> Result<TemplateArtifact, String> {
706    let description: ArtifactDescription = serde_json::from_value(description).map_err(|error| {
707        format!("the artifact `{name}` of the compose template `{template}` cannot be read: {error}")
708    })?;
709    let file = match (&description.file, &description.dir) {
710        (Some(_), Some(_)) => {
711            return Err(format!(
712                "the artifact `{name}` of the compose template `{template}` gives both `file` and `dir`; give one"
713            ));
714        }
715        (None, Some(dir)) => return template_folder(template, name, dir, &description, folders),
716        (Some(file), None) => file.as_str(),
717        (None, None) => {
718            return Err(format!("the artifact `{name}` of the compose template `{template}` must give `file` or `dir`"));
719        }
720    };
721    let apply = description.template.unwrap_or(false);
722    if apply && engine == CONTENT_ONLY {
723        return Err(format!(
724            "the artifact `{name}` of the compose template `{template}` sets `template` to `true`, and the \
725             template engine `{CONTENT_ONLY}` applies no text"
726        ));
727    }
728    let Some(extension) = extension_of_file(file) else {
729        return Err(format!(
730            "the file `{file}` of the artifact `{name}` of the compose template `{template}` must have an \
731             extension"
732        ));
733    };
734    let media_type = match description.media_type.as_deref().or_else(|| media_type_of(extension)) {
735        Some(media_type) => media_type.to_string(),
736        None => {
737            return Err(format!(
738                "the artifact `{name}` of the compose template `{template}` must give `media_type`, since \
739                 the extension `{extension}` of its file `{file}` has no known media type"
740            ));
741        }
742    };
743    let bytes = match files(file) {
744        Ok(Some(bytes)) => bytes,
745        Ok(None) => {
746            return Err(format!(
747                "the file `{file}` of the artifact `{name}` of the compose template `{template}` is not a \
748                 file of the compose template's package"
749            ));
750        }
751        Err(error) => {
752            return Err(format!(
753                "the file `{file}` of the artifact `{name}` of the compose template `{template}` cannot be \
754                 read: {error}"
755            ));
756        }
757    };
758    if apply && std::str::from_utf8(&bytes).is_err() {
759        return Err(format!(
760            "the file `{file}` of the artifact `{name}` of the compose template `{template}` must be text, \
761             since `template` is `true`"
762        ));
763    }
764    Ok(TemplateArtifact::File {
765        name: name.to_string(),
766        extension: extension.to_string(),
767        media_type,
768        apply,
769        bytes,
770        source: place(file),
771    })
772}
773
774/// Returns the folder `dir` that the artifact `name` of the compose template `template`
775/// ships (its description `description`), read through `folders`.
776fn template_folder(
777    template: &str,
778    name: &str,
779    dir: &str,
780    description: &ArtifactDescription,
781    folders: FolderReader<'_>,
782) -> Result<TemplateArtifact, String> {
783    let given: Vec<&str> = [("template", description.template.is_some()), ("media_type", description.media_type.is_some())]
784        .into_iter()
785        .filter_map(|(key, given)| given.then_some(key))
786        .collect();
787    if !given.is_empty() {
788        let verb = if given.len() == 1 { "applies" } else { "apply" };
789        return Err(format!(
790            "the artifact `{name}` of the compose template `{template}` gives `dir` together with `{}`, which {verb} \
791             to a file only",
792            given.join("` and `")
793        ));
794    }
795    match folders(dir)? {
796        None => Err(format!("the shipped folder `{dir}` of the compose template `{template}` does not exist")),
797        Some(files) if files.is_empty() => {
798            Err(format!("the shipped folder `{dir}` of the compose template `{template}` holds no file"))
799        }
800        Some(files) => Ok(TemplateArtifact::Folder { name: name.to_string(), files }),
801    }
802}
803
804impl Template {
805    /// The compose template of the package `package` (the factory's name), from its
806    /// description as data, `text`, which reads the file of its text, `files`, which reads
807    /// a file the description lists, `folders`, which reads a folder it lists,
808    /// `place`, which gives the place of a file it reads, and `path`, which reads a path
809    /// that a setting's `default` writes.
810    ///
811    /// The description is a map of these keys:
812    ///
813    /// - `name`: the compose template's name, by which the setting `compose.template`
814    ///   chooses it;
815    /// - `output`: the output the compose template serves;
816    /// - `engine`: the name of its template engine;
817    /// - `main` (optional): the path of the file that holds its text, relative to the
818    ///   folder of the description; without it, the compose template's text is empty;
819    /// - `accepts`: the pieces it accepts, `all` or a list of piece names;
820    /// - `requires` (optional): the pieces it requires, a list of piece names;
821    /// - `settings` (optional): the JSON Schema of its own settings
822    ///   ([`Template::settings`]), an object schema whose `properties` are the settings,
823    ///   each with its `type`, its `description` (plain text), its `default` and its marks
824    ///   (`x-flm-marks`); every setting gives a `default`, and these are the compose
825    ///   template's defaults ([`Template::config`]), each text of a default that the
826    ///   schema marks [`Mark::Path`] as `path` gives
827    ///   it; without it, the compose template has no setting;
828    /// - `delimiters` (optional): the delimiters of its language where they differ from
829    ///   the usual ones ([`Delimiters`]);
830    /// - `artifacts` (optional): the files and folders it ships (see the [module
831    ///   documentation](self#files-a-compose-template-ships)), a map from each one's name
832    ///   to a map of these keys: `file`, the file's path, relative to the folder of the
833    ///   description, whose extension is the artifact's; `template` (optional, default
834    ///   `false`), whether the file's text is applied as a template of the same engine;
835    ///   `media_type` (optional), the file's media type, by default the one its extension
836    ///   gives ([`media_type_of`]). In place of `file`, the key `dir` gives the path of a
837    ///   folder, relative to the folder of the description, shipped whole as one folder
838    ///   artifact ([`TemplateArtifact::Folder`]); `template` and `media_type` are refused
839    ///   with it, since a folder is never applied as a template and its files' media types
840    ///   come from their extensions.
841    ///
842    /// `text(path)` returns the text of the file at `path` as the description's `main`
843    /// writes it, `Ok(None)` when there is no such file, and `Err` with a text for a person
844    /// when it cannot be read. It is called once when the description gives `main`, and not
845    /// at all otherwise.
846    ///
847    /// `files(path)` returns the bytes of the file at `path` as the description writes it,
848    /// `Ok(None)` when there is no such file, and `Err` with a text for a person when it
849    /// cannot be read. It is called once per file listed.
850    ///
851    /// `folders(path)` returns the files of the folder at `path` as the description writes
852    /// it, each by its path relative to that folder (forward slashes, no leading slash) and
853    /// its bytes, listed at every depth in lexical order of the paths; `Ok(None)` when
854    /// there is no such folder; and `Err` with a complete text for a person when the folder
855    /// cannot be shipped (it cannot be read, or its path is refused), which `from_data`
856    /// returns as it is. The reader decides which names it leaves out (an extension's
857    /// reader leaves out the names beginning with `.`). It is called once per folder
858    /// listed.
859    ///
860    /// `place(path)` returns the place of the file at `path` as the description writes it:
861    /// the qualified path of the file (see the [module
862    /// documentation](self#files-a-compose-template-includes)), or `None` where the files
863    /// read have no qualified paths. It is called for the text and for each file listed,
864    /// once each has been read, and gives [`Template::source`] and the field `source` of
865    /// [`TemplateArtifact::File`].
866    ///
867    /// `path(written)` returns the path `written`, a text of a setting's `default` that the
868    /// schema marks as a path, as the reader of the setting receives it: a qualified path,
869    /// a bare path given the root and the folder of the description; or `Err` with a text
870    /// for a person when the path has no meaning there. The defaults of
871    /// [`config`](Template::config) and of [`settings`](Template::settings) both hold its
872    /// answer.
873    ///
874    /// # Examples
875    ///
876    /// ```
877    /// use flm_core::stdlib::features::compose::{Accepts, Template};
878    /// use serde_json::json;
879    ///
880    /// let template = Template::from_data(
881    ///     "mine",
882    ///     json!({ "name": "page", "output": "html", "engine": "host", "main": "page.html", "accepts": "all" }),
883    ///     &|path| Ok((path == "page.html").then(|| String::from("<main>{{ regions.content }}</main>"))),
884    ///     &|_| Ok(None),
885    ///     &|_| Ok(None),
886    ///     &|path| Some(format!("ext+mine:{path}")),
887    ///     &|written| Ok(format!("ext+mine:{written}")),
888    /// )
889    /// .unwrap();
890    /// assert_eq!((template.name.as_str(), template.output.as_str()), ("page", "html"));
891    /// assert_eq!(template.accepts, Accepts::All);
892    /// assert_eq!(template.text, "<main>{{ regions.content }}</main>");
893    /// assert_eq!(template.source.as_deref(), Some("ext+mine:page.html"));
894    /// ```
895    ///
896    /// # Errors
897    ///
898    /// Returns a text, for a person to read, that says what is wrong:
899    ///
900    /// - the description cannot be read: it is not a map, it holds an unknown key, it
901    ///   lacks `name`, `output`, `engine` or `accepts`, a value has the wrong shape,
902    ///   `accepts` is neither `all` nor a list of names, `settings` is not an object
903    ///   schema with `properties`, a setting gives no `default`, or `path` refuses the
904    ///   path of a default;
905    /// - its text cannot be read: there is no file at `main`, or it cannot be read (the
906    ///   text of `text`'s `Err`);
907    /// - a file it lists cannot be shipped: there is no such file, it cannot be read, it
908    ///   has no extension, its media type is not known, or it is applied as a template
909    ///   while it is not text or the engine is `content-only`;
910    /// - a folder it lists cannot be shipped: the artifact gives both `file` and `dir`, or
911    ///   neither, or `dir` together with `template` or `media_type`, there is no such
912    ///   folder, it holds no file, or the text of `folders`'s `Err`.
913    // The readers' types are spelled out, so that their contracts read in the signature.
914    #[allow(clippy::type_complexity)]
915    pub fn from_data(
916        package: &str,
917        description: Value,
918        text: &dyn Fn(&str) -> Result<Option<String>, String>,
919        files: &dyn Fn(&str) -> Result<Option<Vec<u8>>, String>,
920        folders: &dyn Fn(&str) -> Result<Option<Vec<(String, Vec<u8>)>>, String>,
921        place: &dyn Fn(&str) -> Option<String>,
922        path: &dyn Fn(&str) -> Result<String, String>,
923    ) -> Result<Template, String> {
924        // A description that cannot be read is named by its `name` where it gives one.
925        let given_name = description.get("name").and_then(Value::as_str).map(str::to_string);
926        let description: Description = serde_json::from_value(description).map_err(|error| match given_name {
927            Some(name) => format!("the description of the compose template `{name}` cannot be read: {error}"),
928            None => format!("the description of a compose template cannot be read: {error}"),
929        })?;
930        let name = description.name.as_str();
931        let accepts = match description.accepts {
932            AcceptsData::All(all) if all == "all" => Accepts::All,
933            AcceptsData::All(other) => {
934                return Err(format!(
935                    "in the description of the compose template `{name}`, `accepts` must be `all` or a list \
936                     of piece names, not `{other}`"
937                ));
938            }
939            AcceptsData::Only(names) => Accepts::Only(names.into_iter().map(Name::from).collect()),
940        };
941        let (template_text, source) = match description.main.as_deref() {
942            None => (String::new(), None),
943            Some(main) => match text(main) {
944                Ok(Some(read)) => (read, place(main)),
945                Ok(None) => {
946                    return Err(format!(
947                        "the text `{main}` that `main` gives for the compose template `{name}` is not a file of \
948                         the compose template's package"
949                    ));
950                }
951                Err(error) => {
952                    return Err(format!(
953                        "the text `{main}` that `main` gives for the compose template `{name}` cannot be read: \
954                         {error}"
955                    ));
956                }
957            },
958        };
959        let (mut settings, mut config) = template_settings(name, description.settings)?;
960        rewrite_marked(&settings, Mark::Path, &mut config, &mut |written| path(written))
961            .map_err(|detail| format!("{detail} (a default of the compose template ‘{name}’)"))?;
962        // The schema states each setting's default as the compose template receives it.
963        if let Some(properties) = settings.get_mut("properties").and_then(Value::as_object_mut) {
964            for (key, property) in properties.iter_mut() {
965                if let (Some(default), Some(property)) = (config.get(key), property.as_object_mut()) {
966                    property.insert(String::from("default"), default.clone());
967                }
968            }
969        }
970        let mut artifacts = Vec::new();
971        for (artifact, data) in description.artifacts {
972            artifacts.push(template_artifact(name, &description.engine, &artifact, data, files, folders, place)?);
973        }
974        Ok(Template {
975            name: description.name,
976            package: String::from(package),
977            output: description.output,
978            engine: description.engine,
979            text: template_text,
980            source,
981            accepts,
982            requires: description.requires.into_iter().map(Name::from).collect(),
983            config,
984            settings: Some(settings),
985            delimiters: description.delimiters,
986            artifacts,
987        })
988    }
989}
990
991/// One piece as a compose template reads it: see the [module
992/// documentation](self#what-a-compose-template-reads).
993#[derive(Debug, Clone, PartialEq, Eq)]
994pub struct PieceValue {
995    /// The piece's name.
996    pub name: String,
997    /// Where the backend places it: `before-content` or `after-content`.
998    pub place: String,
999    /// Its text in the output's format; on HTML, inside the element that carries the
1000    /// piece's name ([`region_id`]).
1001    pub text: String,
1002    /// Its displayed characters as plain text.
1003    pub words: String,
1004}
1005
1006/// What a compose template reads: see the [module
1007/// documentation](self#what-a-compose-template-reads). The stage hands it to the template
1008/// engine together with the compose template.
1009#[derive(Debug, Clone, PartialEq)]
1010pub struct TemplateContext {
1011    /// Whether the output is HTML. A template engine then escapes for HTML every value
1012    /// that the compose template writes, except a region and a piece's text, which are
1013    /// already HTML.
1014    pub html: bool,
1015    /// Every output region, by name, as text, in the backend's order; on HTML, the content
1016    /// and each piece inside the element that carries its name.
1017    pub regions: Vec<(String, String)>,
1018    /// The regions that are pieces, in the backend's order.
1019    pub pieces: Vec<PieceValue>,
1020    /// The document's metadata, as data.
1021    pub metadata: Value,
1022    /// The compose template's own settings: its defaults, with the values of the render
1023    /// option `template_config` written over them.
1024    pub config: Map<String, Value>,
1025    /// The path of each file the compose template ships, as (name, path), in the order
1026    /// in which its template engine gives them ([`TemplateEngine::artifacts`]; by default
1027    /// the order of its description, [`Template::artifacts`]). A path is relative to the
1028    /// folder where the program writes the output's files, where the entry file lies
1029    /// under a host's usual naming of files. A template engine exposes them as the value
1030    /// `artifacts`, a map from name to path.
1031    pub artifacts: Vec<(String, String)>,
1032}
1033
1034/// A template engine: the code that applies a compose template written in its language to
1035/// a [`TemplateContext`].
1036///
1037/// A feature contributes one to [`ENGINES_SLOT`]; a compose template refers to its
1038/// template engine by name ([`Template::engine`]).
1039pub trait TemplateEngine: Send + Sync {
1040    /// Returns the engine's name, by which a compose template refers to it.
1041    fn name(&self) -> &str;
1042
1043    /// Returns the text of the compose template `template` applied to `context`.
1044    ///
1045    /// # Errors
1046    ///
1047    /// Returns a text, for a person to read, that says why the compose template cannot be
1048    /// applied: for instance its text does not compile, or it refers to a value that
1049    /// `context` does not provide. The stage reports it in [`TemplateFailed`].
1050    ///
1051    /// An engine whose language includes other files reads a path written without a
1052    /// root beside the place of the text that writes it ([`Template::source`]).
1053    ///
1054    /// An engine whose language ships a file hands it to `shipper` and writes the path it
1055    /// returns. The pointer is shared, so that the engine can keep it where a function of
1056    /// its language must own what it holds.
1057    fn render(
1058        &self,
1059        template: &Template,
1060        context: &TemplateContext,
1061        shipper: &Arc<dyn TemplateShipper>,
1062    ) -> Result<String, String>;
1063
1064    /// Returns the files the compose template `template` ships when it is applied to
1065    /// `context`, which the composer names and writes beside the entry artifact, in this
1066    /// order, and whose paths it then gives to [`render`](Self::render) in
1067    /// [`TemplateContext::artifacts`]. The composer calls it once per application, before
1068    /// it names the files, so `context` holds no path yet: its `artifacts` is empty.
1069    ///
1070    /// The default returns the compose template's own list ([`Template::artifacts`]). An
1071    /// engine whose compose templates choose their files when they are applied returns
1072    /// them here. `shipper` is the handle of the same application that
1073    /// [`render`](Self::render) receives, through which the engine reports a warning while
1074    /// it reads the files.
1075    ///
1076    /// # Errors
1077    ///
1078    /// Returns a text, for a person to read, that says why the files cannot be given. The
1079    /// stage reports it in [`TemplateFailed`], as for [`render`](Self::render).
1080    fn artifacts(
1081        &self,
1082        template: &Template,
1083        context: &TemplateContext,
1084        shipper: &Arc<dyn TemplateShipper>,
1085    ) -> Result<Vec<TemplateArtifact>, String> {
1086        let _ = (context, shipper);
1087        Ok(template.artifacts.clone())
1088    }
1089
1090    /// Applies `text`, written in this engine's language under the settings of `template`
1091    /// (its name, its delimiters), to `context`, and returns the result. `place` is the
1092    /// place of `text` (see the [module
1093    /// documentation](self#files-a-compose-template-includes)), `None` for a text that no
1094    /// file holds. The composer calls it for a file the compose template ships and applies
1095    /// (the fields `apply` and `source` of [`TemplateArtifact::File`]).
1096    ///
1097    /// The default applies [`render`](Self::render) to a copy of `template` whose text is
1098    /// `text` and whose place is `place`, which serves an engine that reads the compose
1099    /// template's text. An engine ships files through `shipper` as
1100    /// [`render`](Self::render) does.
1101    ///
1102    /// # Errors
1103    ///
1104    /// As [`render`](Self::render).
1105    fn render_text(
1106        &self,
1107        template: &Template,
1108        text: &str,
1109        place: Option<&str>,
1110        context: &TemplateContext,
1111        shipper: &Arc<dyn TemplateShipper>,
1112    ) -> Result<String, String> {
1113        let source = place.map(str::to_string);
1114        self.render(&Template { text: text.to_string(), source, ..template.clone() }, context, shipper)
1115    }
1116}
1117
1118// --- the settings --------------------------------------------------------------------------
1119
1120/// Which compose template a render uses: one name for every output, or a name per output.
1121#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
1122#[serde(untagged)]
1123pub enum TemplateChoice {
1124    /// The compose template of this name, for whichever output a render request makes.
1125    Name(String),
1126    /// A compose template's name per output's name; an output not listed takes
1127    /// [`DEFAULT_TEMPLATE`].
1128    ByOutput(BTreeMap<String, String>),
1129}
1130
1131impl TemplateChoice {
1132    /// Returns the name of the compose template chosen for the output `output`.
1133    pub fn for_output(&self, output: &str) -> &str {
1134        match self {
1135            TemplateChoice::Name(name) => name,
1136            TemplateChoice::ByOutput(names) => {
1137                names.get(output).map(String::as_str).unwrap_or(DEFAULT_TEMPLATE)
1138            }
1139        }
1140    }
1141}
1142
1143/// The render options of the feature `compose`, set per render request: the compose
1144/// template each output is assembled with, and each compose template's own settings.
1145///
1146/// It is an option type bound to the render request ([`Bind::Render`];
1147/// [`crate::model::options`]). A host combines its value from its sources of settings.
1148///
1149/// # Examples
1150///
1151/// ```
1152/// use flm_core::stdlib::features::compose::{ComposeOptions, DEFAULT_TEMPLATE};
1153///
1154/// assert_eq!(ComposeOptions::default().template.for_output("html"), DEFAULT_TEMPLATE);
1155/// ```
1156#[derive(Debug, Clone, PartialEq, serde::Deserialize, schemars::JsonSchema)]
1157#[serde(default, deny_unknown_fields)]
1158pub struct ComposeOptions {
1159    /// The compose template: a name, or a map from an output's name to a compose
1160    /// template's name. The default is [`DEFAULT_TEMPLATE`], `simple`, for every output.
1161    pub template: TemplateChoice,
1162    /// A map from an output's name to a map from a compose template's name to that
1163    /// compose template's own settings for that output, written over its defaults key by
1164    /// key: `{latex-rendered: {simple: {documentclass: report}}}`. Two compose templates of
1165    /// the same name for two outputs are two compose templates, so their settings are
1166    /// given apart ([`ComposeOptions::config_for`]). An output's name that names no output
1167    /// a render makes is never read, as in [`TemplateChoice::ByOutput`].
1168    pub template_config: BTreeMap<String, BTreeMap<String, Map<String, Value>>>,
1169}
1170
1171impl ComposeOptions {
1172    /// Returns the settings that [`template_config`](Self::template_config) gives for the
1173    /// compose template `template` of the output `output`, if it gives any.
1174    pub fn config_for(&self, output: &str, template: &str) -> Option<&Map<String, Value>> {
1175        self.template_config.get(output)?.get(template)
1176    }
1177}
1178
1179impl Default for ComposeOptions {
1180    fn default() -> ComposeOptions {
1181        ComposeOptions {
1182            template: TemplateChoice::Name(String::from(DEFAULT_TEMPLATE)),
1183            template_config: BTreeMap::new(),
1184        }
1185    }
1186}
1187
1188// An option type is part of a plan's key, so it hashes, and two values it holds equal hash
1189// equal: the settings of a template are data, whose maps are equal whatever the order of
1190// their entries, so they are hashed with every map's entries in the order of their keys.
1191impl Hash for ComposeOptions {
1192    fn hash<H: Hasher>(&self, state: &mut H) {
1193        self.template.hash(state);
1194        for (output, templates) in &self.template_config {
1195            output.hash(state);
1196            for (name, config) in templates {
1197                name.hash(state);
1198                hash_value(&Value::Object(config.clone()), state);
1199            }
1200        }
1201    }
1202}
1203
1204/// Returns the declaration of the feature's settings: the fields of [`ComposeOptions`]
1205/// are its keys, set per render request. `template_config`, each output's map in it and
1206/// each compose template's settings are combined key by key across the sources of
1207/// settings, so that a source that writes one setting of a compose template leaves the
1208/// others as the lower sources write them; `false` is a value like any other there. The
1209/// settings of each compose template are an entry that another feature declares
1210/// ([`declare_settings`]).
1211fn settings() -> SettingsDecl {
1212    SettingsDecl::new(FEATURE)
1213        .options::<ComposeOptions>(
1214            Bind::Render,
1215            "The compose template each output is assembled with (`template`: a name, or a map \
1216             from an output's name to a compose template's name), and each compose template's \
1217             own settings (`template_config`, a map from an output's name to a map from a \
1218             compose template's name to its settings for that output). Set per render request.",
1219        )
1220        .merge_entries("template_config", no_entries)
1221        .merge_entries("template_config.*", no_entries)
1222        .merge_entries("template_config.*.*", no_entries)
1223        .open_entries("template_config.*.*")
1224}
1225
1226/// Returns `decl`, the settings declaration of a feature that contributes the compose
1227/// templates `templates`, declaring the settings of each one that has a schema
1228/// ([`Template::settings`]) as the entry `template_config.OUTPUT.NAME` of the feature
1229/// `compose` ([`declare_template_settings`]).
1230///
1231/// # Errors
1232///
1233/// A [`SettingsError`] of the kind [`SettingsErrorKind::InvalidDeclaration`] for two
1234/// compose templates with a schema, of one output and one name, at the path
1235/// `compose.template_config.OUTPUT.NAME`; and the [`SettingsError`] of a schema whose marks
1236/// are faulty, as [`SettingsDecl::entry_data`] states.
1237pub fn declare_settings(mut decl: SettingsDecl, templates: &[Template]) -> Result<SettingsDecl, SettingsError> {
1238    for (index, template) in templates.iter().enumerate() {
1239        let Some(schema) = &template.settings else { continue };
1240        let path = format!("template_config.{}.{}", template.output, template.name);
1241        let earlier = templates[..index].iter().any(|other| {
1242            other.settings.is_some() && other.output == template.output && other.name == template.name
1243        });
1244        if earlier {
1245            return Err(SettingsError {
1246                path: format!("{FEATURE}.{path}"),
1247                kind: SettingsErrorKind::InvalidDeclaration,
1248                detail: format!(
1249                    "Duplicate compose template ‘{}’ for the output ‘{}’ in the package ‘{}’",
1250                    template.name, template.output, template.package
1251                ),
1252            });
1253        }
1254        decl = declare_template_settings(decl, &template.output, &template.name, schema.clone())?;
1255    }
1256    Ok(decl)
1257}
1258
1259/// Returns `decl`, the settings declaration of a feature that contributes the compose
1260/// template `name` of the output `output`, declaring `schema`, the JSON Schema of the
1261/// compose template's settings, as the entry `template_config.OUTPUT.NAME` of the
1262/// feature `compose` ([`SettingsDecl::entry_data`]), labeled `compose template ‘NAME’
1263/// for the output ‘OUTPUT’`. A schema without a `description` gets one that names the
1264/// compose template. [`declare_settings`] declares the compose templates of a list this
1265/// way; a feature that contributes a compose template known by its name and its output
1266/// before it is made (a template module of an extension) calls this directly.
1267///
1268/// # Errors
1269///
1270/// The [`SettingsError`] of a schema whose marks are faulty, as
1271/// [`SettingsDecl::entry_data`] states.
1272pub fn declare_template_settings(
1273    decl: SettingsDecl,
1274    output: &str,
1275    name: &str,
1276    mut schema: Value,
1277) -> Result<SettingsDecl, SettingsError> {
1278    if let Value::Object(object) = &mut schema {
1279        if !object.contains_key("description") {
1280            let described = format!("The settings of the compose template ‘{name}’ of the output ‘{output}’.");
1281            let mut with = Map::new();
1282            with.insert(String::from("description"), Value::from(described));
1283            with.extend(std::mem::take(object));
1284            *object = with;
1285        }
1286    }
1287    let path = format!("template_config.{output}.{name}");
1288    let label = format!("compose template ‘{name}’ for the output ‘{output}’");
1289    decl.entry_data(FEATURE, path, label, schema)
1290}
1291
1292/// The default entries of each level of `template_config`: none.
1293fn no_entries() -> Result<Value, String> {
1294    Ok(Value::Object(Map::new()))
1295}
1296
1297// --- choosing a template -----------------------------------------------------------------------
1298
1299/// Returns the compose template of the registry `registry` that `options` chooses for the
1300/// output `output`.
1301///
1302/// # Errors
1303///
1304/// Returns a text, for a person to read, when no compose template of the chosen name
1305/// serves the output (the text lists those that do, or says that none does), or when
1306/// several do (the text gives each package that ships one and how many it ships).
1307pub fn chosen_template<'r>(
1308    registry: &'r FlmRegistry,
1309    options: &ComposeOptions,
1310    output: &str,
1311) -> Result<&'r Template, String> {
1312    let name = options.template.for_output(output);
1313    let mut matching = registry
1314        .services()
1315        .services_named::<Template>(TEMPLATES_SLOT)
1316        .filter(|template| template.name == name && template.output == output);
1317    let first = matching.next();
1318    if let Some(template) = first {
1319        let others: Vec<&Template> = matching.collect();
1320        if !others.is_empty() {
1321            // Each package that ships one, with how many it ships.
1322            let mut packages: Vec<(&str, usize)> = Vec::new();
1323            for template in std::iter::once(template).chain(others) {
1324                match packages.iter_mut().find(|(package, _)| *package == template.package) {
1325                    Some((_, count)) => *count += 1,
1326                    None => packages.push((template.package.as_str(), 1)),
1327                }
1328            }
1329            let shipped: Vec<String> =
1330                packages.iter().map(|(package, count)| format!("the package ‘{package}’ ships {count}")).collect();
1331            return Err(format!(
1332                "only one compose template named ‘{name}’ for the output ‘{output}’ may be in use; {}",
1333                shipped.join(", ")
1334            ));
1335        }
1336    }
1337    first.ok_or_else(|| {
1338            let known: Vec<&str> = registry
1339                .services()
1340                .services_named::<Template>(TEMPLATES_SLOT)
1341                .filter(|template| template.output == output)
1342                .map(|template| template.name.as_str())
1343                .collect();
1344            if known.is_empty() {
1345                format!(
1346                    "the compose template `{name}` must be one of the compose templates for the output \
1347                     `{output}`, and no package in use ships one for that output"
1348                )
1349            } else {
1350                format!(
1351                    "the compose template `{name}` must be one of the compose templates for the output \
1352                     `{output}`: `{}`",
1353                    known.join("`, `")
1354                )
1355            }
1356        })
1357}
1358
1359/// Returns the pieces that the compose template `template` accepts among those that
1360/// `registry` declares, in the order of their declarations: the selection of pieces that
1361/// a host writes for the output's backend into [`PiecesRenderOptions::backends`].
1362pub fn accepted_pieces(registry: &FlmRegistry, template: &Template) -> Vec<Name> {
1363    core_pieces::declared_pieces(registry)
1364        .filter(|decl| match &template.accepts {
1365            Accepts::All => true,
1366            Accepts::Only(names) => names.contains(&decl.name),
1367        })
1368        .map(|decl| decl.name.clone())
1369        .collect()
1370}
1371
1372/// Sets, in `pieces`, the selection of pieces of the backend of `output` to the pieces
1373/// that the compose template `template` accepts ([`accepted_pieces`]), and adds the
1374/// pieces it requires ([`Template::requires`]) to the pieces placed although declared off
1375/// by default ([`PiecesRenderOptions::include`]), so that what the compose template
1376/// requires is placed.
1377///
1378/// The host calls it when it prepares the plan of an output that the composer serves.
1379pub fn select_pieces(
1380    registry: &FlmRegistry,
1381    template: &Template,
1382    output: &RegionsOutput,
1383    pieces: &mut PiecesRenderOptions,
1384) {
1385    pieces.backends.insert(
1386        output.backend.clone(),
1387        accepted_pieces(registry, template).into_iter().collect(),
1388    );
1389    pieces.include.extend(template.requires.iter().cloned());
1390}
1391
1392// --- the composer's table on HTML ----------------------------------------------------------
1393
1394/// What one region's place in the page holds: HTML, or plain words.
1395#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1396pub enum ComposedKind {
1397    /// HTML, placed inside the element that carries the region's identifier.
1398    Html,
1399    /// Plain words, placed where no element is allowed: the words of the page's title
1400    /// (the region [`title`](region::TITLE), placed in `<title>`), kept under that
1401    /// region's identifier. A piece's words are not in the table but in the rest of the
1402    /// page (see the [module
1403    /// documentation](self#on-html-one-element-per-region-and-the-composers-table)).
1404    Words,
1405}
1406
1407/// One region as the page holds it.
1408#[derive(Debug, Clone, PartialEq, Eq)]
1409pub struct ComposedRegion {
1410    /// The identifier: [`region_id`] of the region's name.
1411    pub id: String,
1412    /// The region's name.
1413    pub name: String,
1414    /// Whether the text is HTML or words.
1415    pub kind: ComposedKind,
1416    /// The text: the HTML inside the element, or the words.
1417    pub text: String,
1418}
1419
1420/// The composer's table on HTML, [`HTML_REGIONS`]: each region that the composer placed,
1421/// and the rest of the page (see the [module
1422/// documentation](self#on-html-one-element-per-region-and-the-composers-table)).
1423#[derive(Debug, Clone, Default, PartialEq, Eq)]
1424pub struct ComposedRegions {
1425    /// The rest of the page, everything outside its regions: the page with exactly what
1426    /// [`regions`](Self::regions) holds left out, that is with every element that carries
1427    /// a region's identifier empty and the title's words empty, and everything else as in
1428    /// the page (the stylesheets, the scripts, the language, the compose template's own
1429    /// markup, each piece's words). The regions and the rest of the page together make up
1430    /// the page, so two builds that differ anywhere differ in the rest of the page or in
1431    /// an entry of [`regions`](Self::regions).
1432    pub skeleton: String,
1433    /// Each region that the composer placed (the content and the pieces), and the words of
1434    /// the page's title.
1435    pub regions: Vec<ComposedRegion>,
1436}
1437
1438impl ComposedRegions {
1439    /// Returns the region with the identifier `id`, if there is one.
1440    pub fn get(&self, id: &str) -> Option<&ComposedRegion> {
1441        self.regions.iter().find(|region| region.id == id)
1442    }
1443}
1444
1445impl Table for ComposedRegions {
1446    /// The table has one writer per run: a second write replaces the first.
1447    fn absorb(&mut self, piece: ComposedRegions) {
1448        *self = piece;
1449    }
1450
1451    /// `{skeleton, regions: [{id, name, kind, text}]}`.
1452    fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
1453        let regions = self
1454            .regions
1455            .iter()
1456            .map(|region| {
1457                SerialValue::Map(vec![
1458                    (String::from("id"), SerialValue::Str(region.id.clone())),
1459                    (String::from("name"), SerialValue::Str(region.name.clone())),
1460                    (
1461                        String::from("kind"),
1462                        SerialValue::Str(String::from(match region.kind {
1463                            ComposedKind::Html => "html",
1464                            ComposedKind::Words => "words",
1465                        })),
1466                    ),
1467                    (String::from("text"), SerialValue::Str(region.text.clone())),
1468                ])
1469            })
1470            .collect();
1471        SerialValue::Map(vec![
1472            (String::from("skeleton"), SerialValue::Str(self.skeleton.clone())),
1473            (String::from("regions"), SerialValue::List(regions)),
1474        ])
1475    }
1476
1477    fn piece_class(&self) -> PieceClass {
1478        PieceClass::DocumentFact
1479    }
1480}
1481
1482// --- the feature ---------------------------------------------------------------------------
1483
1484/// The feature `compose`: see the [module documentation](self). A host registers it; it
1485/// is not among the standard features that
1486/// [`stdlib::add_features`](crate::stdlib::add_features) adds.
1487#[derive(Debug, Default, Clone, Copy)]
1488pub struct ComposeFeature;
1489
1490impl ComposeFeature {
1491    /// The feature `compose`: the two service slots, the template engine `content-only`,
1492    /// the table `flm.compose.html.regions`, a composer per regions output. It contributes
1493    /// no compose template.
1494    pub fn new() -> ComposeFeature {
1495        ComposeFeature
1496    }
1497}
1498
1499impl FlmFeature for ComposeFeature {
1500    fn info(&self) -> FeatureInfo {
1501        FeatureInfo::new(FEATURE, "Templates").docs(
1502            "the template engines, the compose templates, and for each output a stage that \
1503             assembles the output from its content and its other parts through the chosen \
1504             compose template",
1505        )
1506    }
1507
1508    fn settings(&self) -> Option<SettingsDecl> {
1509        Some(settings())
1510    }
1511
1512    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
1513        b.service_slot::<dyn TemplateEngine>(
1514            ENGINES_SLOT,
1515            Arity::OrderedMany,
1516            "the template engines, each with a name",
1517        )?;
1518        b.service_slot::<Template>(
1519            TEMPLATES_SLOT,
1520            Arity::OrderedMany,
1521            "the compose templates, each with a name and the output it serves",
1522        )?;
1523        b.contribute_to::<dyn TemplateEngine>(ENGINES_SLOT, Arc::new(ContentOnlyEngine))?;
1524        b.table(
1525            HTML_REGIONS,
1526            "the HTML that the page holds under each region's identifier, the words of the page's \
1527             title, and the rest of the page outside those regions",
1528        )?;
1529        b.finalizer(Arc::new(RegisterStages))
1530    }
1531}
1532
1533/// The second round of the feature's registration ([`Finalizer`]): registers one stage
1534/// per output that a backend of the registry states is made of output regions, once every
1535/// feature has contributed to [`REGIONS_SLOT`].
1536struct RegisterStages;
1537
1538impl Finalizer for RegisterStages {
1539    fn finalize(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
1540        let outputs: Vec<RegionsOutput> = b
1541            .services()
1542            .map(|services| services.services_named::<RegionsOutput>(REGIONS_SLOT).cloned().collect())
1543            .unwrap_or_default();
1544        for output in outputs {
1545            b.stage(Arc::new(ComposeStage { output }))?;
1546        }
1547        Ok(())
1548    }
1549}
1550
1551// --- the stage -----------------------------------------------------------------------------
1552
1553/// The composer's stage for one output, `flm.compose.<output>`: see the [module
1554/// documentation](self).
1555struct ComposeStage {
1556    output: RegionsOutput,
1557}
1558
1559/// Returns an empty span whose origin is the stage `stage`, for a problem that has no
1560/// place in the document.
1561fn nowhere(stage: &str) -> FlmSpan {
1562    let source = Arc::new(Source::new("").with_origin(FlmOrigin::synthetic(stage)));
1563    SourceSpan::new(&source, 0..0)
1564}
1565
1566impl ComposeStage {
1567    fn regions_table(&self) -> TableHandle<Regions> {
1568        self.output.regions.clone()
1569    }
1570
1571    fn document_table(&self) -> TableHandle<ArtifactSet> {
1572        TableHandle::new(self.output.document.clone())
1573    }
1574
1575    fn fail(&self, out: &mut StageOut<'_>, template: Option<&str>, detail: impl ToString) {
1576        out.diags.push(Diagnostic::error(
1577            TemplateFailed {
1578                template: template.map(String::from),
1579                output: self.output.output.to_string(),
1580                detail: detail.to_string(),
1581            },
1582            nowhere(&stage_name(self.output.output.as_str())),
1583        ));
1584    }
1585}
1586
1587impl Stage for ComposeStage {
1588    fn decl(&self) -> StageDecl {
1589        let mut decl =
1590            StageDecl::new(stage_name(self.output.output.as_str()), Effect::Compute, Scope::Document)
1591                .writes(self.document_table());
1592        if self.output.capability != self.output.document {
1593            decl = decl.provides(self.output.capability.clone());
1594        }
1595        if is_html(&self.output) {
1596            decl = decl.writes(HTML_REGIONS);
1597        }
1598        decl.docs(format!(
1599            "assembles the `{}` output's entry artifact from its output regions through the \
1600             chosen compose template",
1601            self.output.output
1602        ))
1603    }
1604
1605    fn needs(&self, cx: &PlanCx<'_>) -> Needs {
1606        let mut needs = Needs::new().reads(self.regions_table()).option::<ComposeOptions>();
1607        for artifacts in &self.output.artifacts {
1608            needs = needs.reads_opt(artifacts.clone());
1609        }
1610        // The metadata is read where a feature of the registry declares it.
1611        if cx.registry().option_decl(&OptionKey::of::<DocMeta>()).is_some() {
1612            needs = needs.option::<DocMeta>();
1613        }
1614        // A required piece is read, so that a plan in which nobody provides it fails.
1615        let default = ComposeOptions::default();
1616        let options = cx.render_option::<ComposeOptions>().unwrap_or(&default);
1617        if let Ok(template) = chosen_template(cx.registry(), options, self.output.output.as_str()) {
1618            let declared: Vec<&PieceDecl> = core_pieces::declared_pieces(cx.registry()).collect();
1619            for name in &template.requires {
1620                // A piece nobody declares is read under its table's usual name, which is
1621                // the piece's, so that the plan fails naming it.
1622                let table = match declared.iter().find(|decl| &decl.name == name) {
1623                    Some(decl) => decl.table.clone(),
1624                    None => TableHandle::<Piece>::new(name.clone()),
1625                };
1626                needs = needs.reads(table);
1627            }
1628        }
1629        needs
1630    }
1631
1632    fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
1633        let options = match cx.option::<ComposeOptions>() {
1634            Ok(options) => options,
1635            Err(error) => return self.fail(out, None, error),
1636        };
1637        let name = options.template.for_output(self.output.output.as_str());
1638        let template = match chosen_template(cx.registry(), options, self.output.output.as_str()) {
1639            Ok(template) => template,
1640            Err(detail) => return self.fail(out, Some(name), detail),
1641        };
1642        let Some(engine) = cx
1643            .registry()
1644            .services()
1645            .services_by_precedence_named::<dyn TemplateEngine>(ENGINES_SLOT)
1646            .find(|engine| engine.name() == template.engine)
1647        else {
1648            return self.fail(out, Some(name), format!("the template engine `{}`, in which the template is written, must be provided by a package in use, and none provides it", template.engine));
1649        };
1650        let regions = match cx.get(&self.regions_table()) {
1651            Ok(Some(regions)) => regions,
1652            Ok(None) => return,
1653            Err(error) => return self.fail(out, Some(name), error),
1654        };
1655        let mut beside = Vec::new();
1656        for artifacts in &self.output.artifacts {
1657            match cx.get(artifacts) {
1658                Ok(set) => beside.extend(set),
1659                Err(error) => return self.fail(out, Some(name), error),
1660            }
1661        }
1662        // The metadata is read where a feature of the registry declares it, as the plan
1663        // does; a failed read is reported as the stage's other failed reads are.
1664        let metadata = if cx.registry().option_decl(&OptionKey::of::<DocMeta>()).is_some() {
1665            match cx.option::<DocMeta>() {
1666                Ok(meta) => meta_value(meta),
1667                Err(error) => return self.fail(out, Some(name), error),
1668            }
1669        } else {
1670            Value::Object(Map::new())
1671        };
1672        let mut config = template.config.clone();
1673        if let Some(given) = options.config_for(&template.output, &template.name) {
1674            for (key, value) in given {
1675                config.insert(key.clone(), value.clone());
1676            }
1677        }
1678        let mut context = context(&self.output, regions, metadata, config, Vec::new());
1679        let namer = cx.services_all().shared_service_named::<dyn ArtifactNamer>(NAMER_SLOT).cloned();
1680        let scope = NamingScope::of(cx.registry(), cx.plan().demands());
1681        let shipper = Arc::new(Shipper { namer, scope, shipped: Mutex::new(Vec::new()), warnings: Mutex::new(Vec::new()) });
1682        let handle: Arc<dyn TemplateShipper> = shipper.clone();
1683        // The warnings of the template engine are reported whether the application
1684        // succeeds or fails.
1685        'applied: {
1686            // The files the compose template ships, as its template engine answers them for
1687            // this context, which holds no path yet; then their paths, from the naming of
1688            // files, which the compose template reads.
1689            let artifacts = match engine.artifacts(template, &context, &handle) {
1690                Ok(artifacts) => artifacts,
1691                Err(detail) => break 'applied self.fail(out, Some(name), detail),
1692            };
1693            let mut paths = Vec::new();
1694            if !artifacts.is_empty() {
1695                let Some(namer) = &shipper.namer else {
1696                    let names: Vec<&str> = artifacts.iter().map(TemplateArtifact::name).collect();
1697                    break 'applied self.fail(
1698                        out,
1699                        Some(name),
1700                        format!(
1701                            "the compose template ships the files `{}`, and naming them needs the program's naming \
1702                             of files (the service slot `{NAMER_SLOT}`), which no package in use provides",
1703                            names.join("`, `")
1704                        ),
1705                    );
1706                };
1707                for artifact in &artifacts {
1708                    let id = artifact_id(artifact);
1709                    let named = match artifact {
1710                        TemplateArtifact::File { media_type, extension, .. } => ArtifactRef {
1711                            id: &id,
1712                            entry: false,
1713                            media_type,
1714                            extension: Some(extension),
1715                            output: None,
1716                            folder: false,
1717                        },
1718                        TemplateArtifact::Folder { .. } => {
1719                            ArtifactRef { id: &id, entry: false, media_type: "", extension: None, output: None, folder: true }
1720                        }
1721                    };
1722                    paths.push((artifact.name().to_string(), namer.url_of(&named, &shipper.scope).as_str().to_string()));
1723                }
1724            }
1725            context.artifacts = paths;
1726            let mut shipped = Vec::new();
1727            for artifact in &artifacts {
1728                let (artifact_name, extension, media_type, apply, bytes, place) = match artifact {
1729                    TemplateArtifact::File { name, extension, media_type, apply, bytes, source } => {
1730                        (name, extension, media_type, *apply, bytes, source.as_deref())
1731                    }
1732                    TemplateArtifact::Folder { files, .. } => {
1733                        let files = files.iter().map(|(path, bytes)| (RelPath::new(path.as_str()), bytes.clone())).collect();
1734                        shipped.push(Artifact::folder(artifact_id(artifact), files));
1735                        continue;
1736                    }
1737                };
1738                let bytes = if apply {
1739                    let Ok(text) = std::str::from_utf8(bytes) else {
1740                        let detail = format!(
1741                            "in the artifact `{artifact_name}`: its content must be text, since it is applied as a template"
1742                        );
1743                        break 'applied self.fail(out, Some(name), detail);
1744                    };
1745                    let mut applied = context.clone();
1746                    applied.html = media_type == "text/html";
1747                    match engine.render_text(template, text, place, &applied, &handle) {
1748                        Ok(text) => text.into_bytes(),
1749                        Err(detail) => {
1750                            break 'applied self.fail(out, Some(name), format!("in the artifact `{artifact_name}`: {detail}"));
1751                        }
1752                    }
1753                } else {
1754                    bytes.clone()
1755                };
1756                shipped.push(Artifact::bytes(artifact_id(artifact), media_type.clone(), bytes).with_extension(extension.clone()));
1757            }
1758            let text = match engine.render(template, &context, &handle) {
1759                Ok(text) => text,
1760                Err(detail) => break 'applied self.fail(out, Some(name), detail),
1761            };
1762            let composed = if is_html(&self.output) {
1763                let empty = context_with_regions_left_out(regions, &context);
1764                match engine.render(template, &empty, &handle) {
1765                    Ok(skeleton) => Some(composed_regions(regions, skeleton)),
1766                    Err(detail) => break 'applied self.fail(out, Some(name), detail),
1767                }
1768            } else {
1769                None
1770            };
1771            shipped.extend(shipper.take());
1772            let mut entry =
1773                Artifact::bytes(regions.entry.clone(), regions.media_type.clone(), text.into_bytes())
1774                    .as_entry();
1775            entry.refs.extend(regions.refs.iter().cloned());
1776            entry.refs.extend(shipped.iter().map(|artifact| artifact.id.clone()));
1777            let set = match out.table(&self.document_table()) {
1778                Ok(set) => set,
1779                Err(error) => break 'applied self.fail(out, Some(name), error),
1780            };
1781            let reports = match set.insert_entry_with(entry, &beside) {
1782                Ok(reports) => reports,
1783                Err(violation) => break 'applied self.fail(out, Some(name), violation),
1784            };
1785            let refused: Vec<_> = shipped.into_iter().filter_map(|artifact| set.insert(artifact).err()).collect();
1786            reports.into_iter().for_each(|report| out.diags.push(report));
1787            for violation in refused {
1788                self.fail(out, Some(name), violation);
1789            }
1790            if let Some(composed) = composed {
1791                match out.table(HTML_REGIONS) {
1792                    Ok(table) => *table = composed,
1793                    Err(error) => self.fail(out, Some(name), error),
1794                }
1795            }
1796        }
1797        for detail in shipper.take_warnings() {
1798            out.diags.push(Diagnostic::warning(
1799                TemplateWarning { template: name.to_string(), output: self.output.output.to_string(), detail },
1800                nowhere(&stage_name(self.output.output.as_str())),
1801            ));
1802        }
1803    }
1804}
1805
1806/// The composer's [`TemplateShipper`] for one application of a compose template: it names
1807/// each file it is handed and keeps it, until the composer adds the files to the output's
1808/// artifact set, and keeps each warning given to [`warn`](TemplateShipper::warn), until the
1809/// composer reports it.
1810struct Shipper {
1811    /// The program's naming of files, where a package in use provides it.
1812    namer: Option<Arc<dyn ArtifactNamer>>,
1813    /// The scope in which the files are named.
1814    scope: NamingScope,
1815    /// The files shipped so far, in the order of their first shipping, each with its path.
1816    shipped: Mutex<Vec<(Artifact, String)>>,
1817    /// The warnings of the template engine, each once, in the order first given.
1818    warnings: Mutex<Vec<String>>,
1819}
1820
1821impl Shipper {
1822    /// Returns the files shipped, in the order of their first shipping.
1823    fn take(&self) -> Vec<Artifact> {
1824        let mut shipped = self.shipped.lock().unwrap_or_else(PoisonError::into_inner);
1825        std::mem::take(&mut *shipped).into_iter().map(|(artifact, _)| artifact).collect()
1826    }
1827
1828    /// Returns the warnings of the template engine, each once, in the order first given.
1829    fn take_warnings(&self) -> Vec<String> {
1830        std::mem::take(&mut *self.warnings.lock().unwrap_or_else(PoisonError::into_inner))
1831    }
1832}
1833
1834impl TemplateShipper for Shipper {
1835    fn warn(&self, detail: String) {
1836        let mut warnings = self.warnings.lock().unwrap_or_else(PoisonError::into_inner);
1837        if !warnings.contains(&detail) {
1838            warnings.push(detail);
1839        }
1840    }
1841
1842    fn ship(&self, file: ShippedFile) -> Result<String, String> {
1843        let ShippedFile { stem, extension, media_type, bytes } = file;
1844        let Some(namer) = &self.namer else {
1845            return Err(format!("Missing naming of files for the shipped file ‘{stem}.{extension}’ (service slot ‘{NAMER_SLOT}’)"));
1846        };
1847        let mut digest = Fnv1a64::new();
1848        digest.write_bytes(&bytes);
1849        digest.write_str(&media_type);
1850        let id = ArtifactId::new(FEATURE, digest_name(&name_safe(&stem), &digest));
1851        let mut shipped = self.shipped.lock().unwrap_or_else(PoisonError::into_inner);
1852        if let Some((_, path)) = shipped.iter().find(|(artifact, _)| artifact.id == id) {
1853            return Ok(path.clone());
1854        }
1855        let named =
1856            ArtifactRef { id: &id, entry: false, media_type: &media_type, extension: Some(&extension), output: None, folder: false };
1857        let path = namer.url_of(&named, &self.scope).as_str().to_string();
1858        let artifact = Artifact::bytes(id, media_type, bytes).with_extension(extension);
1859        shipped.push((artifact, path.clone()));
1860        Ok(path)
1861    }
1862}
1863
1864/// Returns the metadata as a compose template reads it: see the [module
1865/// documentation](self#what-a-compose-template-reads).
1866fn meta_value(meta: &DocMeta) -> Value {
1867    let mut map = Map::new();
1868    if let Some(title) = &meta.title {
1869        map.insert(String::from("title"), Value::String(title.text.clone()));
1870    }
1871    if !meta.authors.is_empty() {
1872        map.insert(String::from(AUTHOR_KEY), Value::Array(meta.authors.iter().map(author_value).collect()));
1873    }
1874    if let Some(date) = &meta.date {
1875        map.insert(String::from("date"), Value::String(date.text.clone()));
1876    }
1877    for (key, value) in &meta.other {
1878        map.insert(key.clone(), value.clone());
1879    }
1880    Value::Object(map)
1881}
1882
1883/// Returns one author as a compose template reads it: a map holding `name`,
1884/// `affiliation` (a list), `email` (when the author has one), `note` (a list) and the
1885/// author's other keys, each text as the author wrote it.
1886fn author_value(author: &MetaAuthor) -> Value {
1887    let texts = |texts: &[MetaText]| Value::Array(texts.iter().map(|text| Value::String(text.text.clone())).collect());
1888    let mut map = Map::new();
1889    map.insert(String::from(NAME_KEY), Value::String(author.name.text.clone()));
1890    map.insert(String::from(AFFILIATION_KEY), texts(&author.affiliations));
1891    if let Some(email) = &author.email {
1892        map.insert(String::from(EMAIL_KEY), Value::String(email.text.clone()));
1893    }
1894    map.insert(String::from(NOTE_KEY), texts(&author.notes));
1895    for (key, value) in &author.other {
1896        map.insert(key.clone(), value.clone());
1897    }
1898    Value::Object(map)
1899}
1900
1901/// Returns the text of `region` as a compose template places it: on HTML, the content and
1902/// each piece inside the element that carries its name.
1903fn placed(output: &RegionsOutput, region: &Region) -> String {
1904    let name = region.name.as_str();
1905    let text = region.text();
1906    if is_html(output) && composed_kind(region) == Some(ComposedKind::Html) {
1907        region_element(name, &text)
1908    } else {
1909        text
1910    }
1911}
1912
1913/// Returns the identity of the file `artifact` that a compose template ships,
1914/// `compose:<name>`.
1915fn artifact_id(artifact: &TemplateArtifact) -> ArtifactId {
1916    ArtifactId::new(FEATURE, artifact.name())
1917}
1918
1919/// Returns what a compose template reads, from the output's regions, the metadata, the
1920/// compose template's settings and the paths of the files it ships.
1921fn context(
1922    output: &RegionsOutput,
1923    regions: &Regions,
1924    metadata: Value,
1925    config: Map<String, Value>,
1926    artifacts: Vec<(String, String)>,
1927) -> TemplateContext {
1928    let mut values = Vec::new();
1929    let mut pieces = Vec::new();
1930    for region in &regions.regions {
1931        let text = placed(output, region);
1932        if let Some(place) = region.piece {
1933            pieces.push(PieceValue {
1934                name: region.name.to_string(),
1935                place: String::from(place.as_str()),
1936                text: text.clone(),
1937                words: region.words.clone().unwrap_or_default(),
1938            });
1939        }
1940        values.push((region.name.to_string(), text));
1941    }
1942    TemplateContext { html: is_html(output), regions: values, pieces, metadata, config, artifacts }
1943}
1944
1945/// Returns how the composer's table on HTML holds `region`: the content and each piece as
1946/// HTML, the words of the page's title as words, and every other region not at all (it is
1947/// then part of the rest of the page, as each piece's words are). The regions in the table
1948/// and the rest of the page together make up the page, so this one rule decides both
1949/// ([`composed_regions`], [`context_with_regions_left_out`]).
1950fn composed_kind(region: &Region) -> Option<ComposedKind> {
1951    if region.piece.is_some() || region.name.as_str() == region::CONTENT {
1952        Some(ComposedKind::Html)
1953    } else if region.name.as_str() == region::TITLE {
1954        Some(ComposedKind::Words)
1955    } else {
1956        None
1957    }
1958}
1959
1960/// Returns `context` with exactly the regions of the composer's table left out
1961/// ([`composed_kind`]): the content and each piece placed in its element with nothing
1962/// inside, the title's words empty, and every other region (the stylesheets, the scripts,
1963/// the language) and each piece's words as in the page. Applying the compose template to
1964/// it gives the rest of the page.
1965fn context_with_regions_left_out(regions: &Regions, context: &TemplateContext) -> TemplateContext {
1966    let mut empty = context.clone();
1967    for (name, text) in &mut empty.regions {
1968        let Some(region) = regions.get(name) else { continue };
1969        match composed_kind(region) {
1970            Some(ComposedKind::Html) => *text = region_element(name, ""),
1971            Some(ComposedKind::Words) => text.clear(),
1972            None => {}
1973        }
1974    }
1975    for piece in &mut empty.pieces {
1976        piece.text = region_element(&piece.name, "");
1977    }
1978    empty
1979}
1980
1981/// Returns the composer's table on HTML, from the output's regions and the rest of the page
1982/// `skeleton`.
1983fn composed_regions(regions: &Regions, skeleton: String) -> ComposedRegions {
1984    let mut composed = Vec::new();
1985    for region in &regions.regions {
1986        let Some(kind) = composed_kind(region) else { continue };
1987        let text = match kind {
1988            ComposedKind::Html => region.text(),
1989            ComposedKind::Words => region.words.clone().unwrap_or_default(),
1990        };
1991        let name = region.name.as_str();
1992        composed.push(ComposedRegion { id: region_id(name), name: String::from(name), kind, text });
1993    }
1994    ComposedRegions { skeleton, regions: composed }
1995}
1996
1997#[cfg(test)]
1998mod tests {
1999    use super::*;
2000    use std::collections::hash_map::DefaultHasher;
2001
2002    fn hash_of(options: &ComposeOptions) -> u64 {
2003        let mut hasher = DefaultHasher::new();
2004        options.hash(&mut hasher);
2005        hasher.finish()
2006    }
2007
2008    #[test]
2009    fn two_equal_options_hash_equal_whatever_the_order_of_their_entries() {
2010        let with = |entries: &[(&str, Value)]| {
2011            let mut config = Map::new();
2012            for (key, value) in entries {
2013                config.insert(String::from(*key), value.clone());
2014            }
2015            let mut options = ComposeOptions::default();
2016            options.template_config.entry(String::from("html")).or_default().insert(String::from("simple"), config);
2017            options
2018        };
2019        let inner = |a: i64, b: i64| {
2020            let mut map = Map::new();
2021            map.insert(String::from("a"), Value::from(a));
2022            map.insert(String::from("b"), Value::from(b));
2023            map
2024        };
2025        let mut reversed = Map::new();
2026        reversed.insert(String::from("b"), Value::from(2));
2027        reversed.insert(String::from("a"), Value::from(1));
2028        let first = with(&[("x", Value::from("one")), ("y", Value::Object(inner(1, 2)))]);
2029        let second = with(&[("y", Value::Object(reversed)), ("x", Value::from("one"))]);
2030        assert_eq!(first, second);
2031        assert_eq!(hash_of(&first), hash_of(&second));
2032        let other = with(&[("x", Value::from("one")), ("y", Value::Object(inner(1, 3)))]);
2033        assert_ne!(hash_of(&first), hash_of(&other));
2034    }
2035
2036    #[test]
2037    fn a_repeated_warning_is_kept_once_in_the_order_first_given() {
2038        let shipper = Shipper { namer: None, scope: NamingScope::default(), shipped: Mutex::new(Vec::new()), warnings: Mutex::new(Vec::new()) };
2039        shipper.warn(String::from("first"));
2040        shipper.warn(String::from("second"));
2041        shipper.warn(String::from("first"));
2042        assert_eq!(shipper.take_warnings(), vec![String::from("first"), String::from("second")]);
2043    }
2044}