Skip to main content

einvoice_validator/rulesets/
catalogue.rs

1//! The catalogue of the rule sets fetched from their publishers: for each family, the
2//! files to download (pinned URL and checksum), the release directory its bundles are
3//! assembled in, and for each rule set its bundle and the manifest that bundle has,
4//! byte for byte the one the fetch script of the family writes.
5//!
6//! Every value that can change with a release is a pin of the fetch script, referred to
7//! by name (`{name}` in the templates below); nothing here repeats a version or a
8//! checksum.
9
10use std::fmt::Write as _;
11use std::sync::OnceLock;
12
13use super::pins::{self, Pins};
14use crate::{Error, Syntax};
15
16/// A digest algorithm of a pinned download.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub(crate) enum Algorithm {
19    Sha256,
20}
21
22/// A file a family downloads.
23#[derive(Debug)]
24pub(crate) struct SourceSpec {
25    /// What the file is, for messages (a template).
26    pub(crate) what: &'static str,
27    /// Its URL (a template).
28    pub(crate) url: &'static str,
29    /// Its file name in the download directory, as the fetch script names it (a
30    /// template).
31    pub(crate) file: &'static str,
32    pub(crate) algorithm: Algorithm,
33    /// The pin of its digest.
34    pub(crate) digest: &'static str,
35}
36
37/// How the bundles of a family are assembled.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub(crate) enum Kind {
40    FacturX,
41    XRechnung,
42    FrCtc,
43    Peppol,
44}
45
46/// A family of rule sets: the rule sets built from the same downloads, fetched
47/// together.
48#[derive(Debug)]
49pub(crate) struct FamilySpec {
50    pub(crate) kind: Kind,
51    /// Its name (`factur-x`): `rules fetch` accepts it for the whole family.
52    pub(crate) name: &'static str,
53    pub(crate) title: &'static str,
54    pub(crate) pins: Pins,
55    /// The directory its bundles are assembled in (a template), as the fetch script
56    /// names it under its output directory.
57    pub(crate) release: &'static str,
58    /// The version of its rule sets (a template).
59    pub(crate) version: &'static str,
60    /// Where its files come from (a template).
61    pub(crate) publisher: &'static str,
62    /// What is downloaded, in order.
63    pub(crate) sources: &'static [SourceSpec],
64}
65
66/// A rule set of a family.
67#[derive(Debug)]
68pub(crate) struct RuleSetSpec {
69    /// The name of its manifest, and of the rule set (`--rules`).
70    pub(crate) name: &'static str,
71    pub(crate) title: &'static str,
72    pub(crate) family: &'static FamilySpec,
73    /// Its bundle directory, relative to the release directory (empty: the release
74    /// directory itself).
75    pub(crate) dir: &'static str,
76    /// The syntax of the documents it validates, when it is UBL or CII.
77    pub(crate) syntax: Option<Syntax>,
78}
79
80// --- Factur-X ----------------------------------------------------------------------
81
82static FACTURX: FamilySpec = FamilySpec {
83    kind: Kind::FacturX,
84    name: "factur-x",
85    title: "Factur-X",
86    pins: pins::FACTURX,
87    release: "factur-x-{facturx}",
88    version: "{facturx}",
89    publisher: "the Mustang validator {mustang} (org.mustangproject:validator, Maven Central)",
90    sources: &[SourceSpec {
91        what: "the Mustang validator {mustang}",
92        url: "https://repo1.maven.org/maven2/org/mustangproject/validator/{mustang}/validator-{mustang}.jar",
93        file: "mustang-validator-{mustang}.jar",
94        algorithm: Algorithm::Sha256,
95        digest: "mustang_jar_sha256",
96    }],
97};
98
99/// The Factur-X profiles: bundle directory, Mustang file name, pins of the stylesheet
100/// and of its code list.
101pub(crate) const FACTURX_PROFILES: [(&str, &str, &str, &str); 5] = [
102    (
103        "minimum",
104        "MINIMUM",
105        "minimum_xslt_sha256",
106        "minimum_codedb_sha256",
107    ),
108    (
109        "basic-wl",
110        "BASIC-WL",
111        "basic_wl_xslt_sha256",
112        "basic_wl_codedb_sha256",
113    ),
114    ("basic", "BASIC", "basic_xslt_sha256", "basic_codedb_sha256"),
115    (
116        "en16931",
117        "EN16931",
118        "en16931_xslt_sha256",
119        "en16931_codedb_sha256",
120    ),
121    (
122        "extended",
123        "EXTENDED",
124        "extended_xslt_sha256",
125        "extended_codedb_sha256",
126    ),
127];
128
129// --- XRechnung ---------------------------------------------------------------------
130
131static XRECHNUNG: FamilySpec = FamilySpec {
132    kind: Kind::XRechnung,
133    name: "xrechnung",
134    title: "XRechnung",
135    pins: pins::XRECHNUNG,
136    release: "xrechnung-{xrechnung}",
137    version: "{xrechnung}",
138    publisher: "the KoSIT validator configuration {configuration} for XRechnung {xrechnung} (projekte.kosit.org)",
139    sources: &[SourceSpec {
140        what: "the XRechnung {xrechnung} validator configuration {configuration}",
141        url: "https://projekte.kosit.org/api/v4/projects/356/packages/maven/de/xeinkauf/xrechnung-{xrechnung}-validator-configuration/{configuration}/xrechnung-{xrechnung}-validator-configuration-{configuration}.zip",
142        file: "xrechnung-{xrechnung}-validator-configuration-{configuration}.zip",
143        algorithm: Algorithm::Sha256,
144        digest: "configuration_sha256",
145    }],
146};
147
148/// The stylesheets of the configuration: name in the bundles, path in the
149/// configuration (a template), pin of its SHA-256, pin of its version.
150pub(crate) const XRECHNUNG_STYLESHEETS: [(&str, &str, &str, &str); 4] = [
151    (
152        "EN16931-UBL",
153        "resources/ubl/2.1/xsl/EN16931-UBL-validation.xsl",
154        "cen_ubl_sha256",
155        "cen",
156    ),
157    (
158        "XRechnung-UBL",
159        "resources/xrechnung/{xrechnung}/xsl/XRechnung-UBL-validation.xsl",
160        "xrechnung_ubl_sha256",
161        "schematron",
162    ),
163    (
164        "EN16931-CII",
165        "resources/cii/16b/xsl/EN16931-CII-validation.xsl",
166        "cen_cii_sha256",
167        "cen",
168    ),
169    (
170        "XRechnung-CII",
171        "resources/xrechnung/{xrechnung}/xsl/XRechnung-CII-validation.xsl",
172        "xrechnung_cii_sha256",
173        "schematron",
174    ),
175];
176
177/// The namespaces of the UBL invoice scenarios of the configuration, as their
178/// `namespace` elements bind them (`rep` is the namespace of its validation reports).
179const XRECHNUNG_UBL_INVOICE_NAMESPACES: &str = "cbc=urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2 invoice=urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 rep=http://www.xoev.de/de/validator/varl/1";
180/// The namespaces of the UBL credit note scenarios.
181const XRECHNUNG_UBL_CREDIT_NOTE_NAMESPACES: &str = "cbc=urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2 creditnote=urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2 rep=http://www.xoev.de/de/validator/varl/1";
182/// The namespaces of the CII scenarios.
183const XRECHNUNG_CII_NAMESPACES: &str = "rsm=urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100 ram=urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100 rep=http://www.xoev.de/de/validator/varl/1";
184
185/// A scenario of the configuration: syntax of the bundle, name, namespaces (`prefix=uri`
186/// pairs), its `match` expression as written, the stylesheets it runs (bundle names, in
187/// order), and the rule ids of the levels error, warning and information (separated by
188/// spaces).
189type XRechnungScenario = (
190    &'static str,
191    &'static str,
192    &'static str,
193    &'static str,
194    &'static str,
195    &'static str,
196    &'static str,
197    &'static str,
198);
199
200/// The scenarios of the configuration (`scenarios.xml`), in its order, as
201/// `scripts/fetch-xrechnung.sh` lists them: the `[[scenario]]` tables of the bundles
202/// (`fatal`, `warning`, `other`), each in the bundle of its syntax.
203pub(crate) const XRECHNUNG_SCENARIOS: [XRechnungScenario; 11] = [
204    (
205        "ubl",
206        "EN16931 XRechnung (UBL Invoice)",
207        XRECHNUNG_UBL_INVOICE_NAMESPACES,
208        "exists(/invoice:Invoice/cbc:CustomizationID[ . = 'urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0']) ",
209        "EN16931-UBL XRechnung-UBL",
210        "UBL-CR-646",
211        "BR-CL-23 BR-CL-21",
212        "",
213    ),
214    (
215        "ubl",
216        "EN16931 XRechnung Extension (UBL Invoice)",
217        XRECHNUNG_UBL_INVOICE_NAMESPACES,
218        "exists(/invoice:Invoice/cbc:CustomizationID[ . = 'urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0#conformant#urn:xeinkauf.de:kosit:extension:xrechnung_3.0'])",
219        "EN16931-UBL XRechnung-UBL",
220        "",
221        "BR-CL-23",
222        "BR-CL-21 BR-CL-24 BR-CL-10 BR-CL-11 BR-CL-25 BR-CL-26 BR-CO-16 UBL-CR-470 UBL-CR-646",
223    ),
224    (
225        "ubl",
226        "EN16931 XRechnung CVD (UBL Invoice)",
227        XRECHNUNG_UBL_INVOICE_NAMESPACES,
228        "exists(/invoice:Invoice/cbc:CustomizationID[ . = 'urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0#compliant#urn:xeinkauf.de:kosit:xrechnung:cvd_0.9']) ",
229        "EN16931-UBL XRechnung-UBL",
230        "UBL-CR-646",
231        "BR-CL-23 BR-CL-21",
232        "BR-CL-13",
233    ),
234    (
235        "ubl",
236        "EN16931 XRechnung (UBL CreditNote)",
237        XRECHNUNG_UBL_CREDIT_NOTE_NAMESPACES,
238        "exists(/creditnote:CreditNote[ cbc:CustomizationID/text() = 'urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0'])",
239        "EN16931-UBL XRechnung-UBL",
240        "",
241        "BR-CL-23 BR-CL-21",
242        "",
243    ),
244    (
245        "ubl",
246        "EN16931 XRechnung CVD (UBL CreditNote)",
247        XRECHNUNG_UBL_CREDIT_NOTE_NAMESPACES,
248        "exists(/creditnote:CreditNote[ cbc:CustomizationID/text() = 'urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0#compliant#urn:xeinkauf.de:kosit:xrechnung:cvd_0.9'])",
249        "EN16931-UBL XRechnung-UBL",
250        "UBL-CR-646",
251        "BR-CL-23 BR-CL-21",
252        "BR-CL-13",
253    ),
254    (
255        "cii",
256        "EN16931 XRechnung (CII)",
257        XRECHNUNG_CII_NAMESPACES,
258        "exists(/rsm:CrossIndustryInvoice[rsm:ExchangedDocumentContext/ram:GuidelineSpecifiedDocumentContextParameter/ram:ID/text() = 'urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0'])",
259        "EN16931-CII XRechnung-CII",
260        "CII-SR-452 CII-SR-453 CII-SR-454 CII-SR-465 CII-SR-466",
261        "BR-CL-23 BR-CL-21",
262        "CII-SR-475 CII-SR-476",
263    ),
264    (
265        "cii",
266        "EN16931 XRechnung Extension (CII)",
267        XRECHNUNG_CII_NAMESPACES,
268        "exists(/rsm:CrossIndustryInvoice[rsm:ExchangedDocumentContext/ram:GuidelineSpecifiedDocumentContextParameter/ram:ID/text() = 'urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0#conformant#urn:xeinkauf.de:kosit:extension:xrechnung_3.0'])",
269        "EN16931-CII XRechnung-CII",
270        "CII-SR-452 CII-SR-453 CII-SR-454 CII-SR-465 CII-SR-466",
271        "BR-CL-23",
272        "BR-CL-21 BR-CL-11 BR-CL-10 BR-CL-24 BR-CL-25 BR-CL-26 CII-SR-475 CII-SR-476",
273    ),
274    (
275        "cii",
276        "EN16931 XRechnung CVD (CII)",
277        XRECHNUNG_CII_NAMESPACES,
278        "exists(/rsm:CrossIndustryInvoice[rsm:ExchangedDocumentContext/ram:GuidelineSpecifiedDocumentContextParameter/ram:ID/text() = 'urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0#compliant#urn:xeinkauf.de:kosit:xrechnung:cvd_0.9'])",
279        "EN16931-CII XRechnung-CII",
280        "CII-SR-452 CII-SR-453 CII-SR-454 CII-SR-465 CII-SR-466",
281        "BR-CL-23 BR-CL-21",
282        "BR-CL-13 CII-SR-475 CII-SR-476",
283    ),
284    (
285        "ubl",
286        "EN16931 (UBL Invoice)",
287        XRECHNUNG_UBL_INVOICE_NAMESPACES,
288        "exists(/invoice:Invoice[ cbc:CustomizationID/text() = 'urn:cen.eu:en16931:2017' ])",
289        "EN16931-UBL",
290        "",
291        "",
292        "",
293    ),
294    (
295        "ubl",
296        "EN16931 (UBL CreditNote)",
297        XRECHNUNG_UBL_CREDIT_NOTE_NAMESPACES,
298        "exists(/creditnote:CreditNote[cbc:CustomizationID/text() = 'urn:cen.eu:en16931:2017'])",
299        "EN16931-UBL",
300        "",
301        "",
302        "",
303    ),
304    (
305        "cii",
306        "EN16931 (CII)",
307        XRECHNUNG_CII_NAMESPACES,
308        "exists(/rsm:CrossIndustryInvoice[ rsm:ExchangedDocumentContext/ram:GuidelineSpecifiedDocumentContextParameter/ram:ID/text() = 'urn:cen.eu:en16931:2017'])",
309        "EN16931-CII",
310        "",
311        "",
312        "",
313    ),
314];
315
316// --- The French rules --------------------------------------------------------------
317
318static FR_CTC: FamilySpec = FamilySpec {
319    kind: Kind::FrCtc,
320    name: "fr-ctc",
321    title: "French e-invoicing rules (FNFE-MPE)",
322    pins: pins::FR_CTC,
323    release: "fr-ctc-{pack}",
324    version: "{pack}",
325    publisher: "the FNFE-MPE package Schematrons FR CTC {pack} (fnfe-mpe.org)",
326    sources: &[SourceSpec {
327        what: "the FNFE-MPE package {pack}",
328        url: "https://fnfe-mpe.org/wp-content/uploads/2026/09/2026_09_04_FNFE_SCHEMATRONS_FR_CTC_V{pack}.zip",
329        file: "2026_09_04_FNFE_SCHEMATRONS_FR_CTC_V{pack}.zip",
330        algorithm: Algorithm::Sha256,
331        digest: "pack_sha256",
332    }],
333};
334
335/// The top directory of the package (a template).
336#[cfg(feature = "fetch")]
337pub(crate) const FR_CTC_PACK_DIR: &str = "2026_09_04_FNFE_SCHEMATRONS_FR_CTC_V{pack}";
338
339/// The stylesheets the bundles name: name in the bundles, path in the package, pin of
340/// its SHA-256, pin of the SHA-256 of the code list it reads with `document()` (named
341/// after it: `<path without .xslt>_codedb.xml`).
342pub(crate) const FR_CTC_STYLESHEETS: [(&str, &str, &str, Option<&str>); 14] = [
343    (
344        "EN16931-CII",
345        "CII/EN16931/2xslt/EN16931-CII-validation.xslt",
346        "cii_en16931_sha256",
347        None,
348    ),
349    (
350        "EXTENDED-CTC-FR-CII",
351        "CII/EXTENDED-CTC-FR/2xslt/EXTENDED-CTC-FR-CII.xslt",
352        "cii_extended_ctc_fr_sha256",
353        None,
354    ),
355    (
356        "BR-FR-Flux2-CII",
357        "CII/EN16931/2xslt/BR-FR-Flux2-Schematron-CII.xslt",
358        "cii_br_fr_sha256",
359        None,
360    ),
361    (
362        "BR-FR-Flux2-CII_WARNING",
363        "CII/EN16931/2xslt/BR-FR-Flux2-Schematron-CII_WARNING.xslt",
364        "cii_br_fr_warning_sha256",
365        None,
366    ),
367    (
368        "EN16931-UBL",
369        "UBL/EN16931/2xslt/EN16931-UBL-validation.xslt",
370        "ubl_en16931_sha256",
371        None,
372    ),
373    (
374        "EXTENDED-CTC-FR-UBL",
375        "UBL/EXTENDED-CTC-FR/2xslt/EXTENDED-CTC-FR-UBL.xslt",
376        "ubl_extended_ctc_fr_sha256",
377        None,
378    ),
379    (
380        "BR-FR-Flux2-UBL",
381        "UBL/EN16931/2xslt/BR-FR-Flux2-Schematron-UBL.xslt",
382        "ubl_br_fr_sha256",
383        None,
384    ),
385    (
386        "BR-FR-Flux2-UBL_WARNING",
387        "UBL/EN16931/2xslt/BR-FR-Flux2-Schematron-UBL_WARNING.xslt",
388        "ubl_br_fr_warning_sha256",
389        None,
390    ),
391    (
392        "BR-FR-CDV-CDAR",
393        "CDAR/2xslt/BR-FR-CDV-Schematron-CDAR.xslt",
394        "cdar_sha256",
395        None,
396    ),
397    (
398        "BR-FR-CDV-CDAR_WARNING",
399        "CDAR/2xslt/BR-FR-CDV-Schematron-CDAR_WARNING.xslt",
400        "cdar_warning_sha256",
401        None,
402    ),
403    ("Flux10", "Flux10/Flux10.xslt", "flux10_sha256", None),
404    (
405        "FACTUR-X_BASIC-WL",
406        "Factur-X_1.09.2.fixFR04/BASICWL/2xslt/FACTUR-X_BASIC-WL.xslt",
407        "fx_basic_wl_sha256",
408        Some("fx_basic_wl_codedb_sha256"),
409    ),
410    (
411        "FACTUR-X_EN16931",
412        "Factur-X_1.09.2.fixFR04/EN16931/2xslt/FACTUR-X_EN16931.xslt",
413        "fx_en16931_sha256",
414        Some("fx_en16931_codedb_sha256"),
415    ),
416    (
417        "FACTUR-X_EXTENDED",
418        "Factur-X_1.09.2.fixFR04/EXTENDED/2xslt/FACTUR-X_EXTENDED.xslt",
419        "fx_extended_sha256",
420        Some("fx_extended_codedb_sha256"),
421    ),
422];
423
424/// The bundles of the French rules: directory, whether it validates against the UBL
425/// 2.1 schema, title, stylesheets in order.
426pub(crate) const FR_CTC_BUNDLES: [(&str, bool, &str, &[&str]); 14] = [
427    (
428        "cii-en16931",
429        false,
430        "EN 16931 CII and the French rules",
431        &["EN16931-CII", "BR-FR-Flux2-CII"],
432    ),
433    (
434        "cii-en16931-warning",
435        false,
436        "EN 16931 CII and the French rules (WARNING version)",
437        &["EN16931-CII", "BR-FR-Flux2-CII_WARNING"],
438    ),
439    (
440        "cii-extended-ctc-fr",
441        false,
442        "EXTENDED-CTC-FR CII and the French rules",
443        &["EXTENDED-CTC-FR-CII", "BR-FR-Flux2-CII"],
444    ),
445    (
446        "cii-extended-ctc-fr-warning",
447        false,
448        "EXTENDED-CTC-FR CII and the French rules (WARNING version)",
449        &["EXTENDED-CTC-FR-CII", "BR-FR-Flux2-CII_WARNING"],
450    ),
451    (
452        "ubl-en16931",
453        true,
454        "EN 16931 UBL and the French rules",
455        &["EN16931-UBL", "BR-FR-Flux2-UBL"],
456    ),
457    (
458        "ubl-en16931-warning",
459        true,
460        "EN 16931 UBL and the French rules (WARNING version)",
461        &["EN16931-UBL", "BR-FR-Flux2-UBL_WARNING"],
462    ),
463    (
464        "ubl-extended-ctc-fr",
465        true,
466        "EXTENDED-CTC-FR UBL and the French rules",
467        &["EXTENDED-CTC-FR-UBL", "BR-FR-Flux2-UBL"],
468    ),
469    (
470        "ubl-extended-ctc-fr-warning",
471        true,
472        "EXTENDED-CTC-FR UBL and the French rules (WARNING version)",
473        &["EXTENDED-CTC-FR-UBL", "BR-FR-Flux2-UBL_WARNING"],
474    ),
475    (
476        "cdar",
477        false,
478        "Life-cycle statuses (CDAR)",
479        &["BR-FR-CDV-CDAR"],
480    ),
481    (
482        "cdar-warning",
483        false,
484        "Life-cycle statuses (CDAR, WARNING version)",
485        &["BR-FR-CDV-CDAR_WARNING"],
486    ),
487    (
488        "factur-x-basic-wl",
489        false,
490        "Factur-X BASIC WL and the French rules",
491        &["FACTUR-X_BASIC-WL", "BR-FR-Flux2-CII"],
492    ),
493    (
494        "factur-x-en16931",
495        false,
496        "Factur-X EN16931 and the French rules",
497        &["FACTUR-X_EN16931", "BR-FR-Flux2-CII"],
498    ),
499    (
500        "factur-x-extended",
501        false,
502        "Factur-X EXTENDED and the French rules",
503        &["FACTUR-X_EXTENDED", "BR-FR-Flux2-CII"],
504    ),
505    ("flux10", false, "E-reporting (Flux 10)", &["Flux10"]),
506];
507
508/// Whether the stylesheet `name` of the package is a Factur-X profile (`FACTUR-X_<P>`),
509/// whose failed asserts without a flag are fatal, as the Mustang validator reads them.
510pub(crate) fn fr_ctc_factur_x(name: &str) -> bool {
511    name.starts_with("FACTUR-X_")
512}
513
514/// The code list a Factur-X stylesheet of the package reads: its path, from the
515/// stylesheet's.
516pub(crate) fn fr_ctc_side_file(path: &str) -> Option<String> {
517    let base = path.rsplit('/').next().unwrap_or(path);
518    if base.starts_with("FACTUR-X_") && path.contains('/') {
519        path.strip_suffix(".xslt")
520            .map(|p| format!("{p}_codedb.xml"))
521    } else {
522        None
523    }
524}
525
526// --- Peppol BIS Billing 3.0 ---------------------------------------------------------
527
528static PEPPOL: FamilySpec = FamilySpec {
529    kind: Kind::Peppol,
530    name: "peppol",
531    title: "Peppol BIS Billing",
532    pins: pins::PEPPOL,
533    release: "peppol-bis-billing-ubl-{tag}",
534    version: "{tag}",
535    publisher: "the Peppol BIS Billing {tag} release (OpenPeppol, github.com), its Schematron compiled as ph-schematron {plugin} compiles it, with the ISO Schematron skeleton of ph-schematron-isosch {plugin} (Maven Central)",
536    sources: &[
537        SourceSpec {
538            what: "the Peppol BIS Billing {tag} release archive",
539            url: "https://github.com/OpenPeppol/peppol-bis-invoice-3/archive/refs/tags/{tag}.tar.gz",
540            file: "peppol-bis-invoice-3-{tag}.tar.gz",
541            algorithm: Algorithm::Sha256,
542            digest: "archive_sha256",
543        },
544        SourceSpec {
545            what: "the ISO Schematron skeleton of ph-schematron-isosch {plugin}",
546            url: "https://repo1.maven.org/maven2/com/helger/schematron/ph-schematron-isosch/{plugin}/ph-schematron-isosch-{plugin}.jar",
547            file: "ph-schematron-isosch-{plugin}.jar",
548            algorithm: Algorithm::Sha256,
549            digest: "isosch_sha256",
550        },
551    ],
552};
553
554/// The two compiled stylesheets of Peppol, in the order they run: name (and file name
555/// without `.xslt`), pin of the SHA-256 of the compiled file.
556#[cfg(feature = "fetch")]
557pub(crate) const PEPPOL_STYLESHEETS: [(&str, &str); 2] = [
558    ("CEN-EN16931-UBL", "cen_xslt_sha256"),
559    ("PEPPOL-EN16931-UBL", "peppol_xslt_sha256"),
560];
561
562// --- The rule sets -----------------------------------------------------------------
563
564const fn rule_set(
565    name: &'static str,
566    title: &'static str,
567    family: &'static FamilySpec,
568    dir: &'static str,
569    syntax: Option<Syntax>,
570) -> RuleSetSpec {
571    RuleSetSpec {
572        name,
573        title,
574        family,
575        dir,
576        syntax,
577    }
578}
579
580const CII: Option<Syntax> = Some(Syntax::Cii);
581const UBL: Option<Syntax> = Some(Syntax::Ubl);
582
583/// Every fetched rule set, by family.
584pub(crate) static RULE_SETS: [RuleSetSpec; 22] = [
585    rule_set(
586        "factur-x-minimum",
587        "Factur-X MINIMUM",
588        &FACTURX,
589        "minimum",
590        CII,
591    ),
592    rule_set(
593        "factur-x-basic-wl",
594        "Factur-X BASIC-WL",
595        &FACTURX,
596        "basic-wl",
597        CII,
598    ),
599    rule_set("factur-x-basic", "Factur-X BASIC", &FACTURX, "basic", CII),
600    rule_set(
601        "factur-x-en16931",
602        "Factur-X EN16931",
603        &FACTURX,
604        "en16931",
605        CII,
606    ),
607    rule_set(
608        "factur-x-extended",
609        "Factur-X EXTENDED",
610        &FACTURX,
611        "extended",
612        CII,
613    ),
614    rule_set("xrechnung-ubl", "XRechnung UBL", &XRECHNUNG, "ubl", UBL),
615    rule_set("xrechnung-cii", "XRechnung CII", &XRECHNUNG, "cii", CII),
616    rule_set(
617        "fr-ctc-cii-en16931",
618        FR_CTC_BUNDLES[0].2,
619        &FR_CTC,
620        FR_CTC_BUNDLES[0].0,
621        CII,
622    ),
623    rule_set(
624        "fr-ctc-cii-en16931-warning",
625        FR_CTC_BUNDLES[1].2,
626        &FR_CTC,
627        FR_CTC_BUNDLES[1].0,
628        CII,
629    ),
630    rule_set(
631        "fr-ctc-cii-extended-ctc-fr",
632        FR_CTC_BUNDLES[2].2,
633        &FR_CTC,
634        FR_CTC_BUNDLES[2].0,
635        CII,
636    ),
637    rule_set(
638        "fr-ctc-cii-extended-ctc-fr-warning",
639        FR_CTC_BUNDLES[3].2,
640        &FR_CTC,
641        FR_CTC_BUNDLES[3].0,
642        CII,
643    ),
644    rule_set(
645        "fr-ctc-ubl-en16931",
646        FR_CTC_BUNDLES[4].2,
647        &FR_CTC,
648        FR_CTC_BUNDLES[4].0,
649        UBL,
650    ),
651    rule_set(
652        "fr-ctc-ubl-en16931-warning",
653        FR_CTC_BUNDLES[5].2,
654        &FR_CTC,
655        FR_CTC_BUNDLES[5].0,
656        UBL,
657    ),
658    rule_set(
659        "fr-ctc-ubl-extended-ctc-fr",
660        FR_CTC_BUNDLES[6].2,
661        &FR_CTC,
662        FR_CTC_BUNDLES[6].0,
663        UBL,
664    ),
665    rule_set(
666        "fr-ctc-ubl-extended-ctc-fr-warning",
667        FR_CTC_BUNDLES[7].2,
668        &FR_CTC,
669        FR_CTC_BUNDLES[7].0,
670        UBL,
671    ),
672    rule_set(
673        "fr-ctc-cdar",
674        FR_CTC_BUNDLES[8].2,
675        &FR_CTC,
676        FR_CTC_BUNDLES[8].0,
677        None,
678    ),
679    rule_set(
680        "fr-ctc-cdar-warning",
681        FR_CTC_BUNDLES[9].2,
682        &FR_CTC,
683        FR_CTC_BUNDLES[9].0,
684        None,
685    ),
686    rule_set(
687        "fr-ctc-factur-x-basic-wl",
688        FR_CTC_BUNDLES[10].2,
689        &FR_CTC,
690        FR_CTC_BUNDLES[10].0,
691        CII,
692    ),
693    rule_set(
694        "fr-ctc-factur-x-en16931",
695        FR_CTC_BUNDLES[11].2,
696        &FR_CTC,
697        FR_CTC_BUNDLES[11].0,
698        CII,
699    ),
700    rule_set(
701        "fr-ctc-factur-x-extended",
702        FR_CTC_BUNDLES[12].2,
703        &FR_CTC,
704        FR_CTC_BUNDLES[12].0,
705        CII,
706    ),
707    rule_set(
708        "fr-ctc-flux10",
709        FR_CTC_BUNDLES[13].2,
710        &FR_CTC,
711        FR_CTC_BUNDLES[13].0,
712        None,
713    ),
714    rule_set(
715        "peppol-bis-billing-ubl",
716        "Peppol BIS Billing 3.0 UBL",
717        &PEPPOL,
718        "",
719        UBL,
720    ),
721];
722
723/// Every family, in the order of the catalogue.
724#[cfg(any(test, feature = "fetch"))]
725pub(crate) static FAMILIES: [&FamilySpec; 4] = [&FACTURX, &XRECHNUNG, &FR_CTC, &PEPPOL];
726
727/// The rule sets an alias stands for: for a syntax, or for any (`None`).
728pub(crate) type AliasTargets = &'static [(Option<Syntax>, &'static str)];
729
730/// Names that stand for rule sets: a family for `rules fetch`, and for validation the
731/// rule set of the document's syntax (the first of the list when it is neither).
732pub(crate) const ALIASES: [(&str, AliasTargets); 2] = [
733    ("peppol", &[(None, "peppol-bis-billing-ubl")]),
734    (
735        "xrechnung",
736        &[(UBL, "xrechnung-ubl"), (CII, "xrechnung-cii")],
737    ),
738];
739
740// --- Resolution --------------------------------------------------------------------
741
742/// A pinned download, resolved.
743#[derive(Debug, Clone, PartialEq, Eq)]
744pub struct Source {
745    what: String,
746    url: String,
747    file: String,
748    algorithm: Algorithm,
749    digest: String,
750}
751
752impl Source {
753    /// What the file is (`the Mustang validator 2.26.0`).
754    #[must_use]
755    pub fn what(&self) -> &str {
756        &self.what
757    }
758
759    /// The URL it is downloaded from, at its publisher.
760    #[must_use]
761    pub fn url(&self) -> &str {
762        &self.url
763    }
764
765    /// Its file name, as the fetch scripts of the repository name it in their download
766    /// directory (what `FetchOptions::from_dir`, feature `fetch`, looks
767    /// for).
768    #[must_use]
769    pub fn file(&self) -> &str {
770        &self.file
771    }
772
773    /// `SHA-256`: the digest pinned for it.
774    #[must_use]
775    pub const fn algorithm(&self) -> &'static str {
776        match self.algorithm {
777            Algorithm::Sha256 => "SHA-256",
778        }
779    }
780
781    #[cfg(any(test, feature = "fetch"))]
782    pub(crate) const fn algorithm_kind(&self) -> Algorithm {
783        self.algorithm
784    }
785
786    /// The pinned digest, lower-case hexadecimal.
787    #[must_use]
788    pub fn digest(&self) -> &str {
789        &self.digest
790    }
791
792    /// A source of the tests.
793    #[cfg(all(test, feature = "fetch"))]
794    pub(crate) fn for_test(url: &str, file: &str, sha256: &str) -> Self {
795        Self {
796            what: format!("test file {file}"),
797            url: url.to_owned(),
798            file: file.to_owned(),
799            algorithm: Algorithm::Sha256,
800            digest: sha256.to_owned(),
801        }
802    }
803}
804
805/// A rule set this crate fetches from its publisher on demand
806/// ([`RuleSetCache`](crate::RuleSetCache)): its files are not redistributed by the
807/// project. Each is one bundle of a family; the rule sets of a family come from the
808/// same downloads and are fetched together.
809#[derive(Debug)]
810pub struct FetchedRuleSet {
811    pub(crate) spec: &'static RuleSetSpec,
812    version: String,
813    release: String,
814    publisher: String,
815    sources: Vec<Source>,
816    manifest: String,
817}
818
819impl FetchedRuleSet {
820    /// Its name, as `--rules` and [`Validator::from_cache`](crate::Validator::from_cache)
821    /// take it, and as its manifest gives it (`factur-x-en16931`).
822    #[must_use]
823    pub const fn name(&self) -> &'static str {
824        self.spec.name
825    }
826
827    /// Its title (`Factur-X EN16931`).
828    #[must_use]
829    pub const fn title(&self) -> &'static str {
830        self.spec.title
831    }
832
833    /// The version of the official artefacts (`1.09.2`).
834    #[must_use]
835    pub fn version(&self) -> &str {
836        &self.version
837    }
838
839    /// The name of its family (`factur-x`, `xrechnung`, `fr-ctc`, `peppol`), which
840    /// `RuleSetCache::fetch` (feature `fetch`) also takes.
841    #[must_use]
842    pub const fn family(&self) -> &'static str {
843        self.spec.family.name
844    }
845
846    /// The title of its family (`Factur-X`).
847    #[must_use]
848    pub const fn family_title(&self) -> &'static str {
849        self.spec.family.title
850    }
851
852    /// Where its files come from.
853    #[must_use]
854    pub fn publisher(&self) -> &str {
855        &self.publisher
856    }
857
858    /// The files fetched for its family, with their pinned URLs and digests.
859    #[must_use]
860    pub fn sources(&self) -> &[Source] {
861        &self.sources
862    }
863
864    /// The syntax of the documents it validates, when it is UBL or CII.
865    #[must_use]
866    pub const fn syntax(&self) -> Option<Syntax> {
867        self.spec.syntax
868    }
869
870    /// The directory of its bundle, relative to the cache's rule-set directory:
871    /// `<release>/<bundle>` (`factur-x-1.09.2/en16931`), as the fetch script of its
872    /// family lays it out under its output directory.
873    #[must_use]
874    pub fn bundle_path(&self) -> String {
875        if self.spec.dir.is_empty() {
876            self.release.clone()
877        } else {
878            format!("{}/{}", self.release, self.spec.dir)
879        }
880    }
881
882    /// The release directory of its family, relative to the cache's rule-set directory.
883    #[cfg(any(test, feature = "fetch"))]
884    pub(crate) fn release(&self) -> &str {
885        &self.release
886    }
887
888    /// The manifest of its bundle (`bundle.toml`), as the fetch script writes it.
889    #[must_use]
890    pub fn manifest(&self) -> &str {
891        &self.manifest
892    }
893}
894
895static CATALOGUE: OnceLock<Result<Vec<FetchedRuleSet>, String>> = OnceLock::new();
896
897/// Every rule set fetched on demand, in the order of the catalogue: the five Factur-X
898/// profiles, XRechnung UBL and CII, the fourteen bundles of the French rules, Peppol BIS
899/// Billing 3.0.
900///
901/// # Errors
902///
903/// [`Error::Internal`] if the embedded catalogue does not resolve against its pins, which
904/// a test rules out.
905pub fn fetched_rule_sets() -> Result<&'static [FetchedRuleSet], Error> {
906    CATALOGUE
907        .get_or_init(resolve_all)
908        .as_deref()
909        .map_err(|e| Error::internal(format!("the rule-set catalogue: {e}")))
910}
911
912/// The fetched rule set named `name`, or the one an alias names for a document of
913/// `syntax` (`peppol`; `xrechnung`, which is `xrechnung-ubl` or `xrechnung-cii`).
914///
915/// # Errors
916///
917/// As [`fetched_rule_sets`].
918pub fn fetched_rule_set(
919    name: &str,
920    syntax: Option<Syntax>,
921) -> Result<Option<&'static FetchedRuleSet>, Error> {
922    let all = fetched_rule_sets()?;
923    let name = ALIASES
924        .iter()
925        .find(|(alias, _)| *alias == name)
926        .map_or(name, |(_, targets)| {
927            targets
928                .iter()
929                .find(|(s, _)| s.is_some() && *s == syntax)
930                .or_else(|| targets.first())
931                .map_or(name, |(_, target)| *target)
932        });
933    Ok(all.iter().find(|r| r.name() == name))
934}
935
936/// The aliases [`fetched_rule_set`] takes besides the names of the rule sets: `peppol`
937/// (`peppol-bis-billing-ubl`) and `xrechnung` (`xrechnung-ubl` or `xrechnung-cii`, by
938/// syntax).
939#[must_use]
940pub fn fetched_rule_set_aliases() -> Vec<&'static str> {
941    ALIASES.iter().map(|(alias, _)| *alias).collect()
942}
943
944/// The rule sets that `name` names for fetching: one rule set, an alias, or a family
945/// (every rule set of it). Empty for an unknown name.
946#[cfg(any(test, feature = "fetch"))]
947pub(crate) fn named(name: &str) -> Result<Vec<&'static FetchedRuleSet>, Error> {
948    let all = fetched_rule_sets()?;
949    if let Some((_, targets)) = ALIASES.iter().find(|(alias, _)| *alias == name) {
950        return Ok(all
951            .iter()
952            .filter(|r| targets.iter().any(|(_, t)| *t == r.name()))
953            .collect());
954    }
955    if FAMILIES.iter().any(|f| f.name == name) {
956        return Ok(all.iter().filter(|r| r.family() == name).collect());
957    }
958    Ok(all.iter().filter(|r| r.name() == name).collect())
959}
960
961fn resolve_all() -> Result<Vec<FetchedRuleSet>, String> {
962    RULE_SETS.iter().map(resolve).collect()
963}
964
965fn resolve(spec: &'static RuleSetSpec) -> Result<FetchedRuleSet, String> {
966    let family = spec.family;
967    let pins = family.pins;
968    let sources = family
969        .sources
970        .iter()
971        .map(|s| {
972            Ok(Source {
973                what: pins.expand(s.what)?,
974                url: pins.expand(s.url)?,
975                file: pins.expand(s.file)?,
976                algorithm: s.algorithm,
977                digest: pins.get(s.digest)?.to_owned(),
978            })
979        })
980        .collect::<Result<Vec<_>, String>>()?;
981    Ok(FetchedRuleSet {
982        spec,
983        version: pins.expand(family.version)?,
984        release: pins.expand(family.release)?,
985        publisher: pins.expand(family.publisher)?,
986        sources,
987        manifest: manifest(spec)?,
988    })
989}
990
991// --- Manifests ----------------------------------------------------------------------
992
993/// The manifest of the bundle of `spec`, as the fetch script of its family writes it.
994fn manifest(spec: &RuleSetSpec) -> Result<String, String> {
995    match spec.family.kind {
996        Kind::FacturX => manifest_facturx(spec),
997        Kind::XRechnung => manifest_xrechnung(spec),
998        Kind::FrCtc => manifest_fr_ctc(spec),
999        Kind::Peppol => manifest_peppol(spec),
1000    }
1001}
1002
1003/// As `scripts/fetch-facturx.sh` writes it.
1004fn manifest_facturx(spec: &RuleSetSpec) -> Result<String, String> {
1005    let p = |name: &str| spec.family.pins.get(name);
1006    let (dir, file, xslt, codedb) = FACTURX_PROFILES
1007        .iter()
1008        .find(|(dir, ..)| *dir == spec.dir)
1009        .ok_or_else(|| format!("{}: no Factur-X profile", spec.name))?;
1010    let (facturx, mustang) = (p("facturx")?, p("mustang")?);
1011    Ok(format!(
1012        "# Factur-X {facturx}, profile {file}, from the Mustang validator {mustang}: the
1013# rule-set bundle manifest of einvoice-validator, as scripts/fetch-facturx.sh and
1014# einvoice-validate rules fetch write it (einvoice-validate --bundle DIR). The
1015# stylesheet reads, with document(), the code list FACTUR-X_{file}_codedb.xml
1016# next to it, a resource of the bundle. A failed assert without a flag is fatal,
1017# as the Mustang validator reads the report.
1018format = 2
1019name = \"factur-x-{dir}\"
1020title = \"Factur-X {file}\"
1021version = \"{facturx}\"
1022
1023[[stylesheet]]
1024name = \"FACTUR-X_{file}\"
1025path = \"FACTUR-X_{file}.xslt\"
1026sha256 = \"{xslt}\"
1027unflagged-assert = \"fatal\"
1028
1029[[resource]]
1030path = \"FACTUR-X_{file}_codedb.xml\"
1031sha256 = \"{codedb}\"
1032",
1033        xslt = p(xslt)?,
1034        codedb = p(codedb)?,
1035    ))
1036}
1037
1038/// As `scripts/fetch-xrechnung.sh` writes it.
1039fn manifest_xrechnung(spec: &RuleSetSpec) -> Result<String, String> {
1040    let p = |name: &str| spec.family.pins.get(name);
1041    let upper = spec.dir.to_ascii_uppercase();
1042    let mut m = format!(
1043        "# XRechnung {xrechnung} ({upper}), validator configuration {configuration}: the
1044# rule-set bundle manifest of einvoice-validator, as scripts/fetch-xrechnung.sh
1045# and einvoice-validate rules fetch write it (einvoice-validate --bundle DIR).
1046# As the KoSIT validator runs the configuration: a document must match exactly
1047# one of its scenarios (match), which names the stylesheets that run and gives
1048# rule ids levels of their own (customLevel: error is fatal, information
1049# other); a document that matches none is rejected; a failed assert without a
1050# flag is fatal.
1051",
1052        xrechnung = p("xrechnung")?,
1053        configuration = p("configuration")?,
1054    );
1055    if spec.dir == "cii" {
1056        m.push_str(
1057            "# The scenarios validate the documents against the UN/CEFACT CII D16B XML
1058# schema first (CrossIndustryInvoice_100pD16B.xsd): schema = \"cii-d16b\".
1059",
1060        );
1061    }
1062    let _ = write!(
1063        m,
1064        "format = 2\nname = \"xrechnung-{syntax}\"\ntitle = \"XRechnung {upper}\"\nversion = \"{xrechnung}\"\n",
1065        syntax = spec.dir,
1066        xrechnung = p("xrechnung")?,
1067    );
1068    // The XML schema of the scenarios of the syntax (`validateWithXmlSchema`).
1069    if spec.dir == "ubl" {
1070        m.push_str("schema = \"ubl-2.1\"\n");
1071    } else {
1072        m.push_str("schema = \"cii-d16b\"\n");
1073    }
1074    for (name, path, sha, version) in XRECHNUNG_STYLESHEETS {
1075        if !name.ends_with(&format!("-{upper}")) {
1076            continue;
1077        }
1078        let file = path.rsplit('/').next().unwrap_or(path);
1079        let _ = write!(
1080            m,
1081            "\n[[stylesheet]]\nname = \"{name}\"\npath = \"{file}\"\nsha256 = \"{}\"\nversion = \"{}\"\nunflagged-assert = \"fatal\"\n",
1082            p(sha)?,
1083            p(version)?
1084        );
1085    }
1086    for (syntax, name, namespaces, matching, stylesheets, fatal, warning, other) in
1087        XRECHNUNG_SCENARIOS
1088    {
1089        if syntax != spec.dir {
1090            continue;
1091        }
1092        let _ = write!(
1093            m,
1094            "\n[[scenario]]\nname = \"{name}\"\nnamespaces = \"{namespaces}\"\nmatch = \"{matching}\"\nstylesheets = \"{stylesheets}\"\n"
1095        );
1096        for (key, ids) in [("fatal", fatal), ("warning", warning), ("other", other)] {
1097            if !ids.is_empty() {
1098                let _ = writeln!(m, "{key} = \"{ids}\"");
1099            }
1100        }
1101    }
1102    Ok(m)
1103}
1104
1105/// As `scripts/fetch-fr-ctc.sh` writes it.
1106fn manifest_fr_ctc(spec: &RuleSetSpec) -> Result<String, String> {
1107    let p = |name: &str| spec.family.pins.get(name);
1108    let (dir, ubl, title, names) = FR_CTC_BUNDLES
1109        .iter()
1110        .find(|(dir, ..)| *dir == spec.dir)
1111        .ok_or_else(|| format!("{}: no bundle of the French rules", spec.name))?;
1112    let pack = p("pack")?;
1113    let mut m = format!(
1114        "# {title}, FNFE-MPE package {pack}: the rule-set bundle
1115# manifest of einvoice-validator, as scripts/fetch-fr-ctc.sh and
1116# einvoice-validate rules fetch write it (einvoice-validate --bundle DIR).
1117"
1118    );
1119    let stylesheets = names
1120        .iter()
1121        .map(|name| {
1122            FR_CTC_STYLESHEETS
1123                .iter()
1124                .find(|(n, ..)| n == name)
1125                .ok_or_else(|| format!("no stylesheet {name}"))
1126        })
1127        .collect::<Result<Vec<_>, String>>()?;
1128    // The code lists, by file name, with the pin of their SHA-256.
1129    let mut side = Vec::new();
1130    for (_, path, _, codedb) in &stylesheets {
1131        if let Some(file) = fr_ctc_side_file(path) {
1132            let base = file.rsplit('/').next().unwrap_or(&file).to_owned();
1133            let pin = codedb.ok_or_else(|| format!("{path}: no pin of its code list"))?;
1134            side.push((base, pin));
1135        }
1136    }
1137    for (base, _) in &side {
1138        let stem = base.strip_suffix("_codedb.xml").unwrap_or(base);
1139        let _ = write!(
1140            m,
1141            "# The stylesheet {stem}.xslt reads, with document(), the code list\n# {base} next to it, a resource of the bundle.\n"
1142        );
1143    }
1144    for (name, ..) in &stylesheets {
1145        if fr_ctc_factur_x(name) {
1146            let _ = write!(
1147                m,
1148                "# A failed assert of {name} without a flag is fatal, as the\n# Mustang validator reads the Factur-X reports.\n"
1149            );
1150        }
1151    }
1152    let _ = write!(
1153        m,
1154        "format = 2\nname = \"fr-ctc-{dir}\"\ntitle = \"{title}\"\nversion = \"{pack}\"\n"
1155    );
1156    if *ubl {
1157        m.push_str("schema = \"ubl-2.1\"\n");
1158    }
1159    for (name, _, sha, _) in &stylesheets {
1160        let _ = write!(
1161            m,
1162            "\n[[stylesheet]]\nname = \"{name}\"\npath = \"{name}.xslt\"\nsha256 = \"{}\"\n",
1163            p(sha)?
1164        );
1165        if fr_ctc_factur_x(name) {
1166            m.push_str("unflagged-assert = \"fatal\"\n");
1167        }
1168    }
1169    for (base, pin) in &side {
1170        let _ = write!(
1171            m,
1172            "\n[[resource]]\npath = \"{base}\"\nsha256 = \"{}\"\n",
1173            p(pin)?
1174        );
1175    }
1176    Ok(m)
1177}
1178
1179/// As `scripts/fetch-peppol.sh` writes it.
1180fn manifest_peppol(spec: &RuleSetSpec) -> Result<String, String> {
1181    let p = |name: &str| spec.family.pins.get(name);
1182    Ok(format!(
1183        "# Peppol BIS Billing {tag} (UBL): the rule-set bundle manifest of
1184# einvoice-validator, as scripts/fetch-peppol.sh and einvoice-validate rules
1185# fetch write it (einvoice-validate --bundle DIR).
1186format = 1
1187name = \"peppol-bis-billing-ubl\"
1188title = \"Peppol BIS Billing 3.0 UBL\"
1189version = \"{tag}\"
1190schema = \"ubl-2.1\"
1191
1192[[stylesheet]]
1193name = \"CEN-EN16931-UBL\"
1194path = \"xslt/CEN-EN16931-UBL.xslt\"
1195sha256 = \"{cen_sha}\"
1196version = \"{cen}\"
1197
1198[[stylesheet]]
1199name = \"PEPPOL-EN16931-UBL\"
1200path = \"xslt/PEPPOL-EN16931-UBL.xslt\"
1201sha256 = \"{peppol_sha}\"
1202",
1203        tag = p("tag")?,
1204        cen_sha = p("cen_xslt_sha256")?,
1205        cen = p("cen")?,
1206        peppol_sha = p("peppol_xslt_sha256")?,
1207    ))
1208}
1209
1210#[cfg(test)]
1211mod tests {
1212    use super::*;
1213    use crate::RuleSet;
1214
1215    #[test]
1216    fn every_rule_set_resolves_and_its_manifest_parses() {
1217        let all = fetched_rule_sets().unwrap();
1218        assert_eq!(all.len(), RULE_SETS.len());
1219        for r in all {
1220            let parsed =
1221                RuleSet::parse(r.manifest()).unwrap_or_else(|e| panic!("{}: {e}", r.name()));
1222            assert_eq!(parsed.name(), r.name());
1223            assert_eq!(parsed.title(), r.title());
1224            assert_eq!(parsed.version(), r.version());
1225            assert_ne!(r.sources(), []);
1226            for s in r.sources() {
1227                assert!(s.url().starts_with("https://"), "{}", s.url());
1228                let length = match s.algorithm_kind() {
1229                    Algorithm::Sha256 => 64,
1230                };
1231                assert_eq!(s.digest().len(), length, "{}", s.url());
1232                assert!(!s.file().contains('/'), "{}", s.file());
1233            }
1234            // UBL 2.1 for UBL; CII D16B for XRechnung CII, whose KoSIT scenarios validate
1235            // against it.
1236            let schema = if r.syntax() == Some(Syntax::Ubl) {
1237                Some(crate::SchemaId::Ubl21)
1238            } else if r.name() == "xrechnung-cii" {
1239                Some(crate::SchemaId::CiiD16b)
1240            } else {
1241                None
1242            };
1243            assert_eq!(parsed.schema(), schema, "{}", r.name());
1244        }
1245        // Names are unique, and no name is an alias or a family.
1246        for (i, r) in all.iter().enumerate() {
1247            assert!(
1248                all[..i].iter().all(|o| o.name() != r.name()),
1249                "{}",
1250                r.name()
1251            );
1252            assert!(ALIASES.iter().all(|(a, _)| *a != r.name()));
1253            assert!(FAMILIES.iter().all(|f| f.name != r.name()));
1254            assert!(crate::BUILTIN_RULE_SETS.iter().all(|b| *b != r.name()));
1255        }
1256    }
1257
1258    /// Where an unflagged failed assert is fatal, and where scenarios give rule ids their
1259    /// levels: as the reference validator of each family reads the reports.
1260    #[test]
1261    fn severities_of_the_reference_validators() {
1262        use crate::Severity;
1263        for r in fetched_rule_sets().unwrap() {
1264            let parsed = RuleSet::parse(r.manifest()).unwrap();
1265            for s in parsed.stylesheets() {
1266                // Mustang (Factur-X, and the Factur-X profiles of the French package)
1267                // and KoSIT (XRechnung) reject a document for an unflagged failed
1268                // assert; Peppol and the rest of the French rules flag every assert.
1269                let fatal = r.family() == "factur-x"
1270                    || r.family() == "xrechnung"
1271                    || s.name().starts_with("FACTUR-X_");
1272                let expected = if fatal {
1273                    Severity::Fatal
1274                } else {
1275                    Severity::Other
1276                };
1277                assert_eq!(s.unflagged_assert(), expected, "{} {}", r.name(), s.name());
1278            }
1279            let scenarios: Vec<(&str, Option<&[String]>)> = parsed
1280                .scenarios()
1281                .iter()
1282                .map(|s| (s.name(), s.stylesheets()))
1283                .collect();
1284            match r.name() {
1285                "xrechnung-ubl" | "xrechnung-cii" => {
1286                    // Every scenario of the configuration that runs its stylesheets, each
1287                    // with a match expression: the bundle selects by scenario.
1288                    assert_eq!(
1289                        scenarios.len(),
1290                        if r.name() == "xrechnung-ubl" { 7 } else { 4 }
1291                    );
1292                    assert!(parsed.selects_by_scenario());
1293                }
1294                _ => {
1295                    assert_eq!(scenarios, [], "{}", r.name());
1296                    assert!(!parsed.selects_by_scenario());
1297                }
1298            }
1299            // Every XML schema of the reference validator is run.
1300            assert_eq!(parsed.unchecked_schema(), None, "{}", r.name());
1301        }
1302        let ubl = RuleSet::parse(
1303            fetched_rule_set("xrechnung-ubl", None)
1304                .unwrap()
1305                .unwrap()
1306                .manifest(),
1307        )
1308        .unwrap();
1309        let standard = &ubl.scenarios()[0];
1310        assert_eq!(standard.name(), "EN16931 XRechnung (UBL Invoice)");
1311        assert_eq!(standard.level("UBL-CR-646"), Some(Severity::Fatal));
1312        assert_eq!(standard.level("BR-CL-23"), Some(Severity::Warning));
1313        assert_eq!(
1314            ubl.scenarios()[1].level("UBL-CR-646"),
1315            Some(Severity::Other)
1316        );
1317        let names = |s: &crate::Scenario| s.stylesheets().map(<[String]>::to_vec);
1318        assert_eq!(
1319            names(standard),
1320            Some(vec!["EN16931-UBL".to_owned(), "XRechnung-UBL".to_owned()])
1321        );
1322        // The scenario of the CEN rules alone runs the CEN stylesheet alone.
1323        let cen = &ubl.scenarios()[5];
1324        assert_eq!(cen.name(), "EN16931 (UBL Invoice)");
1325        assert_eq!(names(cen), Some(vec!["EN16931-UBL".to_owned()]));
1326        assert_eq!(cen.levels(), []);
1327    }
1328
1329    #[test]
1330    fn aliases_and_families() {
1331        let name = |n: &str, s| fetched_rule_set(n, s).unwrap().map(FetchedRuleSet::name);
1332        assert_eq!(name("peppol", None), Some("peppol-bis-billing-ubl"));
1333        assert_eq!(name("xrechnung", Some(Syntax::Ubl)), Some("xrechnung-ubl"));
1334        assert_eq!(name("xrechnung", Some(Syntax::Cii)), Some("xrechnung-cii"));
1335        assert_eq!(name("xrechnung", None), Some("xrechnung-ubl"));
1336        assert_eq!(name("factur-x-basic", None), Some("factur-x-basic"));
1337        assert_eq!(name("nope", None), None);
1338        assert_eq!(named("factur-x").unwrap().len(), 5);
1339        assert_eq!(named("fr-ctc").unwrap().len(), 14);
1340        assert_eq!(named("xrechnung").unwrap().len(), 2);
1341        assert_eq!(named("peppol").unwrap().len(), 1);
1342        assert_eq!(named("xrechnung-cii").unwrap().len(), 1);
1343        assert!(named("cen-ubl").unwrap().is_empty());
1344    }
1345
1346    #[test]
1347    fn side_files_of_the_french_package() {
1348        assert_eq!(
1349            fr_ctc_side_file("a/b/FACTUR-X_EN16931.xslt").as_deref(),
1350            Some("a/b/FACTUR-X_EN16931_codedb.xml")
1351        );
1352        assert_eq!(
1353            fr_ctc_side_file("CII/EN16931/2xslt/EN16931-CII-validation.xslt"),
1354            None
1355        );
1356        // Each stylesheet with a code list has its pin, and only those.
1357        for (name, path, _, codedb) in FR_CTC_STYLESHEETS {
1358            assert_eq!(fr_ctc_side_file(path).is_some(), codedb.is_some(), "{name}");
1359        }
1360    }
1361}