diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..f233385 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,9 @@ +# Set update schedule for GitHub Actions + +version: 2 +updates: + + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/mermaid-svg/package-lock.json b/.github/mermaid-svg/package-lock.json new file mode 100644 index 0000000..070cd5e --- /dev/null +++ b/.github/mermaid-svg/package-lock.json @@ -0,0 +1,66 @@ +{ + "name": "nl-respec-mermaid-svg-normalization", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "nl-respec-mermaid-svg-normalization", + "dependencies": { + "css-tree": "3.2.1", + "parse5": "8.0.1" + } + }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/entities": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", + "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "license": "CC0-1.0" + }, + "node_modules/parse5": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz", + "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==", + "license": "MIT", + "dependencies": { + "entities": "^8.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + } + } +} diff --git a/.github/mermaid-svg/package.json b/.github/mermaid-svg/package.json new file mode 100644 index 0000000..ea96319 --- /dev/null +++ b/.github/mermaid-svg/package.json @@ -0,0 +1,8 @@ +{ + "name": "nl-respec-mermaid-svg-normalization", + "private": true, + "dependencies": { + "css-tree": "3.2.1", + "parse5": "8.0.1" + } +} diff --git a/.github/repos.json b/.github/repos.json new file mode 100644 index 0000000..0a5f4a0 --- /dev/null +++ b/.github/repos.json @@ -0,0 +1,540 @@ +{ + "Geonovum": { + "repos": { + "IMG": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "Metadata-handreiking": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "praktijkrichtlijn-vector-tiling": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "imev-werkomgeving": { + "updateAllow": true, + "respecBuildUrl": null, + "respecVersion": "24.5.2" + }, + "IMROI": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "HR-CRS-Gebruik": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "Geo-standaarden-wijzigingsprotocol": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "raamwerk-geostandaarden": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "ow-IMOW": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "dso-validatiematrix": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "24.5.2" + }, + "bestuurlijke-gebieden-cm": { + "updateAllow": true, + "respecBuildUrl": "js/modeldesk-respec.js?v=3", + "respecVersion": "35.8.0" + }, + "imgolf-werkomgeving": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "IMG-wijzigingsprotocol": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "IMX-ModelMapping": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "dso-cim-op": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.0.0" + }, + "dso-cim-oi": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "dso-cim-org": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.0.0" + }, + "dso-cim-ow": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.0.0" + }, + "dso-cim-tr": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "dso-cim-am": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.0.0" + }, + "dso-cim-bhkv": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "dso-cim-hlp": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "dso-cim-mac": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "dso-cim-pdc": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "dso-cim-swf": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.0.0" + }, + "ogc-api-features-guideline": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "hvd": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "DCAT-AP-NL30": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "3d-tiling": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "geonovum-allemodellen": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "NL-SBB": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "imkl-werkomgeving": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.0.0" + }, + "hr-3d-standaarden": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "ibro-scope": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "visiestandaarden": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "Testbed-sensordata": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "mim-uml": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "mim-ld": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "mim-metamodel": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "mim-fbm": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "NL-ReSpec-template": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "ibro-cm": { + "updateAllow": true, + "respecBuildUrl": "js/modeldesk-respec.js?v=3", + "respecVersion": "35.8.0" + }, + "IMMOB": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "specref.geostandaarden.nl": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "dcat-ap-nl-wijzigingsprotocol": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "mim-archimate": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.3.0" + }, + "mim-ontouml": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "test_repo": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "vth-cim-flo": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "ibro-lm": { + "updateAllow": true, + "respecBuildUrl": "js/modeldesk-respec.js?v=3", + "respecVersion": "37.0.0" + }, + "imev-beheerplan": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "geonovum-dashboard": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "mim-lineage": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.6.1" + }, + "bestuurlijke-gebieden-lm": { + "updateAllow": true, + "respecBuildUrl": "js/modeldesk-respec.js?v=3", + "respecVersion": "35.8.0" + }, + "vth-dim-vergunning-llm": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.4.1" + }, + "ReSpec-oefen": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "ReSpec-debug": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.4.1" + }, + "GeoBIM_BIM_naar_Geo": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "geooptijd": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "KBI-WOZ-advies": { + "updateAllow": false, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "3d-standaard-rapport": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "TransparantieApp": { + "updateAllow": true, + "respecBuildUrl": "https://logius-standaarden.github.io/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "geen-respec": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "35.8.0" + }, + "nl-sbb-bp": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "geonovum-datatypen": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.0.0" + }, + "mim-datatypen": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.0.0" + }, + "iso-19107-datatypen": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.0.0" + }, + "word2markdown-handleiding-1": { + "updateAllow": true, + "respecBuildUrl": null, + "respecVersion": null + }, + "word2werkversie-handleiding-1": { + "updateAllow": true, + "respecBuildUrl": null, + "respecVersion": null + }, + "word2werkversie-handleiding": { + "updateAllow": true, + "respecBuildUrl": null, + "respecVersion": null + }, + "word2markdown-handleiding": { + "updateAllow": true, + "respecBuildUrl": null, + "respecVersion": null + }, + "TransparantieApp-Gebruikers-Onderzoek-UX": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "TransparantieApp-Applicatie-Architectuur": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "testbed-sensordata-2026": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "imev-wijzigingsprotocol": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "3d-standaard-onderzoek": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.0.0" + }, + "CIM-Funderingen": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "mim-begrippenkader": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "mim-conceptueel": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.0.0" + }, + "mim-logisch": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.0.0" + }, + "mim-best-practices": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.0.0" + }, + "IMMOB-english": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "toegankelijke-locatiedata": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "inspire-handreiking": { + "updateAllow": true, + "respecBuildUrl": "https://tools.geostandaarden.nl/respec/builds/respec-geonovum.js", + "respecVersion": "24.5.2" + }, + "NLDT-Architectuur": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "logboek-dataverwerkingen-voor-objecten": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "nen3610-ontologie": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "vth-lith": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "handreiking-rasterdata": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "NLDT-Wijzigingsprotocol": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + } + } + }, + "BROprogramma": { + "repos": { + "BHR-G": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "BHR-GT": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "GMW": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "SAD": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "SLD": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "GAR": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "GMN": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "37.2.0" + }, + "CPT": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": null + }, + "BHR-P": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": null + }, + "EPL": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": null + }, + "SFR": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "24.5.2" + }, + "GLD": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": "24.5.2" + }, + "GUF": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": null + }, + "FRD": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": null + }, + "GPD": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": null + }, + "EPC": { + "updateAllow": true, + "respecBuildUrl": "https://gitdocumentatie.logius.nl/publicatie/respec/builds/respec-nlgov.js", + "respecVersion": null + } + } + } +} diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..7eae1c8 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,374 @@ +name: Build / check +on: + workflow_call: +jobs: + build: + name: Snapshot + Checks + runs-on: ubuntu-24.04 + permissions: + contents: write + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + # Hulpbestanden (normalizer, pdf.js) komen uit dezelfde repository en ref + # als deze reusable workflow, zodat documentrepos ze niet zelf hoeven te bevatten. + - name: Determine tooling ref + id: tooling + shell: bash + env: + WORKFLOW_REF: ${{ job.workflow_ref }} + run: | + set -euo pipefail + + TOOLING_REPOSITORY="${WORKFLOW_REF%%/.github/workflows/*}" + TOOLING_REF="${WORKFLOW_REF##*@}" + + if [[ -z "$TOOLING_REPOSITORY" || -z "$TOOLING_REF" ]]; then + echo "::error title=Workflow ref ontbreekt::Kan job.workflow_ref niet parsen: $WORKFLOW_REF" + exit 1 + fi + + echo "repository=$TOOLING_REPOSITORY" >> "$GITHUB_OUTPUT" + echo "ref=$TOOLING_REF" >> "$GITHUB_OUTPUT" + echo "TOOLING_DIR=$GITHUB_WORKSPACE/.nl-respec-tooling" >> "$GITHUB_ENV" + echo "Tooling repository: $TOOLING_REPOSITORY" + echo "Tooling ref: $TOOLING_REF" + + - name: Checkout workflow tooling + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ steps.tooling.outputs.repository }} + ref: ${{ steps.tooling.outputs.ref }} + path: .nl-respec-tooling + persist-credentials: false + sparse-checkout: | + .github/mermaid-svg + .github/workflows + + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + + - name: Bepaal branch voor terugschrijven + id: commit-target + if: ${{ github.event_name == 'push' }} + shell: bash + run: | + set -euo pipefail + + TARGET_BRANCH="${GITHUB_REF#refs/heads/}" + TARGET_BRANCH="${TARGET_BRANCH#refs/heads/}" + + if [[ -z "$TARGET_BRANCH" ]]; then + echo "::error title=Doelbranch ontbreekt::Kan geen branch bepalen om de gegenereerde documenten naar terug te schrijven." + exit 1 + fi + + if ! git fetch --no-tags origin "refs/heads/$TARGET_BRANCH:refs/remotes/origin/$TARGET_BRANCH"; then + echo "::error title=Doelbranch niet gevonden::Kan branch '$TARGET_BRANCH' niet ophalen om de gegenereerde documenten terug te schrijven." + exit 1 + fi + + TARGET_SHA="$(git rev-parse "refs/remotes/origin/$TARGET_BRANCH")" + if [[ "$TARGET_SHA" != "$GITHUB_SHA" ]]; then + echo "::error title=Doelbranch is gewijzigd::Branch '$TARGET_BRANCH' staat op $TARGET_SHA, maar deze workflow draait voor commit $GITHUB_SHA. De gegenereerde documenten worden daarom niet automatisch teruggeschreven." + exit 1 + fi + + git checkout -B "$TARGET_BRANCH" "refs/remotes/origin/$TARGET_BRANCH" + echo "should_commit=true" >> "$GITHUB_OUTPUT" + echo "target_branch=$TARGET_BRANCH" >> "$GITHUB_OUTPUT" + + - name: Prepare directories + run: | + mkdir -p static "$RUNNER_TEMP/nl-respec-validation" + + - name: Blokkeer raw.githubusercontent.com-links in bronbestand + shell: bash + run: | + set -euo pipefail + MATCH_FILE="$(mktemp)" + trap 'rm -f "$MATCH_FILE"' EXIT + + GREP_STATUS=0 + grep -nE 'raw\.githubusercontent\.com' index.html > "$MATCH_FILE" || GREP_STATUS=$? + + if [[ "$GREP_STATUS" -gt 1 ]]; then + echo "Zoeken naar raw.githubusercontent.com-links in index.html mislukte." + exit "$GREP_STATUS" + fi + + if [[ -s "$MATCH_FILE" ]]; then + if [[ "${{ github.event_name }}" == "release" ]]; then + echo "::error title=Publicatie geblokkeerd::index.html bevat verwijzingen naar raw.githubusercontent.com. Vervang deze links door verwijzingen naar docs.geostandaarden.nl." + echo "Gevonden verwijzingen in index.html:" + cat "$MATCH_FILE" + exit 1 + fi + + echo "::warning title=Controlewaarschuwing::index.html bevat verwijzingen naar raw.githubusercontent.com. Vervang deze links door verwijzingen naar docs.geostandaarden.nl." + echo "Gevonden verwijzingen in index.html:" + cat "$MATCH_FILE" + fi + + - name: Generate HTML snapshot + run: npx --yes respec@37.3.2 --localhost --disable-sandbox --timeout 120 --src index.html --out snapshot.html + + - name: Normaliseer mermaid-diagrammen in snapshot + run: | + set -euo pipefail + (cd "$TOOLING_DIR/.github/mermaid-svg" && npm ci --ignore-scripts --no-audit --no-fund) + node "$TOOLING_DIR/.github/workflows/normalize-mermaid-svg.mjs" snapshot.html + + - name: Check localized header links + run: | + if [ -f scripts/check-localized-header-links.mjs ]; then + node scripts/check-localized-header-links.mjs snapshot.html + fi + + - name: Prepare publication for validation + run: | + set -euo pipefail + + PUBLICATION_DIR="$GITHUB_WORKSPACE/publication-validation" + rm -rf "$PUBLICATION_DIR" + mkdir -p "$PUBLICATION_DIR" + cp snapshot.html "$PUBLICATION_DIR/index.html" + + for dir in data media js css; do + if [[ -d "$dir" ]]; then + cp -R "$dir" "$PUBLICATION_DIR/" + fi + done + + find "$PUBLICATION_DIR" -type f \ + \( -name '*.respec.html' -o -name '*.respec.catalog.xhtml' \) \ + -delete + + - name: Validate publication HTML + id: publication-html + uses: anishathalye/proof-html@f060b7619c2410bd85d970459a60ef431cf47ed5 # v2.2.5 + with: + directory: publication-validation + check_html: true + check_css: false + disable_external: true + check_external_hash: false + enforce_https: false + ignore_empty_alt: true + + - name: Check for alternateFormats via Node + id: config + run: | + # Maak config require-baar + cp ./js/config.js config.js + echo "module.exports = { respecConfig };" >> config.js + + # Laat Node bepalen of er een PDF entry is (en exitcode gebruiken) + if node -e "const {respecConfig}=require('./config.js'); + const ok = Array.isArray(respecConfig.alternateFormats) + && respecConfig.alternateFormats.some(f => f && f.label==='pdf' && f.uri); + if (!ok) process.exit(1);" ; then + echo "grep=true" >> $GITHUB_OUTPUT + else + echo "grep=false" >> $GITHUB_OUTPUT + fi + + - name: Copy pdf.js if needed + if: ${{ steps.config.outputs.grep == 'true' }} + run: cp "$TOOLING_DIR/.github/workflows/pdf.js" . + + - name: Generate PDF(s) + if: ${{ steps.config.outputs.grep == 'true' }} + run: | + cp ./js/config.js config.js + echo "module.exports = { respecConfig };" >> config.js + echo "var window = {respecMermaid:{createFigures:null}};" | cat - config.js > temp && mv temp config.js + npm install puppeteer + python3 -m http.server 8081 >/dev/null 2>&1 & + # wacht tot de lokale server draait + for i in {1..30}; do + if curl -sf http://localhost:8081/snapshot.html > /dev/null; then + break + fi + sleep 1 + done + curl -sf http://localhost:8081/snapshot.html > /dev/null || (echo "Local HTTP server on 8081 not reachable"; exit 1) + rm -f *.pdf + PDF_SNAPSHOT_URL=http://localhost:8081/snapshot.html node pdf.js + mv *.pdf static/ + + - name: Serve snapshot over HTTP + run: | + cd "${{ github.workspace }}" + python3 -m http.server 8080 >/dev/null 2>&1 & + echo "SNAPSHOT_SERVER_PID=$!" >> "$GITHUB_ENV" + + - name: Locate Chrome and ChromeDriver for WCAG check + id: browser + shell: bash + run: | + set -euo pipefail + + CHROME_BIN="$(command -v google-chrome)" + CHROMEDRIVER_BIN="${CHROMEWEBDRIVER}/chromedriver" + + test -x "$CHROME_BIN" + test -x "$CHROMEDRIVER_BIN" + + "$CHROME_BIN" --version + "$CHROMEDRIVER_BIN" --version + + echo "chrome_bin=$CHROME_BIN" >> "$GITHUB_OUTPUT" + echo "chromedriver_bin=$CHROMEDRIVER_BIN" >> "$GITHUB_OUTPUT" + + - name: Run WCAG 2.2 check + run: | + for i in {1..30}; do + if curl -sf http://localhost:8080/snapshot.html > /dev/null; then + break + fi + sleep 1 + done + curl -sf http://localhost:8080/snapshot.html > /dev/null || (echo "Local HTTP server on 8080 not reachable"; exit 1) + + set -o pipefail + VALIDATION_DIR="$RUNNER_TEMP/nl-respec-validation" + RAW_WCAG="$VALIDATION_DIR/wcag-raw.json" + if npx --yes @axe-core/cli@latest --stdout \ + --chrome-path "${{ steps.browser.outputs.chrome_bin }}" \ + --chromedriver-path "${{ steps.browser.outputs.chromedriver_bin }}" \ + --tags wcag2a,wcag2aa,wcag21a,wcag21aa,wcag22a,wcag22aa \ + http://localhost:8080/snapshot.html > "$RAW_WCAG"; then + if jq ' + [ + .[] as $page | + $page.violations[] | + { + url: $page.url, + id, + impact, + description, + helpUrl, + nodes: [ + .nodes[] | + { + target, + html, + failureSummary + } + ] + } + ] + ' "$RAW_WCAG" > "$VALIDATION_DIR/wcag-report.json"; then + echo "WCAG output saved to $VALIDATION_DIR/wcag-report.json" + else + echo "{\"error\":\"WCAG-check mislukt: axe-output was geen geldige JSON. Zie logs voor details.\"}" > "$VALIDATION_DIR/wcag-report.json" + echo "WCAG output saved to $VALIDATION_DIR/wcag-report.json (error)" + fi + else + echo "{\"error\":\"WCAG-check mislukt (axe-cli). Zie logs voor details.\"}" > "$VALIDATION_DIR/wcag-report.json" + echo "WCAG output saved to $VALIDATION_DIR/wcag-report.json (error)" + fi + rm -f "$RAW_WCAG" + + - name: Validate publication links + id: publication-links + if: ${{ !cancelled() }} + uses: lycheeverse/lychee-action@e7477775783ea5526144ba13e8db5eec57747ce8 # v2.9.0 + with: + args: >- + --offline + --root-dir "${{ github.workspace }}/publication-validation" + './index.html' + fail: true + failIfEmpty: true + format: markdown + jobSummary: true + output: ${{ runner.temp }}/nl-respec-validation/link-check.txt + workingDirectory: ${{ github.workspace }}/publication-validation + + - name: Summarize publication preflight + if: ${{ always() }} + run: | + HTML_OUTCOME="${{ steps.publication-html.outcome }}" + LINK_OUTCOME="${{ steps.publication-links.outcome }}" + BUILD_STATUS="${{ job.status }}" + + { + echo "## Publicatiepreflight" + echo + echo "| Controle | Resultaat |" + echo "| --- | --- |" + echo "| HTML | $HTML_OUTCOME |" + echo "| Links | $LINK_OUTCOME |" + echo "| Build | $BUILD_STATUS |" + echo + + if [[ "$BUILD_STATUS" == "success" && "$HTML_OUTCOME" == "success" && "$LINK_OUTCOME" == "success" ]]; then + echo "✅ **Publicatiegereed: ja**" + else + echo "❌ **Publicatiegereed: nee**" + fi + } >> "$GITHUB_STEP_SUMMARY" + + - name: Stop snapshot HTTP server + if: always() + run: | + if [[ -n "${SNAPSHOT_SERVER_PID:-}" ]]; then + kill "$SNAPSHOT_SERVER_PID" || true + fi + + - name: Remove validation working directory + if: ${{ always() }} + run: rm -rf "$GITHUB_WORKSPACE/publication-validation" + + - name: Commit all results + if: ${{ steps.commit-target.outputs.should_commit == 'true' }} + run: | + set -euo pipefail + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + + if [[ "${{ steps.config.outputs.grep }}" == "true" ]] && ls static/*.pdf 1>/dev/null 2>&1; then + mv static/*.pdf . + fi + + git add snapshot.html + + if compgen -G "*.pdf" > /dev/null; then + git add *.pdf + fi + + if git diff --cached --quiet; then + echo "No changes to commit" + exit 0 + fi + + git commit -m "Snapshot gegenereerd" + + TARGET_BRANCH="${{ steps.commit-target.outputs.target_branch }}" + git push origin HEAD:"$TARGET_BRANCH" + + - name: Upload snapshot artifact + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: snapshot + path: | + snapshot.html + static/*.pdf + media/**/* + js/**/* + data/**/* + + - name: Upload validation reports + if: ${{ always() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: validation-reports + path: | + ${{ runner.temp }}/nl-respec-validation/wcag-report.json + ${{ runner.temp }}/nl-respec-validation/link-check.txt + if-no-files-found: warn diff --git a/.github/workflows/normalize-mermaid-svg.mjs b/.github/workflows/normalize-mermaid-svg.mjs new file mode 100644 index 0000000..84b6ab3 --- /dev/null +++ b/.github/workflows/normalize-mermaid-svg.mjs @@ -0,0 +1,191 @@ +#!/usr/bin/env node +// Normaliseer alleen Mermaid-uitvoer, vóór HTML-validatie, PDF en publicatie. +// Installatie: (cd .github/mermaid-svg && npm ci --ignore-scripts) +// Gebruik: node .github/workflows/normalize-mermaid-svg.mjs snapshot.html [...] +import { readFileSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; + +// Een eigen dependency-directory: verander geen package.json van documentrepos. +const require = createRequire(new URL("../mermaid-svg/package.json", import.meta.url)); +const { parse } = await import(require.resolve("parse5")); +const css = require("css-tree"); +const SVG = "http://www.w3.org/2000/svg"; +const IDREFS = new Set([ + "aria-labelledby", "aria-describedby", "aria-controls", "aria-owns", + "aria-activedescendant", "aria-details", "aria-errormessage", "aria-flowto", +]); +const URL_ATTRIBUTES = new Set([ + "fill", "stroke", "filter", "clip-path", "mask", "marker", "marker-start", + "marker-mid", "marker-end", "cursor", "color-profile", +]); + +function* elements(node) { + if (node.tagName) yield node; + for (const child of node.childNodes ?? []) yield* elements(child); +} + +function attr(node, name) { + return node.attrs?.find(attribute => attribute.name === name)?.value ?? ""; +} + +function textContent(node) { + return (node.childNodes ?? []).map(child => child.value ?? textContent(child)).join(""); +} + +function isMermaid(svg) { + // Mermaid's eigen container blijft bestaan bij rechtstreeks gebruik. + for (let node = svg; node; node = node.parentNode) { + if (attr(node, "class").split(/\s+/).includes("mermaid")) return true; + } + // respec-mermaid 1.0.1 verwijdert de .mermaid-container. De gegenereerde + // diagram-id EN Mermaid-styles herkennen ook flowcharts zonder ARIA/title. + // 1.3.0 maakt : die blijven intact. + return /^diagram-\d+$/.test(attr(svg, "id")) && [...elements(svg)].some(node => + node.tagName === "style" && textContent(node).includes("--mermaid-font-family")); +} + +function applyEdits(source, edits) { + for (const { start, end, value } of edits.sort((a, b) => b.start - a.start)) { + source = source.slice(0, start) + value + source.slice(end); + } + return source; +} + +function escapeText(value) { + return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">"); +} + +function localFragment(value, renames) { + return value.startsWith("#") && renames.has(value.slice(1)) + ? `#${renames.get(value.slice(1))}` : value; +} + +function rewriteCss(source, context, renames) { + if (renames.size === 0) return source; + const edits = []; + const tree = css.parse(source, { context, positions: true, parseCustomProperty: true }); + css.walk(tree, node => { + let value; + if (node.type === "IdSelector") { + const renamed = renames.get(css.ident.decode(node.name)); + if (renamed) value = `#${css.ident.encode(renamed)}`; + } else if (node.type === "Url") { + const renamed = localFragment(node.value, renames); + if (renamed !== node.value) value = css.generate({ ...node, value: renamed }); + } else if (node.type === "AttributeSelector" && node.value) { + const name = css.ident.decode(node.name.name); + const original = node.value.type === "String" + ? node.value.value : css.ident.decode(node.value.name); + let renamed = original; + if (name === "id" && node.matcher === "=") renamed = renames.get(original) ?? original; + else if (["href", "xlink|href", "*|href"].includes(name) && node.matcher === "=") { + renamed = localFragment(original, renames); + } else if (IDREFS.has(name) && ["=", "~="].includes(node.matcher)) { + renamed = original.replace(/\S+/g, id => renames.get(id) ?? id); + } + if (renamed !== original) { + edits.push({ start: node.value.loc.start.offset, end: node.value.loc.end.offset, + value: node.value.type === "String" ? css.string.encode(renamed) : css.ident.encode(renamed) }); + } + } + // Gewone CSS strings (zoals content), kleuren en externe URLs blijven intact. + if (value !== undefined) { + edits.push({ start: node.loc.start.offset, end: node.loc.end.offset, value }); + } + }); + return applyEdits(source, edits); +} + +function normalize(html) { + const document = parse(html, { sourceCodeLocationInfo: true }); + const nodes = [...elements(document)]; + const counts = new Map(); + for (const node of nodes) { + const id = attr(node, "id"); + if (id) counts.set(id, (counts.get(id) ?? 0) + 1); + } + const taken = new Set(counts.keys()); + const edits = []; + let renamed = 0; + let stripped = 0; + const diagrams = nodes.filter(node => { + if (node.namespaceURI !== SVG || node.tagName !== "svg") return false; + for (let parent = node.parentNode; parent; parent = parent.parentNode) { + if (parent.namespaceURI === SVG && parent.tagName === "svg" && isMermaid(parent)) return false; + } + return isMermaid(node); + }); + + diagrams.forEach((svg, index) => { + const descendants = [...elements(svg)]; + const renames = new Map(); + const prefix = attr(svg, "id") || `mermaid-${index + 1}`; + const localIds = new Set(); + for (const node of descendants) { + const id = attr(node, "id"); + if (!id) continue; + // Meerdere definities binnen hetzelfde diagram hebben geen eenduidig + // doel voor references. Niet stilzwijgend een willekeurig doel kiezen. + if (localIds.has(id)) throw new Error(`Dubbele id binnen Mermaid-diagram ${prefix}: ${id}`); + localIds.add(id); + // Het buitenste SVG is een mogelijk figuuranker; laat dat intact. + if (node === svg || counts.get(id) < 2) continue; + let candidate = `${prefix}-${id}`; + let suffix = 2; + while (taken.has(candidate)) candidate = `${prefix}-${id}-${suffix++}`; + taken.add(candidate); + renames.set(id, candidate); + } + renamed += renames.size; + + for (const node of descendants) { + for (const attribute of node.attrs ?? []) { + const name = attribute.prefix ? `${attribute.prefix}:${attribute.name}` : attribute.name; + const location = node.sourceCodeLocation?.attrs?.[name]; + if (!location) continue; + const original = attribute.value; + let value = original; + if (node.namespaceURI === SVG && node.tagName === "g" && + ["label-offset-x", "label-offset-y"].includes(name)) { + edits.push({ start: location.startOffset, end: location.endOffset, value: "" }); + stripped++; + continue; + } + if (name === "id" && node !== svg) value = renames.get(value) ?? value; + else if (name === "href" || name === "xlink:href") value = localFragment(value, renames); + else if (IDREFS.has(name)) value = value.replace(/\S+/g, id => renames.get(id) ?? id); + else if (name === "style") value = rewriteCss(value, "declarationList", renames); + else if (URL_ATTRIBUTES.has(name)) value = rewriteCss(value, "value", renames); + if (value !== original) { + edits.push({ start: location.startOffset, end: location.endOffset, + value: `${name}="${escapeText(value).replaceAll('"', """)}"` }); + } + } + if (node.namespaceURI === SVG && node.tagName === "style") { + const original = textContent(node); + const value = rewriteCss(original, "stylesheet", renames); + if (value !== original) { + const location = node.sourceCodeLocation; + edits.push({ start: location.startTag.endOffset, end: location.endTag.startOffset, + value: escapeText(value) }); + } + } + } + }); + // Alleen gewijzigde attributen en SVG-styles terugschrijven. De overige HTML, + // tekst, comments, scripts, afbeeldingen en ReSpec-ankers blijven bytegelijk. + return { html: applyEdits(html, edits), renamed, stripped, svgCount: diagrams.length }; +} + +const files = process.argv.slice(2); +if (files.length === 0) { + console.error("Gebruik: node normalize-mermaid-svg.mjs [...]"); + process.exit(2); +} +for (const file of files) { + const original = readFileSync(file, "utf8"); + const { html, renamed, stripped, svgCount } = normalize(original); + if (html !== original) writeFileSync(file, html); + console.log(`${file}: ${svgCount} Mermaid SVG('s), ${renamed} dubbele id('s) herschreven, ` + + `${stripped} ongeldig(e) attribu(u)t(en) verwijderd.`); +} diff --git a/.github/workflows/pdf.js b/.github/workflows/pdf.js new file mode 100644 index 0000000..bd816ca --- /dev/null +++ b/.github/workflows/pdf.js @@ -0,0 +1,40 @@ +const config = require("./config.js"); + +const alternateFormats = config.respecConfig.alternateFormats; +if (alternateFormats === undefined) { + console.warn("'alternateFormats' not found."); +} else { + const found = alternateFormats.find((element) => element.label === "pdf"); + if (found === undefined) { + console.warn("PDF not selected as alternate format."); + } else if (found.uri === undefined) { + console.warn("PDF file name ('uri') missing."); + } else { + const name = found.uri; + console.log("Printing PDF with name: " + name); + + const puppeteer = require("puppeteer"); + + const website_url = + process.env.PDF_SNAPSHOT_URL || "http://localhost:8081/snapshot.html"; + + (async () => { + const browser = await puppeteer.launch({ + args: ["--no-sandbox", "--disable-setuid-sandbox"], + }); + const page = await browser.newPage(); + console.log("Opening snapshot at:", website_url); + await page.goto(website_url, { waitUntil: "networkidle0" }); + await page.emulateMediaType("print"); + await page.addStyleTag({ content: ".sidelabel {position: absolute}" }); + const pdf = await page.pdf({ + path: name, + margin: { top: "100px", right: "50px", bottom: "100px", left: "50px" }, + printBackground: true, + format: "A4", + }); + + await browser.close(); + })(); + } +} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..f69122b --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,266 @@ +name: Publish +on: + workflow_call: + secrets: + GH_APP_ID: + required: true + GH_APP_PRIVATE_KEY: + required: true + workflow_dispatch: + +jobs: + release: + name: Release + runs-on: ubuntu-24.04 + permissions: + contents: write + pull-requests: write + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Download snapshot artefact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: snapshot + path: . + + - name: Prepare content + run: | + set -euo pipefail + + rm -f *.md index.html + mv snapshot.html index.html + mkdir content + cp index.html content/ + + for dir in data media js css; do + if [ -d "$dir" ]; then + cp -r "$dir" content/ + else + echo "Directory '$dir' bestaat niet, wordt overgeslagen." + fi + done + + find content -type f \ + \( -name '*.respec.html' -o -name '*.respec.catalog.xhtml' \) \ + -delete + + - name: Blokkeer raw.githubusercontent.com-links in publicatie + shell: bash + run: | + set -euo pipefail + MATCH_FILE="$(mktemp)" + trap 'rm -f "$MATCH_FILE"' EXIT + + GREP_STATUS=0 + grep -nE 'raw\.githubusercontent\.com' content/index.html > "$MATCH_FILE" || GREP_STATUS=$? + + if [[ "$GREP_STATUS" -gt 1 ]]; then + echo "Zoeken naar raw.githubusercontent.com-links in content/index.html mislukte." + exit "$GREP_STATUS" + fi + + if [[ -s "$MATCH_FILE" ]]; then + echo "::error title=Publicatie afgebroken::De te publiceren index.html bevat verwijzingen naar raw.githubusercontent.com. Vervang deze links door verwijzingen naar docs.geostandaarden.nl." + echo "Gevonden verwijzingen in content/index.html:" + cat "$MATCH_FILE" + exit 1 + fi + + - name: Extract & validate publishing metadata + id: metadata + shell: bash + run: | + set -euo pipefail + + CONFIG_FILE=content/js/config.js + + # 0. Strip alle //‑comments (hele regel of inline) + CLEAN_CONFIG=$(sed -E 's://.*$::' "$CONFIG_FILE") + + # 1. Helper: haal waarde op en zet om naar lowercase + get_value_lower() { + echo "$CLEAN_CONFIG" \ + | grep -Po "${1}:\s*\"\K[^\"]+" \ + | tr -d '[:space:]' \ + | tr '[:upper:]' '[:lower:]' || true + } + + # 2. Parse + lowercase + DOMAIN=$(get_value_lower 'pubDomain') + SPEC_STATUS=$(get_value_lower 'specStatus') + SPEC_TYPE=$(get_value_lower 'specType') + SHORT_NAME=$(get_value_lower 'shortName') + PUBLISH_DATE=$(get_value_lower 'publishDate') + + if [[ "$SPEC_STATUS" == "wv" ]]; then + echo "::error title=Ongeldige status voor publicatie::Document met status 'wv' (Werkversie) mag niet gepubliceerd worden." + exit 1 + fi + + # 3. Check op ontbrekende waarden + MISSING=() + for VAR in DOMAIN SPEC_STATUS SPEC_TYPE SHORT_NAME PUBLISH_DATE; do + if [ -z "${!VAR}" ]; then + MISSING+=("$VAR") + fi + done + if [ ${#MISSING[@]} -gt 0 ]; then + echo "::error title=Ontbrekende metadata::De volgende verplichte waarden ontbreken in config.js: ${MISSING[*]}" + exit 1 + fi + + # 4. Valideer specStatus tegen toegestane waarden + ALLOWED_STATUS=(wv cv vv def ld basis) + if [[ ! " ${ALLOWED_STATUS[*]} " =~ " $SPEC_STATUS " ]]; then + echo "::error title=Invalid specStatus::$SPEC_STATUS is geen geldige specStatus. Mogelijke waarden: ${ALLOWED_STATUS[*]}" + exit 1 + fi + + # 5. Valideer specType tegen toegestane waarden + ALLOWED_TYPES=(no st im pr hr wa al bd bp) + if [[ ! " ${ALLOWED_TYPES[*]} " =~ " $SPEC_TYPE " ]]; then + echo "::error title=Invalid specType::$SPEC_TYPE is geen geldige specType. Mogelijke waarden: ${ALLOWED_TYPES[*]}" + exit 1 + fi + + echo "Gevonden en gevalideerd (allemaal lowercase):" + echo " pubDomain = $DOMAIN" + echo " specStatus = $SPEC_STATUS" + echo " specType = $SPEC_TYPE" + echo " shortName = $SHORT_NAME" + echo " publishDate = $PUBLISH_DATE" + + # 6. Download pubDomainList.json indien nog niet aanwezig + CONFIG_JSON=pubDomainList.json + if [[ ! -f "$CONFIG_JSON" ]]; then + curl -sSL \ + https://docs.geostandaarden.nl/pubDomainList.json \ + -o "$CONFIG_JSON" + fi + + # 7. Check of pubDomain bestaat in de Geonovum-list (case‑insensitive) + if ! jq -e --arg domain "$DOMAIN" \ + '.Geonovum[] | select((.pubDomain|ascii_downcase)==$domain)' \ + "$CONFIG_JSON" >/dev/null; then + echo "::error title=Invalid pubDomain::pubDomain '$DOMAIN' niet gevonden in $CONFIG_JSON" + exit 1 + fi + + # 8. Valideer publishDate-formaat en geldigheid + if ! [[ "$PUBLISH_DATE" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then + echo "::error title=Invalid publishDate formaat::publishDate '$PUBLISH_DATE' heeft niet het formaat yyyy-MM-dd" + exit 1 + fi + if ! date -d "$PUBLISH_DATE" "+%Y-%m-%d" >/dev/null 2>&1; then + echo "::error title=Invalid publishDate::publishDate '$PUBLISH_DATE' is geen geldige datum" + exit 1 + fi + + # 9. Bouw de folder-path en exporteer als output + PUBLISH_DATE_COMPACT="$(echo "$PUBLISH_DATE" | tr -d '-')" + FOLDER_PATH="${DOMAIN}/${SPEC_STATUS}-${SPEC_TYPE}-${SHORT_NAME}-${PUBLISH_DATE_COMPACT}/" + + echo "folderPath=$FOLDER_PATH" >> $GITHUB_OUTPUT + echo "pubdomain=$DOMAIN" >> $GITHUB_OUTPUT + echo "specStatus=$SPEC_STATUS" >> $GITHUB_OUTPUT + echo "specType=$SPEC_TYPE" >> $GITHUB_OUTPUT + echo "shortName=$SHORT_NAME" >> $GITHUB_OUTPUT + echo "publishDate=$PUBLISH_DATE" >> $GITHUB_OUTPUT + + echo "Metadata en folder-path gevalideerd en opgeslagen" + + - name: Generate GitHub App token + id: app-token + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 + with: + client-id: ${{ secrets.GH_APP_ID }} + private-key: ${{ secrets.GH_APP_PRIVATE_KEY }} + owner: Geonovum + repositories: | + docs.geostandaarden.nl + + - name: Checkout private docs + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: Geonovum/docs.geostandaarden.nl + token: ${{ steps.app-token.outputs.token }} + path: docs.geostandaarden.nl + + - name: Switch naar develop branch bij pre-release + if: ${{ github.event.release.prerelease == true }} + run: | + cd docs.geostandaarden.nl + git config user.name "${{ github.actor }}" + git config user.email "${{ github.actor_id }}+${{ github.actor }}@users.noreply.github.com" + git fetch --all + git checkout develop || git checkout -b develop origin/develop + + - name: Copy output to pubDomain folder + run: | + mkdir -p docs.geostandaarden.nl/${{ steps.metadata.outputs.folderPath }} + cp -r content/* docs.geostandaarden.nl/${{ steps.metadata.outputs.folderPath }}/ + rm docs.geostandaarden.nl/${{ steps.metadata.outputs.folderPath }}/js/config.js + + - name: Update .htaccess “latest” pointer + run: | + set -euo pipefail + + FOLDER_PATH="${{ steps.metadata.outputs.folderPath }}" + SHORT_NAME="${{ steps.metadata.outputs.shortName }}" + REPO_DIR="docs.geostandaarden.nl" + + TOPIC="$(echo "$FOLDER_PATH" | cut -d/ -f1)" + VERSION_DIR="$(basename "$FOLDER_PATH")" + VERSION_DIR="${VERSION_DIR%/}" + LINK_DIR="$TOPIC/$SHORT_NAME" + + mkdir -p "$REPO_DIR/$LINK_DIR" + + # .htaccess updaten: redirect root + subpaden naar nieuwste versie-map + cat > "$REPO_DIR/$LINK_DIR/.htaccess" <<'EOF' + RewriteEngine On + # Redirect map-root en onderliggende paden naar de nieuwste versie-map + RewriteRule ^$ /__TOPIC__/__VERSION__/ [R=302,L] + RewriteRule ^(.+)$ /__TOPIC__/__VERSION__/$1 [R=302,L] + Options -Indexes + EOF + + # Variabelen invullen + sed -i \ + -e "s#__TOPIC__#${TOPIC}#g" \ + -e "s#__VERSION__#${VERSION_DIR}#g" \ + "$REPO_DIR/$LINK_DIR/.htaccess" + + echo "Updated $REPO_DIR/$LINK_DIR/.htaccess -> /$TOPIC/$VERSION_DIR/" + + - name: Push naar develop bij pre-release + if: ${{ github.event.release.prerelease == true }} + run: | + cd docs.geostandaarden.nl + git add . + git commit -m "Automatische pre-release update van ${{ github.repository }} (triggered by ${{ github.actor }})" + git push origin develop + + - name: Create PR naar main bij release + if: ${{ github.event.release.prerelease != true }} + uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 + with: + token: ${{ steps.app-token.outputs.token }} + path: docs.geostandaarden.nl + branch: auto-update-${{ github.run_id }} + base: main + author: ${{ github.actor }} <${{ github.actor_id }}+${{ github.actor }}@users.noreply.github.com> + committer: ${{ github.actor }} <${{ github.actor_id }}+${{ github.actor }}@users.noreply.github.com> + commit-message: "Automated update from ${{ github.repository }} (triggered by ${{ github.actor }})" + title: "Automated update from ${{ github.repository }} to main" + body: | + Triggered by: @${{ github.actor }} + Release: `${{ github.event.release.tag_name }}` + Update vanuit workflow voor domein ${{ steps.metadata.outputs.pubdomain }} + Folder: `${{ steps.metadata.outputs.folderPath }}` + To branch: `main` + labels: automated pr + delete-branch: true + reviewers: wilkoquak,fterpstra,lvdbrink diff --git a/.github/workflows/release-tag.yml b/.github/workflows/release-tag.yml new file mode 100644 index 0000000..00ab92a --- /dev/null +++ b/.github/workflows/release-tag.yml @@ -0,0 +1,35 @@ +# Alleen voor deze repository. +# Na het pushen van een versietag (bijv. v1.2.3) wordt de major-tag (v1) +# naar dezelfde commit verplaatst. Documentrepos gebruiken @v1 en krijgen +# daarmee automatisch alle niet-brekende updates. +name: Move major version tag + +on: + push: + tags: + - 'v[0-9]+.[0-9]+.[0-9]+' + +permissions: + contents: write + +jobs: + move-major-tag: + if: ${{ github.repository == 'Geonovum/NL-ReSpec-workflows' }} + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Verplaats major-tag + shell: bash + env: + VERSION_TAG: ${{ github.ref_name }} + run: | + set -euo pipefail + + MAJOR_TAG="${VERSION_TAG%%.*}" + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git tag -fa "$MAJOR_TAG" -m "$MAJOR_TAG -> $VERSION_TAG" "$GITHUB_SHA" + git push origin "refs/tags/$MAJOR_TAG" --force + + echo "$MAJOR_TAG wijst nu naar $VERSION_TAG ($GITHUB_SHA)" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/template-regression.yml b/.github/workflows/template-regression.yml new file mode 100644 index 0000000..8816fc6 --- /dev/null +++ b/.github/workflows/template-regression.yml @@ -0,0 +1,67 @@ +# Alleen voor deze repository: test de reusable workflows op het voorbeelddocument in de root. +name: Template regression checks + +on: + # Een push naar main ververst snapshot.html, de basis voor de visuele vergelijking. + push: + branches: [main] + pull_request: + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +jobs: + # Documentrepos gebruiken @v1; hier wordt de build van deze branch zelf getest. + build: + if: ${{ github.repository == 'Geonovum/NL-ReSpec-workflows' }} + permissions: + contents: write + uses: ./.github/workflows/build.yml + + visual-regression: + if: ${{ github.repository == 'Geonovum/NL-ReSpec-workflows' && github.event_name != 'push' }} + uses: ./.github/workflows/visual-regression-reusable.yml + with: + fail_on_difference: false + + mermaid-regression: + if: ${{ github.repository == 'Geonovum/NL-ReSpec-workflows' }} + name: Mermaid structure, rendering and PDF + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + - name: Install normalization dependencies + run: (cd .github/mermaid-svg && npm ci --ignore-scripts --no-audit --no-fund) + - name: Run all Python regression tests + run: | + python3 -m pip install PyYAML + python3 -m unittest discover -s tests -v + - name: Install rendering tools + env: + PUPPETEER_SKIP_DOWNLOAD: "true" + run: | + sudo apt-get update + sudo apt-get install -y poppler-utils + mkdir -p "$RUNNER_TEMP/mermaid-test-tools" + cp tests/verify_mermaid_rendering.mjs "$RUNNER_TEMP/mermaid-test-tools/" + cd "$RUNNER_TEMP/mermaid-test-tools" + npm install --no-audit --no-fund @playwright/test pngjs puppeteer + npx playwright install --with-deps chromium + - name: Compare normalized diagrams on screen and in PDF + run: | + node "$RUNNER_TEMP/mermaid-test-tools/verify_mermaid_rendering.mjs" \ + "$GITHUB_WORKSPACE" "$RUNNER_TEMP/mermaid-report" + - name: Upload Mermaid regression evidence + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: mermaid-regression-report + path: ${{ runner.temp }}/mermaid-report + if-no-files-found: warn diff --git a/.github/workflows/update-workflows.yml b/.github/workflows/update-workflows.yml new file mode 100644 index 0000000..eaafd4b --- /dev/null +++ b/.github/workflows/update-workflows.yml @@ -0,0 +1,115 @@ +name: Update workflows in document repos + +on: + workflow_dispatch: + inputs: + dry_run: + description: 'Dry run — toon wijzigingen maar commit niet' + type: boolean + default: false + +jobs: + # ── Stap 1: repos.json bijhouden ──────────────────────────────────────────── + sync-repos-json: + name: Sync repos.json + runs-on: ubuntu-24.04 + permissions: + contents: write + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + + - name: Maak GitHub App token aan voor Geonovum + id: token-geonovum + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 + with: + client-id: ${{ secrets.GH_APP_ID }} + private-key: ${{ secrets.GH_APP_PRIVATE_KEY }} + owner: Geonovum + + - name: Maak GitHub App token aan voor BROprogramma + id: token-broprogramma + continue-on-error: true + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 + with: + client-id: ${{ secrets.GH_APP_ID }} + private-key: ${{ secrets.GH_APP_PRIVATE_KEY }} + owner: BROprogramma + + - name: Sync repos.json + env: + GH_TOKEN_GEONOVUM: ${{ steps.token-geonovum.outputs.token }} + GH_TOKEN_BROPROGRAMMA: ${{ steps.token-broprogramma.outputs.token }} + SELF_OWNER: ${{ github.repository_owner }} + SELF_REPO: ${{ github.event.repository.name }} + run: > + node scripts/sync-repos.mjs + --repos-file .github/repos.json + --self-owner "$SELF_OWNER" + --self-repo "$SELF_REPO" + + - name: Commit repos.json indien gewijzigd + env: + DRY_RUN: ${{ inputs.dry_run }} + run: | + git config user.email "github-actions[bot]@users.noreply.github.com" + git config user.name "github-actions[bot]" + git add .github/repos.json + if git diff --staged --quiet; then + echo "Geen wijzigingen in repos.json." + elif [[ "$DRY_RUN" == "true" ]]; then + echo "🔍 Dry run — repos.json zou als volgt wijzigen:" + git diff --staged -- .github/repos.json + else + git commit -m "chore: sync repos.json" + git push + fi + + # ── Stap 2: workflows bijwerken ───────────────────────────────────────────── + update: + name: ${{ matrix.org }} + needs: sync-repos-json + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + org: [Geonovum, BROprogramma] + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.ref }} + # Volledige geschiedenis: nodig om exacte kopieën van template-tooling te herkennen. + fetch-depth: 0 + + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + + - name: Maak GitHub App token aan voor ${{ matrix.org }} + id: token + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 + with: + client-id: ${{ secrets.GH_APP_ID }} + private-key: ${{ secrets.GH_APP_PRIVATE_KEY }} + owner: ${{ matrix.org }} + + - name: Update workflows in ${{ matrix.org }} repos + env: + GH_TOKEN: ${{ steps.token.outputs.token }} + ORG: ${{ matrix.org }} + DRY_RUN: ${{ inputs.dry_run }} + TEMPLATE_GITHUB_DIR: ${{ github.workspace }}/document-repo/.github + SELF_OWNER: ${{ github.repository_owner }} + SELF_REPO: ${{ github.event.repository.name }} + run: > + node scripts/update-document-repos.mjs + --org "$ORG" + --repos-file .github/repos.json + --template-github-dir "$TEMPLATE_GITHUB_DIR" + --self-owner "$SELF_OWNER" + --self-repo "$SELF_REPO" diff --git a/.github/workflows/visual-regression-reusable.yml b/.github/workflows/visual-regression-reusable.yml new file mode 100644 index 0000000..29a4bc6 --- /dev/null +++ b/.github/workflows/visual-regression-reusable.yml @@ -0,0 +1,256 @@ +name: Visual regression reusable + +on: + workflow_call: + inputs: + source: + description: ReSpec source file + required: false + type: string + default: index.html + snapshot: + description: Generated snapshot file + required: false + type: string + default: snapshot.html + base_ref: + description: Optional base ref, branch, tag, or SHA + required: false + type: string + default: "" + head_ref: + description: Optional head ref, branch, tag, or SHA + required: false + type: string + default: "" + diff_threshold: + description: Difference ratio above which a viewport is marked changed + required: false + type: string + default: "0.01" + ignore_selectors: + description: Comma or newline separated CSS selectors to hide before screenshots + required: false + type: string + default: "" + fail_on_difference: + description: Fail the workflow when a viewport exceeds diff_threshold + required: false + type: boolean + default: false + workflow_dispatch: + inputs: + source: + description: ReSpec source file + required: false + default: index.html + snapshot: + description: Generated snapshot file + required: false + default: snapshot.html + base_ref: + description: Optional base ref, branch, tag, or SHA + required: false + default: "" + head_ref: + description: Optional head ref, branch, tag, or SHA + required: false + default: "" + diff_threshold: + description: Difference ratio above which a viewport is marked changed + required: false + default: "0.01" + ignore_selectors: + description: Comma or newline separated CSS selectors to hide before screenshots + required: false + default: "" + fail_on_difference: + description: Fail the workflow when a viewport exceeds diff_threshold + required: false + type: boolean + default: false + +jobs: + visual-regression: + name: Compare ReSpec snapshots + runs-on: ubuntu-24.04 + permissions: + contents: read + env: + WORK_DIR: visual-regression + steps: + - name: Determine refs + id: refs + shell: bash + env: + BASE_REF_INPUT: ${{ inputs.base_ref }} + HEAD_REF_INPUT: ${{ inputs.head_ref }} + PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + CURRENT_SHA: ${{ github.sha }} + run: | + set -euo pipefail + + BASE_REF="$BASE_REF_INPUT" + HEAD_REF="$HEAD_REF_INPUT" + + if [[ -z "$BASE_REF" && -n "${PR_BASE_SHA:-}" ]]; then + BASE_REF="$PR_BASE_SHA" + fi + + if [[ -z "$HEAD_REF" && -n "${PR_HEAD_SHA:-}" ]]; then + HEAD_REF="$PR_HEAD_SHA" + fi + + if [[ -z "$BASE_REF" ]]; then + BASE_REF="$DEFAULT_BRANCH" + fi + + if [[ -z "$HEAD_REF" ]]; then + HEAD_REF="$CURRENT_SHA" + fi + + echo "base_ref=$BASE_REF" >> "$GITHUB_OUTPUT" + echo "head_ref=$HEAD_REF" >> "$GITHUB_OUTPUT" + echo "Base ref: $BASE_REF" + echo "Head ref: $HEAD_REF" + + - name: Determine tooling ref + id: tooling + shell: bash + env: + WORKFLOW_REF: ${{ job.workflow_ref }} + run: | + set -euo pipefail + + TOOLING_REPOSITORY="${WORKFLOW_REF%%/.github/workflows/*}" + TOOLING_REF="${WORKFLOW_REF##*@}" + + if [[ -z "$TOOLING_REPOSITORY" || -z "$TOOLING_REF" ]]; then + echo "::error title=Workflow ref ontbreekt::Kan job.workflow_ref niet parsen: $WORKFLOW_REF" + exit 1 + fi + + echo "repository=$TOOLING_REPOSITORY" >> "$GITHUB_OUTPUT" + echo "ref=$TOOLING_REF" >> "$GITHUB_OUTPUT" + echo "Tooling repository: $TOOLING_REPOSITORY" + echo "Tooling ref: $TOOLING_REF" + + - name: Checkout base + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ steps.refs.outputs.base_ref }} + path: ${{ env.WORK_DIR }}/base + + - name: Checkout head + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ steps.refs.outputs.head_ref }} + path: ${{ env.WORK_DIR }}/head + + - name: Checkout visual regression tooling + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ steps.tooling.outputs.repository }} + ref: ${{ steps.tooling.outputs.ref }} + path: ${{ env.WORK_DIR }}/template + + - name: Setup Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + + - name: Prepare ReSpec snapshots + id: prepare + shell: bash + env: + SOURCE: ${{ inputs.source }} + SNAPSHOT: ${{ inputs.snapshot }} + run: | + set -euo pipefail + + build_snapshot() { + local label="$1" + local dir="$2" + + echo "Building $label snapshot in $dir" + cd "$GITHUB_WORKSPACE/$dir" + + if [[ ! -f "$SOURCE" ]]; then + echo "::error title=Source file missing::$SOURCE not found in $dir" + exit 1 + fi + + npx --yes respec@37.3.2 --localhost --disable-sandbox --timeout 120 --src "$SOURCE" --out "$SNAPSHOT" + + # Gebruik de centrale normalizer, net als de publicatiebuild. + # Een gecommitte base-snapshot blijft de werkelijk bewaarde baseline. + node "$TOOLING_DIR/.github/workflows/normalize-mermaid-svg.mjs" "$SNAPSHOT" + } + + TOOLING_DIR="$GITHUB_WORKSPACE/$WORK_DIR/template" + (cd "$TOOLING_DIR/.github/mermaid-svg" && npm ci --ignore-scripts --no-audit --no-fund) + + if [[ -f "$GITHUB_WORKSPACE/$WORK_DIR/base/$SNAPSHOT" ]]; then + echo "Using committed base snapshot: $SNAPSHOT" + elif [[ ! -f "$GITHUB_WORKSPACE/$WORK_DIR/base/$SOURCE" ]]; then + # Bijvoorbeeld een nog lege base-branch: er is niets om mee te vergelijken. + echo "::notice title=Geen basis::Base bevat geen $SNAPSHOT of $SOURCE; de visuele vergelijking wordt overgeslagen." + echo "Visuele vergelijking overgeslagen: de base bevat geen $SNAPSHOT of $SOURCE." >> "$GITHUB_STEP_SUMMARY" + echo "skip=true" >> "$GITHUB_OUTPUT" + exit 0 + else + echo "Base snapshot missing; building fallback base snapshot." + build_snapshot "base" "$WORK_DIR/base" + fi + + build_snapshot "head" "$WORK_DIR/head" + + - name: Install comparison tooling + if: ${{ steps.prepare.outputs.skip != 'true' }} + shell: bash + run: | + set -euo pipefail + + mkdir -p "$RUNNER_TEMP/visual-regression-tools" + cp "$GITHUB_WORKSPACE/$WORK_DIR/template/scripts/visual-regression/compare.mjs" \ + "$RUNNER_TEMP/visual-regression-tools/compare.mjs" + + cd "$RUNNER_TEMP/visual-regression-tools" + npm init -y + npm install --no-audit --no-fund @playwright/test pixelmatch pngjs + npx playwright install --with-deps chromium + + - name: Compare screenshots + if: ${{ steps.prepare.outputs.skip != 'true' }} + shell: bash + env: + SNAPSHOT: ${{ inputs.snapshot }} + DIFF_THRESHOLD: ${{ inputs.diff_threshold }} + IGNORE_SELECTORS: ${{ inputs.ignore_selectors }} + FAIL_ON_DIFFERENCE: ${{ inputs.fail_on_difference }} + run: | + set -euo pipefail + + mkdir -p "$GITHUB_WORKSPACE/$WORK_DIR/report" + cd "$RUNNER_TEMP/visual-regression-tools" + + node compare.mjs \ + --base-dir "$GITHUB_WORKSPACE/$WORK_DIR/base" \ + --head-dir "$GITHUB_WORKSPACE/$WORK_DIR/head" \ + --out-dir "$GITHUB_WORKSPACE/$WORK_DIR/report" \ + --path "$SNAPSHOT" \ + --threshold "$DIFF_THRESHOLD" \ + --ignore-selectors "$IGNORE_SELECTORS" \ + --fail-on-difference "$FAIL_ON_DIFFERENCE" + + cat "$GITHUB_WORKSPACE/$WORK_DIR/report/summary.md" >> "$GITHUB_STEP_SUMMARY" + + - name: Upload visual regression report + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + if: ${{ always() && steps.prepare.outputs.skip != 'true' }} + with: + name: visual-regression-report + path: ${{ env.WORK_DIR }}/report + if-no-files-found: error diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6fd25a8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +*_log +.idea + +.github/mermaid-svg/node_modules/ +.DS_Store +__pycache__/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c80a0bf --- /dev/null +++ b/LICENSE @@ -0,0 +1,17 @@ +The W3C SOFTWARE NOTICE AND LICENSE (W3C) + +https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + +This work is being provided by the copyright holders under the following license. By obtaining and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions. + +Permission to copy, modify, and distribute this work, with or without modification, for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the work or portions thereof, including modifications: +1. The full text of this NOTICE in a location viewable to users of the redistributed or derivative work. +2. Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, the W3C Software and Document Short Notice (https://www.w3.org/Consortium/Legal/2015/copyright-software-short-notice.html) should be included. +3. Notice of any changes or modifications, through a copyright statement on the new code or document such as "This software or document includes material copied from or derived from [title and URI of the W3C document]. Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang)." + + +THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. + +COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT. + +The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the work without specific, written prior permission. Title to copyright in this work will at all times remain with copyright holders. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ffc9dc5 --- /dev/null +++ b/README.md @@ -0,0 +1,130 @@ +# NL-ReSpec-workflows + +Centrale GitHub Actions workflows voor ReSpec-documenten van Geonovum en +BROprogramma. Documentrepositories (gemaakt met +[NL-ReSpec-template](https://github.com/Geonovum/NL-ReSpec-template)) bevatten +alleen twee kleine aanroepende workflows; de build-, controle- en +publicatiestappen staan hier. + +Deze repository is bedoeld voor beheerders. Uitleg voor auteurs staat in de +README van [NL-ReSpec-template](https://github.com/Geonovum/NL-ReSpec-template). + +## Inhoud + +| Pad | Doel | +| --- | --- | +| `.github/workflows/build.yml` | Snapshot, Mermaid-normalisatie, PDF en controles (HTML, WCAG, links) | +| `.github/workflows/publish.yml` | Publicatie naar docs.geostandaarden.nl | +| `.github/workflows/visual-regression-reusable.yml` | Visuele vergelijking van snapshots | +| `.github/workflows/normalize-mermaid-svg.mjs`, `pdf.js`, `.github/mermaid-svg/` | Hulpbestanden die `build.yml` zelf ophaalt | +| `document-repo/.github/workflows/` | De aanroepende workflows (`main.yml`, `visual-regression.yml`) die naar documentrepos worden uitgerold | +| `.github/workflows/update-workflows.yml`, `scripts/`, `.github/repos.json` | Uitrol naar documentrepos | +| `.github/workflows/release-tag.yml` | Verplaatst de major-tag (`v1`) bij een nieuwe versietag | +| `.github/workflows/template-regression.yml`, `tests/` | Regressietests van deze workflows | +| `index.html`, `js/config.js`, `*.md`, `media/`, `snapshot.html` | Voorbeelddocument waarop de regressietests draaien | + +## Gebruik in een documentrepository + +Een documentrepository bevat alleen de bestanden uit +[`document-repo/.github/workflows/`](document-repo/.github/workflows/), bijvoorbeeld: + +```yaml +jobs: + build: + uses: Geonovum/NL-ReSpec-workflows/.github/workflows/build.yml@v1 +``` + +Hulpbestanden zoals de Mermaid-normalisatie en `pdf.js` haalt de centrale +workflow zelf op uit dezelfde versie van deze repository. Een fix hier bereikt +dus alle documentrepositories zonder dat daar iets hoeft te veranderen. + +## Versies + +* Elke workflowrelease krijgt een vaste tag volgens semver, bijv. `v1.0.1`. +* De tag `v1` wijst altijd naar de nieuwste `v1.x.y`. De workflow + **"Move major version tag"** verplaatst `v1` automatisch zodra een + nieuwe `v1.x.y`-tag gepusht wordt. +* Documentrepositories gebruiken `@v1`: niet-brekende wijzigingen + (fixes, nieuwe controles) krijgen ze automatisch. +* Alleen bij een brekende wijziging (bijv. andere verplichte velden in + `config.js` of andere secrets) komt er een `v2`. Dan worden de + aanroepende workflows eenmalig uitgerold met de update-workflow hieronder. +* Terugdraaien: zet `v1` terug naar de vorige `v1.x.y`-tag. + +Een nieuwe versie maken (vanaf `main`): + +```bash +git tag v1.0.1 +git push origin v1.0.1 +``` + +## Testen + +Pull requests draaien **Template regression checks**: de build en de visuele +vergelijking via de workflows van de eigen branch op het voorbeelddocument in +de root, plus de Python-tests: + +```bash +(cd .github/mermaid-svg && npm ci --ignore-scripts) +python3 -m pip install PyYAML +python3 -m unittest discover -s tests -v +``` + +## Workflows updaten in document-repos + +De aanroepende workflows in alle document-repositories kunnen centraal +bijgewerkt worden vanuit deze repository via de workflow +**"Update workflows in document repos"**. + +### Repos bijhouden (automatisch) + +Bij elke run wordt [`.github/repos.json`](.github/repos.json) eerst +automatisch bijgewerkt: + +* Repos met `js/config.js` die **nog niet in de lijst staan** worden + toegevoegd met `"updateAllow": true` +* Repos met `js/config.js` krijgen ook `respecBuildUrl` en + `respecVersion` mee op basis van `index.html` en `snapshot.html` +* Repos die **gearchiveerd of verwijderd** zijn worden uit de lijst verwijderd +* De bijgewerkte `repos.json` wordt terug gecommit naar deze repository + +Wil je een repo **uitsluiten** van updates, zet dan +`"updateAllow": false` in `repos.json`. Die repo wordt dan nooit meer +aangeraakt, ook niet bij toekomstige runs. + +Repos met een `config.js` in de root (maar nog niet in `js/`) krijgen een +aparte PR om dit bestand te verplaatsen naar `js/config.js` en meteen de +beheerde `.github`-bestanden uit deze repository mee te nemen. Zo'n repo +wordt pas bij een volgende run automatisch aan `repos.json` toegevoegd, +nadat de migratie-PR is gemerged. + +### Handmatig triggeren + +Ga naar +[Actions → Update workflows in document repos](https://github.com/Geonovum/NL-ReSpec-workflows/actions/workflows/update-workflows.yml) +en klik op **"Run workflow"**. + +* **Dry run** aanvinken om te zien welke repos bijgewerkt zouden worden, + zonder te committen of PRs aan te maken. + +### Wat wordt bijgewerkt? + +Alleen een vaste set bestanden wordt bijgewerkt. Bestaande andere +bestanden onder `.github/`, zoals extra workflows of templates, blijven +onaangeraakt. + +De volgende bestanden worden bijgewerkt, met als bron +[`document-repo/.github/workflows/`](document-repo/.github/workflows/): + +* `.github/workflows/main.yml` +* `.github/workflows/visual-regression.yml` + +De volgende verouderde kopieën worden verwijderd, omdat ze nu centraal +gebruikt worden: + +* `.github/dependabot.yml` +* `.github/mermaid-svg/package.json` en `package-lock.json` +* `.github/workflows/build.yml` +* `.github/workflows/normalize-mermaid-svg.mjs` +* `.github/workflows/pdf.js` +* `.github/workflows/publish.yml` diff --git a/abstract.md b/abstract.md new file mode 100644 index 0000000..31e641f --- /dev/null +++ b/abstract.md @@ -0,0 +1 @@ +TODO: vul in abstract.md een abstract in. \ No newline at end of file diff --git a/ch01.md b/ch01.md new file mode 100644 index 0000000..3daf6c8 --- /dev/null +++ b/ch01.md @@ -0,0 +1,16 @@ +# Niet-normatieve deel + +Bijvoorbeeld een introductie is niet normatief. + +

+Dit hoofdstuk is toegevoegd met `class="informative"` in `config.js`. +

+ +## Een subparagraaf + +Hier staat een tabel. Als de juiste style gekozen is ziet deze er goed uit. + +| Sleutel | Waarde | +| ------- | ------ | +| key | Deze waarde bevat een lange tekst zodat te zien is of de kolombreedte dynamisch wordt bepaald | + diff --git a/ch02.md b/ch02.md new file mode 100644 index 0000000..2f27834 --- /dev/null +++ b/ch02.md @@ -0,0 +1,39 @@ +# Meer inhoud + +## Definities +Definitie: Een definitie is een beschrijving van een woord. Een ander woord voor _definitie_ is betekenis of beschrijving. + +## Afbeeldingen + +Afbeeldingen krijgen een nummer en vermelding in de figurenlijst [[[#tof]]]. + +![Tekstueel alternatief voor toegankelijkheid](media/Bomos_levenscyclus.svg "Onderschrift") + +## Referenties + +Referenties kunnen op drie plaatsen staan: + +- In SpecRef [Specref](https://www.specref.org/) +- In de organisatie configuraties [[SemVer]]. Deze zijn te vinden op [tools.geostandaarden.nl](https://github.com/Geonovum/tools.geostandaarden.nl/blob/main/tools.geostandaarden.nl/respec/config/geonovum-config.js). +- In het document, zoals [[MIM12]]. Deze zijn te vinden in `js/config.js`. + +Referentie uit organisatie lijst [[SemVer]] of de locale lijst [[MIM12]]. Lijst staat in `organisation-config.js`. Alleen referenties die in de tekst voorkomen worden getoond. + +We gebruiken een definitie om een woord te omschrijven. + +## Optioneel + +De onderstaande secties (_Conformiteit_ e.d.) zijn optioneel, zie `index.html`: + +``` + +
+
+
+
+ +
+
+
+ +``` diff --git a/document-repo/.github/workflows/main.yml b/document-repo/.github/workflows/main.yml new file mode 100644 index 0000000..4f6fe34 --- /dev/null +++ b/document-repo/.github/workflows/main.yml @@ -0,0 +1,31 @@ +# Beheerd vanuit Geonovum/NL-ReSpec-workflows. Pas dit bestand niet aan in een documentrepo: +# de build- en publicatiestappen staan centraal en worden via @v1 gebruikt. +name: Main Workflow +on: + push: + branches: + - '**' + pull_request: + release: + types: [published, edited] + +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'release' && github.event.release.target_commitish || github.ref }} + cancel-in-progress: false + +jobs: + build: + permissions: + contents: write + uses: Geonovum/NL-ReSpec-workflows/.github/workflows/build.yml@v1 + + publish: + if: github.event_name == 'release' + needs: build + permissions: + contents: write + pull-requests: write + uses: Geonovum/NL-ReSpec-workflows/.github/workflows/publish.yml@v1 + secrets: + GH_APP_ID: ${{ secrets.GH_APP_ID }} + GH_APP_PRIVATE_KEY: ${{ secrets.GH_APP_PRIVATE_KEY }} diff --git a/document-repo/.github/workflows/visual-regression.yml b/document-repo/.github/workflows/visual-regression.yml new file mode 100644 index 0000000..d894b81 --- /dev/null +++ b/document-repo/.github/workflows/visual-regression.yml @@ -0,0 +1,12 @@ +# Beheerd vanuit Geonovum/NL-ReSpec-workflows. Pas dit bestand niet aan in een documentrepo. +name: Visual regression + +on: + pull_request: + workflow_dispatch: + +jobs: + visual-regression: + uses: Geonovum/NL-ReSpec-workflows/.github/workflows/visual-regression-reusable.yml@v1 + with: + fail_on_difference: false diff --git a/index.html b/index.html new file mode 100644 index 0000000..4efb8af --- /dev/null +++ b/index.html @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
+
+
+ + + + + + + + + +
+
+
+ + + diff --git a/js/config.js b/js/config.js new file mode 100644 index 0000000..841a928 --- /dev/null +++ b/js/config.js @@ -0,0 +1,128 @@ +let respecConfig = { + useLogo: true, + useLabel: true, + + // TODO: title is verplicht! Neem hieronder de titel van het document op + title: "Geonovum template voor ReSpec", + //-- specStatus is verplicht! (activeer 1 van de volgende) + // specStatus: "wv", // Werkversie + //specStatus: "cv", // Consultatieversie + //specStatus: "vv", // Versie ter vaststelling + //specStatus: "def", // Vastgestelde versie + specStatus: "basis", // Basis Document + + //-- specType is verplicht bij alle andere dan BASIS + //specType: "NO", // Norm + //specType: "ST", // Standaard + //specType: "IM", // Informatie Model + //specType: "PR", // Praktijkrichtlijn + specType: "HR", // HandReiking + //specType: "WA", // Werkafspraak + //specType: "BD", // Beheer Documentatie + //specType: "AL", // Algemeen document + //specType: "BP", // Best Practice + + //-- pubDomain is verplicht! (komt in de URL) + //-- zie: https://geonovum.github.io/handleiding-tooling/ReSpec/#pubdomain + //-- TODO: vul pubDomain in + pubDomain: "3dbv", + + //-- license: voor de geldende gebruiksvoorwaarden. Default is cc-by. + //license: "cc-by-nd", // bronvermelding, geen afgeleide werken (default) + //license: "cc0", // Public Domain Dedication + license: "cc-by", // Attribution, met bronvermelding + + //-- TODO shortName is verplicht! (komt in de URL: kies logische afkorting) + //-- Regel: shortName mag geen hoofdletters bevatten. + shortName: "nl-respec-template", + + //edDraftURI = De URI van de draft version. Deze wordt automatisch afgeleid van de github URI; maar kan hier overschreven worden. + //edDraftURI: ["https://geonovum.github.io", "/", "shortName"], + + //-- publishDate is verplicht. Als je werkversie gekozen hebt dan pakt Respec + //-- de pushdate maar de publishDate is nog steeds verplicht. + publishDate: "2026-02-09", + + //-- publishVersion is verplicht. Hij mag wel leeg zijn [], maar niet de lege string zijn "". + publishVersion: [], + + //-- Voor dit blok geldt: alleen als er eerdere versies zijn en altijd beide aan/uit! + //previousPublishDate: "2014-05-01", + //previousMaturity: "CV", + + //-- Deze gebruiken we niet binnen Geonovum + //prevVersion: "0.0.1", + + //-- TODO: de namen van de Editor(s) / Redacteur(en) + //-- vul in: per Editor: name:, company:, companyURL: + editors: + [ + { + name: "voornaam achternaam", + company: "Geonovum", + companyURL: "https://www.geonovum.nl", + } + ], + + //-- de namen van de auteur(s) + //-- vul in: per auteur: name:, company:, companyURL: + authors: + [ + { + name: "voornaam achternaam", + company: "Geonovum", + companyURL: "https://www.geonovum.nl", + } + ], + + // TODO: Vul de github URL in. + // neem hier de URL van de github repository op waar het respec document in staat + // dit zorgt voor het 'Doe mee:' onderdeel in het voorblad van de publicatie. + github: "https://github.com/Geonovum/NL-ReSpec-template", + + postProcess: [ + ...(organisationConfig.postProcess ?? []), + localizeGitHubHeaderLinks + ], + + // Create PDF and link to file in header (optional): + // TODO: Change the filename as preferred. + //alternateFormats: [ + // { + // label: "pdf", + // uri: "static/template.pdf", + // }, + //], + + // + // Lokale lijst voor bibliografie + // - Kijk eerst naar de beschikbare www.specref.org . + // - Kijk daarna in de organisatieconfig op: https://tools.geostandaarden.nl/specref/ + // - Voeg dan pas hieronder toe. + // - Zie handleiding: https://geonovum.github.io/handleiding-tooling/ReSpec/ReSpec-onderdelen/#bibliografie + // + localBiblio: + { + MIM12: { + id: "MIM12", + title: "MIM - Metamodel Informatie Modellering (Versie 1.2)", + href: "https://docs.geostandaarden.nl/mim/def-st-mim-20240613/", + status: "Definitief", + publisher: "Geonovum", + date: "2024-06-13" + } + } +}; + +function localizeGitHubHeaderLinks(_config, document) { + if (document.documentElement.lang !== "nl") { + return; + } + + const issueLink = document.querySelector( + '.head dl a[href$="/issues/"], .head dl a[href$="/issues"]' + ); + if (issueLink) { + issueLink.textContent = "Alle issues"; + } +} diff --git a/media/Bomos_levenscyclus.svg b/media/Bomos_levenscyclus.svg new file mode 100644 index 0000000..4e04d36 --- /dev/null +++ b/media/Bomos_levenscyclus.svg @@ -0,0 +1,3 @@ + + +
Creatie / Ontwikkeling
Creatie / Ontwikkeling
Adoptie
Adoptie
Introductiefase
Introductiefase
Implementatie / groei
Implementatie / groei
Volwaardige
 toepassing
[Not supported by viewer]
Uitfaseren
Uitfaseren
Tijd
Tijd
\ No newline at end of file diff --git a/media/CIM-Overzicht.png b/media/CIM-Overzicht.png new file mode 100644 index 0000000..f1be399 Binary files /dev/null and b/media/CIM-Overzicht.png differ diff --git a/mermaid.md b/mermaid.md new file mode 100644 index 0000000..8c8fd03 --- /dev/null +++ b/mermaid.md @@ -0,0 +1,13 @@ +# Mermaid diagram +
+ +```mermaid +graph TD; + A-->B; + A-->C; + B-->D; + C-->D; +``` +
Mermaid voorbeeld
+
+ diff --git a/scripts/check-localized-header-links.mjs b/scripts/check-localized-header-links.mjs new file mode 100644 index 0000000..ebeb2f6 --- /dev/null +++ b/scripts/check-localized-header-links.mjs @@ -0,0 +1,30 @@ +import { readFileSync } from "node:fs"; + +const snapshotPath = process.argv[2] ?? "snapshot.html"; +const html = readFileSync(snapshotPath, "utf8"); + +const issueLinks = findAnchorTexts(html, /\/issues\/?$/); + +if (issueLinks.includes("All issues")) { + throw new Error("De GitHub-issueslink op het voorblad is nog Engelstalig."); +} + +if (!issueLinks.includes("Alle issues")) { + throw new Error("De GitHub-issueslink op het voorblad mist de tekst 'Alle issues'."); +} + +function findAnchorTexts(html, hrefPattern) { + const texts = []; + const anchorPattern = /]*href=(["'])(.*?)\1[^>]*>([\s\S]*?)<\/a>/gi; + for (const match of html.matchAll(anchorPattern)) { + const [, , href, text] = match; + if (hrefPattern.test(href)) { + texts.push(stripTags(text).trim().replace(/\s+/g, " ")); + } + } + return texts; +} + +function stripTags(value) { + return value.replace(/<[^>]*>/g, ""); +} diff --git a/scripts/lib/repository-migration.mjs b/scripts/lib/repository-migration.mjs new file mode 100644 index 0000000..4e46dc9 --- /dev/null +++ b/scripts/lib/repository-migration.mjs @@ -0,0 +1,40 @@ +import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +function isChecksIgnoreRule(line) { + const pattern = line.trim(); + const normalized = pattern.replace(/^!/, "").replace(/^\//, ""); + return normalized === ".checks" || normalized.startsWith(".checks/"); +} + +export function migrateChecksDirectory(targetRepoDir) { + const changedPaths = []; + const gitignorePath = path.join(targetRepoDir, ".gitignore"); + + if (existsSync(gitignorePath)) { + const original = readFileSync(gitignorePath, "utf8"); + const lineEnding = original.includes("\r\n") ? "\r\n" : "\n"; + const hasTrailingNewline = /\r?\n$/.test(original); + const lines = original.split(/\r?\n/); + + if (hasTrailingNewline) { + lines.pop(); + } + + const updatedLines = lines.filter((line) => !isChecksIgnoreRule(line)); + const updated = `${updatedLines.join(lineEnding)}${hasTrailingNewline ? lineEnding : ""}`; + + if (updated !== original) { + writeFileSync(gitignorePath, updated); + changedPaths.push(".gitignore"); + } + } + + const checksPath = path.join(targetRepoDir, ".checks"); + if (existsSync(checksPath)) { + rmSync(checksPath, { recursive: true, force: true }); + changedPaths.push(".checks"); + } + + return changedPaths; +} diff --git a/scripts/lib/template-leftovers.mjs b/scripts/lib/template-leftovers.mjs new file mode 100644 index 0000000..dba8e4d --- /dev/null +++ b/scripts/lib/template-leftovers.mjs @@ -0,0 +1,95 @@ +import { existsSync, rmSync } from "node:fs"; +import path from "node:path"; +import { runCommand } from "./workflow-utils.mjs"; + +// Bestanden die met "Use this template" uit NL-ReSpec-template in documentrepos +// terecht zijn gekomen, maar alleen bij de centrale tooling horen. Ze worden +// alleen verwijderd als de inhoud exact gelijk is aan een versie uit de +// geschiedenis van deze repository; aangepaste of eigen bestanden blijven staan. +export const TEMPLATE_LEFTOVER_FILES = [ + ".github/repos.json", + ".github/workflows/check.yml", + ".github/workflows/release-tag.yml", + ".github/workflows/template-regression.yml", + ".github/workflows/update-workflows.yml", + ".github/workflows/visual-regression-reusable.yml", + "publicatie_finder.sh", + "replace_workflow-local.ps1", + "replace_workflow-local.sh", + "replace_workflow.sh", + "scripts/check-localized-header-links.mjs", + "scripts/lib/repository-migration.mjs", + "scripts/lib/workflow-utils.mjs", + "scripts/sync-repos.mjs", + "scripts/update-document-repos.mjs", + "scripts/visual-regression/compare.mjs", + "tests/fixtures/mermaid/README.md", + "tests/fixtures/mermaid/data-image.html", + "tests/fixtures/mermaid/sensordata.html", + "tests/test_central_workflows.py", + "tests/test_mermaid_svg_normalization.py", + "tests/test_publication_preflight.py", + "tests/test_release_writeback_policy.py", + "tests/test_repository_migration.py", + "tests/verify_mermaid_rendering.mjs", +]; + +const NULL_BLOB = /^0+$/; + +// Alle blob-SHA's die de kandidaten ooit hadden in de geschiedenis van historyRepoDir. +export function knownTemplateBlobs(historyRepoDir, files = TEMPLATE_LEFTOVER_FILES) { + const shallow = runCommand("git", ["rev-parse", "--is-shallow-repository"], { + cwd: historyRepoDir, + description: "git rev-parse --is-shallow-repository", + }).stdout.trim(); + if (shallow === "true") { + console.log("⚠️ Geschiedenis is shallow; alleen bekende versies worden opgeruimd."); + } + + const result = runCommand( + "git", + ["log", "--all", "--raw", "--no-abbrev", "--no-renames", "--format=", "--", ...files], + { cwd: historyRepoDir, description: "git log --raw kandidaten" }, + ); + + const known = new Map(files.map((file) => [file, new Set()])); + for (const line of result.stdout.split("\n")) { + // :100644 100644 M\t + const match = line.match(/^:\d+ \d+ ([0-9a-f]+) ([0-9a-f]+) \w+\t(.+)$/); + if (!match || !known.has(match[3])) { + continue; + } + for (const blob of [match[1], match[2]]) { + if (!NULL_BLOB.test(blob)) { + known.get(match[3]).add(blob); + } + } + } + return known; +} + +// Verwijdert exacte kopieën uit targetRepoDir en geeft de verwijderde paden terug. +export function removeTemplateLeftovers(targetRepoDir, knownBlobs) { + const removed = []; + + for (const [file, blobs] of knownBlobs) { + const target = path.join(targetRepoDir, file); + if (!existsSync(target)) { + continue; + } + + const blob = runCommand("git", ["hash-object", "--", file], { + cwd: targetRepoDir, + description: `git hash-object ${file}`, + }).stdout.trim(); + + if (blobs.has(blob)) { + rmSync(target, { force: true }); + removed.push(file); + } else { + console.log(`⏩ ${file} overgeslagen: aangepast t.o.v. de template.`); + } + } + + return removed; +} diff --git a/scripts/lib/workflow-utils.mjs b/scripts/lib/workflow-utils.mjs new file mode 100644 index 0000000..c76d2c6 --- /dev/null +++ b/scripts/lib/workflow-utils.mjs @@ -0,0 +1,276 @@ +import { spawnSync } from "node:child_process"; +import { readFile, writeFile } from "node:fs/promises"; + +const API_BASE_URL = "https://api.github.com"; +const USER_AGENT = "NL-ReSpec-workflows"; + +export function parseArgs(argv) { + const args = {}; + + for (let index = 0; index < argv.length; index += 1) { + const arg = argv[index]; + if (!arg.startsWith("--")) { + continue; + } + + const key = arg.slice(2); + const next = argv[index + 1]; + if (!next || next.startsWith("--")) { + args[key] = "true"; + continue; + } + + args[key] = next; + index += 1; + } + + return args; +} + +export function requireArg(args, name) { + const value = args[name]; + if (!value) { + throw new Error(`Ontbrekend argument: --${name}`); + } + return value; +} + +export function readJson(filePath) { + return readFile(filePath, "utf8").then((contents) => JSON.parse(contents)); +} + +export function writeJson(filePath, data) { + return writeFile(filePath, `${JSON.stringify(data, null, 2)}\n`); +} + +export async function readTextIfExists(filePath) { + try { + return await readFile(filePath, "utf8"); + } catch (error) { + if (error && error.code === "ENOENT") { + return ""; + } + throw error; + } +} + +export function hasOwn(object, property) { + return Object.prototype.hasOwnProperty.call(object, property); +} + +export function extractRespecBuildUrl(html) { + if (!html) { + return null; + } + + const scriptTagPattern = /]*\bsrc="([^"]+)"/gi; + for (const match of html.matchAll(scriptTagPattern)) { + const candidate = match[1]; + if (!candidate.includes("respec")) { + continue; + } + if (candidate.includes("respec-mermaid")) { + continue; + } + if (candidate.includes("/config/")) { + continue; + } + if (candidate.endsWith("config.js")) { + continue; + } + return candidate; + } + + return null; +} + +export function extractRespecVersion(html) { + if (!html) { + return null; + } + + const generatorMatch = + html.match(/]*content=["']ReSpec\s+([^"']+)["']/i) ?? + html.match(/]*content=["']ReSpec\s+([^"']+)["'][^>]*name=["']generator["']/i); + + return generatorMatch ? generatorMatch[1] : null; +} + +export function logSection(title) { + console.log(""); + console.log(`=== ${title} ===`); +} + +export function runCommand(command, args, options = {}) { + const result = spawnSync(command, args, { + cwd: options.cwd, + env: { + ...process.env, + ...(options.env ?? {}), + }, + encoding: "utf8", + }); + + if (result.error) { + throw result.error; + } + + const status = result.status ?? 1; + if (status !== 0 && !options.allowFailure) { + const error = new Error( + `${options.description ?? command} mislukte met exitcode ${status}${ + result.stderr?.trim() ? `: ${result.stderr.trim()}` : "" + }`, + ); + error.status = status; + error.stdout = result.stdout ?? ""; + error.stderr = result.stderr ?? ""; + throw error; + } + + return { + status, + stdout: result.stdout ?? "", + stderr: result.stderr ?? "", + }; +} + +function encodePath(path) { + return path + .split("/") + .map((segment) => encodeURIComponent(segment)) + .join("/"); +} + +export class GitHubClient { + constructor(token) { + if (!token) { + throw new Error("GitHub token ontbreekt."); + } + + this.token = token; + } + + async request(path, options = {}) { + const response = await fetch(`${API_BASE_URL}${path}`, { + method: options.method ?? "GET", + headers: { + Accept: options.accept ?? "application/vnd.github+json", + Authorization: `Bearer ${this.token}`, + "User-Agent": USER_AGENT, + "X-GitHub-Api-Version": "2022-11-28", + ...(options.headers ?? {}), + }, + body: options.body ? JSON.stringify(options.body) : undefined, + }); + + if (options.allow404 && response.status === 404) { + return null; + } + + if (!response.ok) { + const body = await response.text(); + throw new Error( + `GitHub API ${options.method ?? "GET"} ${path} mislukte (${response.status}): ${body.slice(0, 500)}`, + ); + } + + if (response.status === 204) { + return null; + } + + const contentType = response.headers.get("content-type") ?? ""; + if (contentType.includes("application/json")) { + return response.json(); + } + + return response.text(); + } + + async listActiveRepos(org) { + const repos = []; + + for (let page = 1; ; page += 1) { + const batch = await this.request( + `/orgs/${encodeURIComponent(org)}/repos?per_page=100&page=${page}&type=all`, + ); + + if (!Array.isArray(batch) || batch.length === 0) { + break; + } + + for (const repo of batch) { + if (!repo.archived && !repo.disabled) { + repos.push(repo.name); + } + } + + if (batch.length < 100) { + break; + } + } + + return repos; + } + + async fileExists(owner, repo, path) { + const data = await this.request( + `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/contents/${encodePath(path)}`, + { + allow404: true, + }, + ); + + return data !== null; + } + + async getRawFile(owner, repo, path) { + return this.request( + `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/contents/${encodePath(path)}`, + { + accept: "application/vnd.github.raw", + allow404: true, + }, + ); + } + + async getDefaultBranch(owner, repo) { + const data = await this.request( + `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`, + ); + + return data.default_branch; + } + + async findOpenPullRequestByHead(owner, repo, headBranch) { + const params = new URLSearchParams({ + state: "open", + head: `${owner}:${headBranch}`, + }); + const pulls = await this.request( + `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls?${params.toString()}`, + ); + + return pulls[0] ?? null; + } + + async createPullRequest(owner, repo, payload) { + return this.request( + `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls`, + { + method: "POST", + body: payload, + }, + ); + } + + async updatePullRequest(owner, repo, number, payload) { + return this.request( + `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${number}`, + { + method: "PATCH", + body: payload, + }, + ); + } +} diff --git a/scripts/sync-repos.mjs b/scripts/sync-repos.mjs new file mode 100644 index 0000000..481824b --- /dev/null +++ b/scripts/sync-repos.mjs @@ -0,0 +1,115 @@ +import { + GitHubClient, + extractRespecBuildUrl, + extractRespecVersion, + hasOwn, + logSection, + parseArgs, + readJson, + requireArg, + writeJson, +} from "./lib/workflow-utils.mjs"; + +const ORG_TOKENS = [ + { + org: "Geonovum", + token: process.env.GH_TOKEN_GEONOVUM ?? "", + }, + { + org: "BROprogramma", + token: process.env.GH_TOKEN_BROPROGRAMMA ?? "", + }, +]; + +const args = parseArgs(process.argv.slice(2)); +const reposFile = requireArg(args, "repos-file"); +const selfOwner = requireArg(args, "self-owner"); +const selfRepo = requireArg(args, "self-repo"); + +const reposJson = await readJson(reposFile); + +function ensureOrg(org) { + if (!reposJson[org]) { + reposJson[org] = { repos: {} }; + } + if (!reposJson[org].repos) { + reposJson[org].repos = {}; + } + return reposJson[org].repos; +} + +function upsertRepoMetadata(repos, repo, defaultUpdateAllow, metadata) { + const existing = repos[repo] ?? {}; + repos[repo] = { + ...existing, + updateAllow: hasOwn(existing, "updateAllow") ? existing.updateAllow : defaultUpdateAllow, + respecBuildUrl: metadata.respecBuildUrl, + respecVersion: metadata.respecVersion, + }; +} + +async function getRemoteRepoMetadata(client, org, repo) { + const [indexHtml, snapshotHtml] = await Promise.all([ + client.getRawFile(org, repo, "index.html"), + client.getRawFile(org, repo, "snapshot.html"), + ]); + + return { + respecBuildUrl: extractRespecBuildUrl(indexHtml ?? ""), + respecVersion: extractRespecVersion(snapshotHtml ?? ""), + }; +} + +async function scanOrg(org, token) { + if (!token) { + console.log(`⚠️ Geen token voor ${org}, sync overgeslagen.`); + return; + } + + logSection(`Sync ${org}`); + + const client = new GitHubClient(token); + const repos = ensureOrg(org); + const allRepos = await client.listActiveRepos(org); + const activeRepos = new Set(); + + for (const repo of allRepos) { + if (!repo || repo === ".github") { + continue; + } + + // Deze workflows-repo heeft een voorbeelddocument (js/config.js) voor de + // regressietests, maar is zelf geen documentrepo. + if (org === selfOwner && repo === selfRepo) { + console.log(`⏩ Workflows-repo overgeslagen: ${org}/${repo}`); + continue; + } + + const hasJsConfig = await client.fileExists(org, repo, "js/config.js"); + if (!hasJsConfig) { + continue; + } + + activeRepos.add(repo); + + if (!hasOwn(repos, repo)) { + console.log(`➕ Nieuw: ${org}/${repo}`); + } + + const metadata = await getRemoteRepoMetadata(client, org, repo); + upsertRepoMetadata(repos, repo, true, metadata); + } + + for (const repo of Object.keys(repos)) { + if (!activeRepos.has(repo)) { + console.log(`🗑️ Verwijderd (niet meer actief): ${org}/${repo}`); + delete repos[repo]; + } + } +} + +for (const { org, token } of ORG_TOKENS) { + await scanOrg(org, token); +} + +await writeJson(reposFile, reposJson); diff --git a/scripts/update-document-repos.mjs b/scripts/update-document-repos.mjs new file mode 100644 index 0000000..bf75019 --- /dev/null +++ b/scripts/update-document-repos.mjs @@ -0,0 +1,412 @@ +import { cpSync, existsSync, mkdirSync, mkdtempSync, renameSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { + GitHubClient, + logSection, + parseArgs, + readJson, + requireArg, + runCommand, +} from "./lib/workflow-utils.mjs"; +import { migrateChecksDirectory } from "./lib/repository-migration.mjs"; +import { knownTemplateBlobs, removeTemplateLeftovers } from "./lib/template-leftovers.mjs"; + +// Documentrepos bevatten alleen de aanroepende workflows; build en publicatie +// worden centraal via `uses: ...@v1` uit dit template gebruikt. +const MANAGED_FILES = [ + "workflows/main.yml", + "workflows/visual-regression.yml", +]; + +const REMOVED_MANAGED_FILES = [ + "dependabot.yml", + "mermaid-svg/package.json", + "mermaid-svg/package-lock.json", + "workflows/build.yml", + "workflows/normalize-mermaid-svg.mjs", + "workflows/pdf.js", + "workflows/publish.yml", +]; + +const args = parseArgs(process.argv.slice(2)); +const org = requireArg(args, "org"); +const reposFile = requireArg(args, "repos-file"); +const templateGithubDir = path.resolve(requireArg(args, "template-github-dir")); +const selfOwner = requireArg(args, "self-owner"); +const selfRepo = requireArg(args, "self-repo"); +const token = process.env.GH_TOKEN ?? ""; +const dryRun = (process.env.DRY_RUN ?? "false") === "true"; + +if (!token) { + throw new Error("GH_TOKEN ontbreekt."); +} + +const client = new GitHubClient(token); +const reposJson = await readJson(reposFile); +const reposConfig = reposJson[org]?.repos ?? {}; +const reposToUpdate = Object.entries(reposConfig) + .filter(([, config]) => config.updateAllow === true) + .map(([repo]) => repo); + +const configStateCache = new Map(); + +// Exacte kopieën van template-tooling worden herkend aan de geschiedenis van +// deze repository (de geïmporteerde geschiedenis van NL-ReSpec-template). +const toolingRepoDir = runCommand("git", ["rev-parse", "--show-toplevel"], { + cwd: templateGithubDir, + description: "git rev-parse --show-toplevel", +}).stdout.trim(); +const templateBlobs = knownTemplateBlobs(toolingRepoDir); + +function remoteUrl(owner, repo) { + return `https://x-access-token:${encodeURIComponent(token)}@github.com/${owner}/${repo}.git`; +} + +function copyManagedFiles(targetRepoDir) { + const stagedPaths = []; + + for (const relativePath of MANAGED_FILES) { + const source = path.join(templateGithubDir, relativePath); + const target = path.join(targetRepoDir, ".github", relativePath); + mkdirSync(path.dirname(target), { recursive: true }); + cpSync(source, target); + stagedPaths.push(path.join(".github", relativePath)); + } + + return stagedPaths; +} + +function removeDeprecatedManagedFiles(targetRepoDir) { + const changedPaths = []; + + for (const relativePath of REMOVED_MANAGED_FILES) { + const target = path.join(targetRepoDir, ".github", relativePath); + if (existsSync(target)) { + rmSync(target, { force: true }); + changedPaths.push(path.join(".github", relativePath)); + } + } + + return changedPaths; +} + +function gitDiffHasChanges(cwd) { + const result = runCommand("git", ["diff", "--staged", "--quiet"], { + cwd, + allowFailure: true, + description: "git diff --staged --quiet", + }); + + if (result.status === 0) { + return false; + } + + if (result.status === 1) { + return true; + } + + throw new Error("git diff --staged --quiet gaf een onverwachte exitcode."); +} + +function listStagedFiles(cwd) { + const result = runCommand("git", ["diff", "--staged", "--name-only"], { + cwd, + description: "git diff --staged --name-only", + }); + + return result.stdout + .split("\n") + .map((line) => line.trim()) + .filter(Boolean); +} + +async function getConfigState(repo) { + if (configStateCache.has(repo)) { + return configStateCache.get(repo); + } + + const [hasJsConfig, hasRootConfig] = await Promise.all([ + client.fileExists(org, repo, "js/config.js"), + client.fileExists(org, repo, "config.js"), + ]); + + const state = { hasJsConfig, hasRootConfig }; + configStateCache.set(repo, state); + return state; +} + +function cloneRepo(owner, repo, defaultBranch) { + const tempDir = mkdtempSync(path.join(tmpdir(), `nl-respec-${repo}-`)); + + try { + runCommand( + "git", + ["clone", "--quiet", "--depth", "1", "--branch", defaultBranch, remoteUrl(owner, repo), tempDir], + { + description: `git clone ${owner}/${repo}`, + }, + ); + } catch (error) { + rmSync(tempDir, { recursive: true, force: true }); + throw error; + } + + return tempDir; +} + +function configureGit(cwd) { + runCommand("git", ["config", "user.email", "github-actions[bot]@users.noreply.github.com"], { + cwd, + description: "git config user.email", + }); + runCommand("git", ["config", "user.name", "github-actions[bot]"], { + cwd, + description: "git config user.name", + }); +} + +async function createConfigMigrationPr(repo) { + const prTitle = "chore: verplaats config.js naar js/config.js en update workflows"; + const prBody = + "Deze PR migreert de repository naar de actuele NL-ReSpec-template structuur, met workflows uit NL-ReSpec-workflows.\n\n" + + "Wijzigingen:\n" + + "- verplaatst `config.js` naar `js/config.js`\n" + + "- voegt de beheerde GitHub Actions workflows uit NL-ReSpec-workflows toe of werkt ze bij\n" + + "- verwijdert de verouderde `.checks`-map en bijbehorende `.gitignore`-regels\n\n" + + "Na merge wordt de repo bij een volgende run automatisch opgenomen in `repos.json`, omdat `js/config.js` dan aanwezig is."; + + console.log("📦 config.js in root, nog niet in js/ — migratie-PR voorbereiden."); + + if (dryRun) { + return { result: "dry-run" }; + } + + const defaultBranch = await client.getDefaultBranch(org, repo); + const branchName = "chore/verplaats-config-js-naar-js-map"; + const repoDir = cloneRepo(org, repo, defaultBranch); + + try { + configureGit(repoDir); + + runCommand("git", ["checkout", "-b", branchName], { + cwd: repoDir, + description: "git checkout -b", + }); + + mkdirSync(path.join(repoDir, "js"), { recursive: true }); + renameSync(path.join(repoDir, "config.js"), path.join(repoDir, "js", "config.js")); + + const stagedPaths = copyManagedFiles(repoDir); + const removedPaths = removeDeprecatedManagedFiles(repoDir); + const migratedPaths = migrateChecksDirectory(repoDir); + const leftoverPaths = removeTemplateLeftovers(repoDir, templateBlobs); + runCommand( + "git", + [ + "add", + "-A", + "--", + "config.js", + "js/config.js", + ...stagedPaths, + ...removedPaths, + ...migratedPaths, + ...leftoverPaths, + ], + { + cwd: repoDir, + description: "git add migratiebestanden", + }, + ); + + if (!gitDiffHasChanges(repoDir)) { + console.log("✅ Geen wijzigingen voor migratie-PR."); + return { result: "no-change" }; + } + + runCommand( + "git", + ["commit", "-m", "chore: verplaats config.js naar js/config.js en update workflows"], + { + cwd: repoDir, + description: "git commit migratie-PR", + }, + ); + runCommand("git", ["push", "origin", branchName, "--force"], { + cwd: repoDir, + description: "git push migratie-PR", + }); + + const existingPr = await client.findOpenPullRequestByHead(org, repo, branchName); + if (existingPr) { + await client.updatePullRequest(org, repo, existingPr.number, { + title: prTitle, + body: prBody, + }); + console.log(`🔄 PR #${existingPr.number} bijgewerkt.`); + return { result: "updated-pr" }; + } + + const createdPr = await client.createPullRequest(org, repo, { + title: prTitle, + body: prBody, + base: defaultBranch, + head: branchName, + }); + console.log(`✅ PR #${createdPr.number} aangemaakt.`); + return { result: "created-pr" }; + } finally { + rmSync(repoDir, { recursive: true, force: true }); + } +} + +async function updateManagedFiles(repo) { + const defaultBranch = await client.getDefaultBranch(org, repo); + const repoDir = cloneRepo(org, repo, defaultBranch); + + try { + configureGit(repoDir); + + const stagedPaths = copyManagedFiles(repoDir); + const removedPaths = removeDeprecatedManagedFiles(repoDir); + const migratedPaths = migrateChecksDirectory(repoDir); + const leftoverPaths = removeTemplateLeftovers(repoDir, templateBlobs); + runCommand("git", ["add", "-A", "--", ...stagedPaths, ...removedPaths, ...migratedPaths, ...leftoverPaths], { + cwd: repoDir, + description: "git add templatebestanden", + }); + + if (!gitDiffHasChanges(repoDir)) { + console.log("✅ Geen wijzigingen."); + return { result: "no-change" }; + } + + if (dryRun) { + console.log("🔍 Dry run — gewijzigde bestanden:"); + for (const file of listStagedFiles(repoDir)) { + console.log(file); + } + return { result: "dry-run" }; + } + + runCommand( + "git", + ["commit", "-m", "chore: update workflows vanuit NL-ReSpec-workflows"], + { + cwd: repoDir, + description: "git commit template-update", + }, + ); + runCommand("git", ["push", "origin", defaultBranch], { + cwd: repoDir, + description: "git push workflow-update", + }); + console.log(`✅ Gecommit op ${defaultBranch}.`); + return { result: "updated" }; + } finally { + rmSync(repoDir, { recursive: true, force: true }); + } +} + +let updated = 0; +let skipped = 0; +let failed = 0; +let migrationPrs = 0; +const wouldUpdate = []; +const migrationTargets = []; + +const allRepos = await client.listActiveRepos(org); + +for (const repo of allRepos) { + if (!repo || repo === ".github") { + continue; + } + + if (org === selfOwner && repo === selfRepo) { + continue; + } + + const { hasJsConfig, hasRootConfig } = await getConfigState(repo); + if (!hasRootConfig || hasJsConfig) { + continue; + } + + logSection(`${org}/${repo}`); + + try { + const outcome = await createConfigMigrationPr(repo); + if (outcome.result === "dry-run") { + migrationTargets.push(`${org}/${repo} (config.js → js/config.js + templatebestanden)`); + } else if (outcome.result === "created-pr" || outcome.result === "updated-pr") { + migrationPrs += 1; + } + } catch (error) { + console.error(`❌ Fout bij ${org}/${repo}: ${error.message}`); + failed += 1; + } +} + +for (const repo of reposToUpdate) { + if (!repo || repo === ".github") { + continue; + } + + if (org === selfOwner && repo === selfRepo) { + console.log(`⏩ Template repo overgeslagen: ${org}/${repo}`); + skipped += 1; + continue; + } + + logSection(`${org}/${repo}`); + + try { + const { hasJsConfig, hasRootConfig } = await getConfigState(repo); + + if (hasRootConfig && !hasJsConfig) { + console.log("⏩ Root-level config.js; migratie-PR wordt centraal afgehandeld."); + skipped += 1; + continue; + } + + if (!hasJsConfig) { + console.log("⏩ Geen js/config.js of config.js, overslaan."); + skipped += 1; + continue; + } + + const outcome = await updateManagedFiles(repo); + if (outcome.result === "updated") { + updated += 1; + } else if (outcome.result === "dry-run") { + wouldUpdate.push(`${org}/${repo}`); + } + } catch (error) { + console.error(`❌ Fout bij ${org}/${repo}: ${error.message}`); + failed += 1; + } +} + +console.log(""); +console.log("════════════════════════════════════════"); +console.log(`Samenvatting ${org}`); +if (dryRun) { + console.log(` Zou bijwerken (template): ${wouldUpdate.length}`); + for (const repo of wouldUpdate) { + console.log(` - ${repo}`); + } + console.log(` Zou migratie-PRs maken: ${migrationTargets.length}`); + for (const repo of migrationTargets) { + console.log(` - ${repo}`); + } +} else { + console.log(` Bijgewerkt (.github): ${updated}`); + console.log(` Migratie-PRs: ${migrationPrs}`); +} +console.log(` Overgeslagen: ${skipped}`); +console.log(` Mislukt: ${failed}`); +console.log("════════════════════════════════════════"); + +if (failed > 0) { + process.exit(1); +} diff --git a/scripts/visual-regression/compare.mjs b/scripts/visual-regression/compare.mjs new file mode 100644 index 0000000..14ca2b4 --- /dev/null +++ b/scripts/visual-regression/compare.mjs @@ -0,0 +1,530 @@ +import http from "node:http"; +import { existsSync } from "node:fs"; +import { mkdir, readFile, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { chromium } from "@playwright/test"; +import pixelmatch from "pixelmatch"; +import { PNG } from "pngjs"; + +const MIME_TYPES = new Map([ + [".css", "text/css"], + [".gif", "image/gif"], + [".html", "text/html; charset=utf-8"], + [".jpeg", "image/jpeg"], + [".jpg", "image/jpeg"], + [".js", "text/javascript"], + [".json", "application/json"], + [".png", "image/png"], + [".svg", "image/svg+xml"], + [".txt", "text/plain; charset=utf-8"], + [".webp", "image/webp"], +]); + +const VIEWPORTS = [ + { name: "desktop", width: 1440, height: 1200 }, + { name: "tablet", width: 1024, height: 1200 }, + { name: "mobile", width: 390, height: 1200 }, +]; + +function parseArgs(argv) { + const args = {}; + + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (!arg.startsWith("--")) { + throw new Error(`Unexpected argument: ${arg}`); + } + + const key = arg.slice(2); + const value = argv[i + 1]; + if (value === undefined || value.startsWith("--")) { + throw new Error(`Missing value for --${key}`); + } + + args[key] = value; + i += 1; + } + + return args; +} + +function required(args, key) { + if (!args[key]) { + throw new Error(`Missing required argument --${key}`); + } + + return args[key]; +} + +function optional(args, key, defaultValue = "") { + return args[key] ?? defaultValue; +} + +function parseSelectors(value) { + return value + .split(/[\n,]/) + .map((selector) => selector.trim()) + .filter(Boolean); +} + +function normalizeRelativeUrl(value) { + return value.replace(/^\/+/, ""); +} + +function escapeHtml(value) { + return String(value) + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """); +} + +async function startStaticServer(rootDir) { + const root = path.resolve(rootDir); + + const server = http.createServer(async (request, response) => { + try { + const requestUrl = new URL(request.url ?? "/", "http://localhost"); + const relativePath = decodeURIComponent(requestUrl.pathname); + let filePath = path.resolve(root, `.${relativePath}`); + + if (!filePath.startsWith(root)) { + response.writeHead(403); + response.end("Forbidden"); + return; + } + + const fileStat = await stat(filePath); + if (fileStat.isDirectory()) { + filePath = path.join(filePath, "index.html"); + } + + const body = await readFile(filePath); + const contentType = MIME_TYPES.get(path.extname(filePath)) ?? "application/octet-stream"; + response.writeHead(200, { "content-type": contentType }); + response.end(body); + } catch { + response.writeHead(404); + response.end("Not found"); + } + }); + + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + + const address = server.address(); + return { + url: `http://127.0.0.1:${address.port}`, + close: () => new Promise((resolve) => server.close(resolve)), + }; +} + +async function waitForStablePage(page, url) { + await page.goto(url, { waitUntil: "networkidle", timeout: 90_000 }); + await page.evaluate(async () => { + if (document.fonts?.ready) { + await document.fonts.ready; + } + }); + await page.waitForTimeout(500); +} + +async function applyIgnoredSelectors(page, selectors) { + if (selectors.length === 0) { + return; + } + + const css = selectors + .map((selector) => `${selector} { visibility: hidden !important; }`) + .join("\n"); + + await page.addStyleTag({ content: css }); +} + +async function getPageMetrics(page) { + return page.evaluate(() => { + const root = document.scrollingElement ?? document.documentElement; + const viewportWidth = window.innerWidth; + const scrollWidth = Math.ceil(root.scrollWidth); + const scrollHeight = Math.ceil(root.scrollHeight); + + const overflowElements = Array.from(document.body.querySelectorAll("*")) + .map((element) => { + const rect = element.getBoundingClientRect(); + + if (rect.width <= 0 || rect.height <= 0) { + return null; + } + + if (rect.right <= viewportWidth + 1 && rect.left >= -1) { + return null; + } + + const id = element.id ? `#${element.id}` : ""; + const classes = Array.from(element.classList) + .slice(0, 3) + .map((className) => `.${className}`) + .join(""); + const text = (element.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 80); + + return { + selector: `${element.tagName.toLowerCase()}${id}${classes}`, + left: Math.round(rect.left), + right: Math.round(rect.right), + width: Math.round(rect.width), + text, + }; + }) + .filter(Boolean) + .slice(0, 10); + + const headings = Array.from(document.querySelectorAll("h1, h2, h3, h4, h5, h6")) + .map((heading) => ({ + level: heading.tagName.toLowerCase(), + text: (heading.textContent ?? "").replace(/\s+/g, " ").trim(), + })) + .filter((heading) => heading.text); + + return { + scrollWidth, + scrollHeight, + viewportWidth, + hasHorizontalOverflow: scrollWidth > viewportWidth + 1, + overflowElements, + headings, + }; + }); +} + +async function captureViewportWidthFullPage(page, imagePath, viewport, pageHeight) { + const target = new PNG({ width: viewport.width, height: pageHeight }); + + for (let y = 0; y < pageHeight; y += viewport.height) { + const height = Math.min(viewport.height, pageHeight - y); + + await page.evaluate((scrollY) => { + window.scrollTo(0, scrollY); + }, y); + await page.waitForTimeout(50); + + const tileBuffer = await page.screenshot({ + clip: { + x: 0, + y: 0, + width: viewport.width, + height, + }, + }); + const tile = PNG.sync.read(tileBuffer); + PNG.bitblt(tile, target, 0, 0, viewport.width, height, 0, y); + } + + await writeFile(imagePath, PNG.sync.write(target)); +} + +async function capturePage(page, url, imagePath, selectors, viewport) { + await waitForStablePage(page, url); + await applyIgnoredSelectors(page, selectors); + + const metrics = await getPageMetrics(page); + await captureViewportWidthFullPage(page, imagePath, viewport, metrics.scrollHeight); + + return metrics; +} + +function padPng(source, width, height) { + if (source.width === width && source.height === height) { + return source; + } + + const target = new PNG({ width, height, fill: true }); + PNG.bitblt(source, target, 0, 0, source.width, source.height, 0, 0); + return target; +} + +async function compareImages(basePath, headPath, diffPath) { + const base = PNG.sync.read(await readFile(basePath)); + const head = PNG.sync.read(await readFile(headPath)); + const width = Math.max(base.width, head.width); + const height = Math.max(base.height, head.height); + const paddedBase = padPng(base, width, height); + const paddedHead = padPng(head, width, height); + const diff = new PNG({ width, height }); + const diffPixels = pixelmatch( + paddedBase.data, + paddedHead.data, + diff.data, + width, + height, + { threshold: 0.1 }, + ); + + await writeFile(diffPath, PNG.sync.write(diff)); + + return { + diffPixels, + totalPixels: width * height, + ratio: diffPixels / (width * height), + baseSize: `${base.width}x${base.height}`, + headSize: `${head.width}x${head.height}`, + comparedSize: `${width}x${height}`, + }; +} + +async function writeReports(outDir, results, threshold, failOnDifference) { + const changed = results.filter((result) => result.ratio > threshold); + const overflowed = results.filter( + (result) => result.baseMetrics.hasHorizontalOverflow || result.headMetrics.hasHorizontalOverflow, + ); + const outlineDiff = compareHeadings(results[0]?.baseMetrics.headings ?? [], results[0]?.headMetrics.headings ?? []); + const summaryLines = [ + "# Visual regression", + "", + `Threshold: ${(threshold * 100).toFixed(2)}%`, + `Fail on difference: ${failOnDifference}`, + `Changed viewports: ${changed.length}/${results.length}`, + `Horizontal overflow: ${overflowed.length}/${results.length}`, + `Heading changes: ${outlineDiff.added.length} added, ${outlineDiff.removed.length} removed`, + "", + "| viewport | difference | base | head | overflow |", + "| --- | ---: | --- | --- | --- |", + ...results.map((result) => { + const percentage = `${(result.ratio * 100).toFixed(3)}%`; + const overflow = [ + result.baseMetrics.hasHorizontalOverflow ? `base ${result.baseMetrics.scrollWidth}px` : "", + result.headMetrics.hasHorizontalOverflow ? `head ${result.headMetrics.scrollWidth}px` : "", + ].filter(Boolean).join(", ") || "no"; + return `| ${result.name} | ${percentage} | ${result.baseSize} | ${result.headSize} | ${overflow} |`; + }), + "", + ]; + + const htmlRows = results.map((result) => ` +
+

${escapeHtml(result.name)} - ${(result.ratio * 100).toFixed(3)}%

+

Base: ${escapeHtml(result.baseSize)}. Head: ${escapeHtml(result.headSize)}. Compared at ${escapeHtml(result.width)}px viewport width.

+ ${renderOverflowDetails(result)} +
+
Base
+
Head
+
Diff
+
+
+ `).join("\n"); + + const html = ` + + + + Visual regression report + + + +

Visual regression report

+

Changed viewports: ${changed.length}/${results.length}.

+ ${renderHeadingDiff(outlineDiff)} + ${htmlRows} + + +`; + + await writeFile(path.join(outDir, "summary.md"), summaryLines.join("\n")); + await writeFile(path.join(outDir, "report.html"), html); + await writeFile(path.join(outDir, "results.json"), JSON.stringify(results, null, 2)); +} + +function headingKey(heading) { + return `${heading.level}:${heading.text}`; +} + +function compareHeadings(baseHeadings, headHeadings) { + const baseKeys = new Set(baseHeadings.map(headingKey)); + const headKeys = new Set(headHeadings.map(headingKey)); + + return { + added: headHeadings.filter((heading) => !baseKeys.has(headingKey(heading))), + removed: baseHeadings.filter((heading) => !headKeys.has(headingKey(heading))), + }; +} + +function renderHeadingList(headings) { + if (headings.length === 0) { + return "

None.

"; + } + + return `
    ${headings.slice(0, 30).map((heading) => ( + `
  • ${escapeHtml(heading.level)} ${escapeHtml(heading.text)}
  • ` + )).join("\n")}
`; +} + +function renderHeadingDiff(outlineDiff) { + if (outlineDiff.added.length === 0 && outlineDiff.removed.length === 0) { + return ""; + } + + return `
+

Heading changes

+
+
+

Added in head (${outlineDiff.added.length})

+ ${renderHeadingList(outlineDiff.added)} +
+
+

Removed from base (${outlineDiff.removed.length})

+ ${renderHeadingList(outlineDiff.removed)} +
+
+
`; +} + +function renderOverflowDetails(result) { + const rows = [ + ...result.baseMetrics.overflowElements.map((element) => ({ side: "Base", ...element })), + ...result.headMetrics.overflowElements.map((element) => ({ side: "Head", ...element })), + ]; + + if (!result.baseMetrics.hasHorizontalOverflow && !result.headMetrics.hasHorizontalOverflow) { + return ""; + } + + const overflowSummary = [ + result.baseMetrics.hasHorizontalOverflow + ? `Base scroll width: ${result.baseMetrics.scrollWidth}px` + : "Base has no horizontal overflow", + result.headMetrics.hasHorizontalOverflow + ? `Head scroll width: ${result.headMetrics.scrollWidth}px` + : "Head has no horizontal overflow", + ].join(". "); + + const table = rows.length === 0 + ? "" + : ` + + + ${rows.map((row) => ` + + + + + + + `).join("\n")} + +
SideElementPositionText
${escapeHtml(row.side)}${escapeHtml(row.selector)}${escapeHtml(row.left)}-${escapeHtml(row.right)}px (${escapeHtml(row.width)}px)${escapeHtml(row.text)}
`; + + return `
Horizontal overflow detected. ${escapeHtml(overflowSummary)}${table}
`; +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const baseDir = path.resolve(required(args, "base-dir")); + const headDir = path.resolve(required(args, "head-dir")); + const outDir = path.resolve(required(args, "out-dir")); + const pagePath = normalizeRelativeUrl(required(args, "path")); + const threshold = Number(required(args, "threshold")); + const failOnDifference = required(args, "fail-on-difference") === "true"; + const ignoredSelectors = parseSelectors(optional(args, "ignore-selectors")); + + if (!Number.isFinite(threshold) || threshold < 0 || threshold > 1) { + throw new Error("--threshold must be a number between 0 and 1"); + } + + if (!existsSync(path.join(baseDir, pagePath))) { + throw new Error(`Base page not found: ${path.join(baseDir, pagePath)}`); + } + + if (!existsSync(path.join(headDir, pagePath))) { + throw new Error(`Head page not found: ${path.join(headDir, pagePath)}`); + } + + await mkdir(outDir, { recursive: true }); + + const baseServer = await startStaticServer(baseDir); + const headServer = await startStaticServer(headDir); + const browser = await chromium.launch(); + const results = []; + + try { + for (const viewport of VIEWPORTS) { + const page = await browser.newPage({ + deviceScaleFactor: 1, + viewport: { width: viewport.width, height: viewport.height }, + }); + + const baseImage = `base-${viewport.name}.png`; + const headImage = `head-${viewport.name}.png`; + const diffImage = `diff-${viewport.name}.png`; + + const baseMetrics = await capturePage( + page, + `${baseServer.url}/${pagePath}`, + path.join(outDir, baseImage), + ignoredSelectors, + viewport, + ); + + const headMetrics = await capturePage( + page, + `${headServer.url}/${pagePath}`, + path.join(outDir, headImage), + ignoredSelectors, + viewport, + ); + + await page.close(); + + const comparison = await compareImages( + path.join(outDir, baseImage), + path.join(outDir, headImage), + path.join(outDir, diffImage), + ); + + results.push({ + ...viewport, + ...comparison, + baseImage, + headImage, + diffImage, + baseMetrics, + headMetrics, + changed: comparison.ratio > threshold, + }); + } + } finally { + await browser.close(); + await baseServer.close(); + await headServer.close(); + } + + await writeReports(outDir, results, threshold, failOnDifference); + + const changed = results.filter((result) => result.changed); + for (const result of results) { + console.log(`${result.name}: ${(result.ratio * 100).toFixed(3)}%`); + } + + if (failOnDifference && changed.length > 0) { + throw new Error(`${changed.length} viewport(s) exceeded the threshold`); + } +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); diff --git a/snapshot.html b/snapshot.html new file mode 100644 index 0000000..735754f --- /dev/null +++ b/snapshot.html @@ -0,0 +1,1833 @@ + + + + + + + + + + + + + + + +Geonovum template voor ReSpec + + + + + + + + + + + + + + + + + + + + + + + +
+

Geonovum template voor ReSpec

+ +

+ Geonovum Handreiking
+ Document + +

+
+
Deze versie:
+ https://docs.geostandaarden.nl/3dbv/basis-hr-nl-respec-template-20260209 +
+
Laatst gepubliceerde versie:
+ https://docs.geostandaarden.nl/3dbv/nl-respec-template/ +
+
Laatste werkversie:
https://geonovum.github.io/NL-ReSpec-template/
+ + + + + +
Redacteur:
+
+ voornaam achternaam (Geonovum) +
+ +
Auteur:
+ voornaam achternaam (Geonovum) +
+
Doe mee:
+ GitHub Geonovum/NL-ReSpec-template +
+ Alle issues +
+ Dien een melding in +
+ Revisiehistorie +
+ Pull requests +
+
+ + + + +
+
+ +

Samenvatting

TODO: vul in abstract.md een abstract in.

+
+

Status van dit document

Dit is een document zonder officiële status.

+ + +

1. Niet-normatieve deel

Dit onderdeel is niet-normatief.

+

Bijvoorbeeld een introductie is niet normatief.

+
Noot: index

+Dit hoofdstuk is toegevoegd met class="informative" in config.js. +

1.1 Een subparagraaf

+

Hier staat een tabel. Als de juiste style gekozen is ziet deze er goed uit.

+ + + + + + + + + + + +
SleutelWaarde
keyDeze waarde bevat een lange tekst zodat te zien is of de kolombreedte dynamisch wordt bepaald
+
+

2. Meer inhoud

+

2.1 Definities

+

Definitie: Een definitie is een beschrijving van een woord. Een ander woord voor definitie is betekenis of beschrijving.

+

2.2 Afbeeldingen

+

Afbeeldingen krijgen een nummer en vermelding in de figurenlijst 5. Lijst met figuren.

+

+

+ Tekstueel alternatief voor toegankelijkheid +
Figuur 1 Onderschrift
+
+

+

2.3 Referenties

+

Referenties kunnen op drie plaatsen staan:

+ +

Referentie uit organisatie lijst [SemVer] of de locale lijst [MIM12]. Lijst staat in organisation-config.js. Alleen referenties die in de tekst voorkomen worden getoond.

+

We gebruiken een definitie om een woord te omschrijven.

+

2.4 Optioneel

+

De onderstaande secties (Conformiteit e.d.) zijn optioneel, zie index.html:

+
<body>
+  <section id="abstract" data-include-format="markdown" data-include="abstract.md"></section>
+  <section id="sotd"></section><!-- Wordt automatisch gevuld -->
+  <section data-include-format="markdown" class="informative" data-include="ch01.md"></section>
+  <section data-include-format="markdown" data-include="ch02.md"></section>
+  <!-- Hieronder optionele secties. Worden automatisch gevuld -->
+  <section id='conformance'></section>
+  <section id='tof'></section>
+  <section id="index"></section>
+</body>
+
+
+

3. Mermaid diagram

+
+
Figuur 2 Mermaid voorbeeld
+
+ + + + + + + + + +

4. Conformiteit

Naast onderdelen die als niet-normatief gemarkeerd zijn, zijn ook alle diagrammen, voorbeelden, en noten in dit document niet-normatief. Verder is alles in dit document normatief.

+

5. Lijst met figuren

+

A. Index

+

A.1 Termen gedefinieerd door deze specificatie

+ +
+

A.2 Termen gedefinieerd door verwijzing

+
    + +
+
+ + + +

B. Referenties

+

B.1 Normatieve referenties

+
[MIM12]
+ MIM - Metamodel Informatie Modellering (Versie 1.2). Geonovum. 2024-06-13. Definitief. URL: https://docs.geostandaarden.nl/mim/def-st-mim-20240613/ +
[SemVer]
+ Semantic Versioning 2.0.0. T. Preston-Werner. June 2013. URL: https://semver.org +
+
Geonovum Handreiking - Document
\ No newline at end of file diff --git a/tests/fixtures/mermaid/README.md b/tests/fixtures/mermaid/README.md new file mode 100644 index 0000000..42de623 --- /dev/null +++ b/tests/fixtures/mermaid/README.md @@ -0,0 +1,17 @@ +# Mermaid-regressiefixtures + +`sensordata.html` bevat de vier ongewijzigde inline SVG-elementen uit de +[gecommitte snapshot van testbed-sensordata-2026](https://github.com/Geonovum/testbed-sensordata-2026/blob/9cd55c0af07a4569c9cf0394aef7e86cc84f1fb0/snapshot.html). +De omhullende HTML is verkleind om de tests zonder netwerk of publicatie-assets +te draaien. Herkomst: Geonovum, ReSpec 37.2.0 / respec-mermaid 1.0.1. +De twee sequence-diagrammen en twee flowcharts bevatten samen 13 groepen dubbele +ID's (26 definities), drie label-offset-attributen en HTML in foreignObject. + +`data-image.html` bevat de ingebedde SVG-afbeeldingen uit de template-snapshot +op de oorspronkelijke PR-head e2fbf2410d2740913d3c0071e564336aafbf0ee9 +(ReSpec 37.2.0 / respec-mermaid 1.3.0). Deze variant moet bytegelijk blijven. + +De normalizer-test en de browser/PDF-test gebruiken dezelfde oorspronkelijke +fixtures. De browsertest normaliseert zelf een kopie, vergelijkt scherm- en +printweergave en draait het ongewijzigde `.github/workflows/pdf.js` voor beide +versies. PNG's, PDF's en het rapport zijn CI-artifacts, geen bronbestanden. diff --git a/tests/fixtures/mermaid/data-image.html b/tests/fixtures/mermaid/data-image.html new file mode 100644 index 0000000..0d8e796 --- /dev/null +++ b/tests/fixtures/mermaid/data-image.html @@ -0,0 +1 @@ +Mermaid 1.3.0 diff --git a/tests/fixtures/mermaid/sensordata.html b/tests/fixtures/mermaid/sensordata.html new file mode 100644 index 0000000..f580ab1 --- /dev/null +++ b/tests/fixtures/mermaid/sensordata.html @@ -0,0 +1,15 @@ + +Mermaid sensordata regression +
Sensor ManagerFROST-ServerLoRaWANConnectorList DeviceModelsDataPOST ThingLinks to DeviceModel@idPOST OnboardDevice TaskPOST Task(OnboardDevice, ThingID of Device)@idOnboard DeviceUpdate Task: DoneSensor ManagerFROST-ServerLoRaWANConnector
+
Sensor ManagerFROST-ServerLoRaWANConnectorLoRaWANPlatformLoRaWANApplication ServerLoRaWANNetwork ServerLoRaWANJoin ServerPOST TaskOnboardDevice,(ThingID of Device)MQTT Push:New Task (new Sensor with ThingID)GET Thing(sensor)expand=DeviceModel, ConfigurationDataLink Thing(sensor)to Thing(Connector)Create Datastreamsloop[For each Sensor linked toDeviceModel]POST Register Sensor(ApplicationID, DeviceID, DevEUI,JoinEUI, JoinServerAdr,NetworkServerAdr,ApplicationServerAdr)ResponsePOST Register Sensor(DeviceID,DevEUI,JoinEUI)ResponsePOST Register Sensor(DeviceID, DevEUI, JoinEUI, FrequencyID, PhyVersion, LoRaWANVersion, AppKey)ResponsePOST Register Sensor(DeviceID, DevEUI, JoinEUI, AppKey, NetworkServerAdr, ApplicationServerAdr)ResponseGet DeviceModel(x)/decoderDataSet Up DecoderPATCH Sensor(x)/ConfigurationActiveSensor ManagerFROST-ServerLoRaWANConnectorLoRaWANPlatformLoRaWANApplication ServerLoRaWANNetwork ServerLoRaWANJoin Server
+
Targets
Connector
Sources
UrbanAdapt monitoring
FROST v1.1 (WBD)
FROST v2.0 (Fraunhofer demo)
PHP FROST v1.1 (CollaborAll)
Dedup + datastream resolution
Async worker queue
Kafka (TGV Office Lab)
Ohnics API (air quality)
Levellog / CARS (groundwater)
Bridge payloads (file / HTTP)
+
STA servers
Translation layer
Sources
GET
poll
poll
push: POST /ingest/collaborall
write
write
WBD FROST-Server
HTTP and MQTT
Collaborall STA
(destination)
Ingest core
cursor, deduplication, write-log
Validator
clock skew, range, provenance
FROST writer
upsert by name, idempotency probe, dual-write
SULO vendor API
Dummy generator
Collaborall STA
(source server)
collaborall-reader
(separate binary)
+ diff --git a/tests/test_central_workflows.py b/tests/test_central_workflows.py new file mode 100644 index 0000000..0747388 --- /dev/null +++ b/tests/test_central_workflows.py @@ -0,0 +1,88 @@ +import re +import unittest +from pathlib import Path + +import yaml + + +REPOSITORY_ROOT = Path(__file__).resolve().parents[1] +GITHUB_DIR = REPOSITORY_ROOT / ".github" +# Bron van de aanroepende workflows die naar documentrepos worden uitgerold. +CALLER_GITHUB_DIR = REPOSITORY_ROOT / "document-repo" / ".github" +UPDATE_SCRIPT = REPOSITORY_ROOT / "scripts" / "update-document-repos.mjs" +ROLLOUT_WORKFLOW = GITHUB_DIR / "workflows" / "update-workflows.yml" +CENTRAL_PREFIX = "Geonovum/NL-ReSpec-workflows/.github/workflows/" + + +def string_list(source: str, name: str) -> list[str]: + block = source.split(f"const {name} = [")[1].split("];")[0] + return re.findall(r'"([^"]+)"', block) + + +def workflow(name: str, github_dir: Path = GITHUB_DIR) -> dict: + # PyYAML leest de sleutel "on" als True. + return yaml.safe_load((github_dir / "workflows" / name).read_text(encoding="utf-8")) + + +def caller(name: str) -> dict: + return workflow(name, CALLER_GITHUB_DIR) + + +class CentralWorkflowTest(unittest.TestCase): + def setUp(self) -> None: + source = UPDATE_SCRIPT.read_text(encoding="utf-8") + self.managed = string_list(source, "MANAGED_FILES") + self.removed = string_list(source, "REMOVED_MANAGED_FILES") + + def test_document_repositories_only_receive_caller_workflows(self) -> None: + self.assertEqual(sorted(self.managed), ["workflows/main.yml", "workflows/visual-regression.yml"]) + + def test_old_copies_are_removed_from_document_repositories(self) -> None: + for name in ( + "dependabot.yml", + "workflows/build.yml", + "workflows/publish.yml", + "workflows/pdf.js", + "workflows/normalize-mermaid-svg.mjs", + "mermaid-svg/package.json", + "mermaid-svg/package-lock.json", + ): + self.assertIn(name, self.removed) + self.assertFalse(set(self.managed) & set(self.removed)) + + def test_callers_use_central_reusable_workflows_on_the_major_tag(self) -> None: + for name in self.managed: + jobs = caller(Path(name).name)["jobs"] + for job_name, job in jobs.items(): + uses = job.get("uses", "") + with self.subTest(file=name, job=job_name): + self.assertTrue(uses.startswith(CENTRAL_PREFIX), uses) + self.assertTrue(uses.endswith("@v1"), uses) + target = workflow(uses[len(CENTRAL_PREFIX):].split("@")[0]) + self.assertIn("workflow_call", target[True]) + + def test_caller_grants_the_permissions_the_reusable_jobs_need(self) -> None: + jobs = caller("main.yml")["jobs"] + self.assertEqual(jobs["build"]["permissions"], {"contents": "write"}) + self.assertEqual(jobs["publish"]["permissions"], {"contents": "write", "pull-requests": "write"}) + + def test_rollout_copies_callers_from_document_repo_directory(self) -> None: + for name in self.managed: + self.assertTrue((CALLER_GITHUB_DIR / name).is_file(), name) + # Aanroepende workflows draaien niet in deze repository zelf. + self.assertFalse((GITHUB_DIR / name).exists(), name) + steps = workflow("update-workflows.yml")["jobs"]["update"]["steps"] + env = next(step["env"] for step in steps if "TEMPLATE_GITHUB_DIR" in step.get("env", {})) + self.assertEqual(env["TEMPLATE_GITHUB_DIR"], "${{ github.workspace }}/document-repo/.github") + + def test_template_tests_its_own_build_workflow(self) -> None: + jobs = workflow("template-regression.yml")["jobs"] + self.assertEqual(jobs["build"]["uses"], "./.github/workflows/build.yml") + + def test_version_tag_moves_major_tag(self) -> None: + release = workflow("release-tag.yml") + self.assertEqual(release[True]["push"]["tags"], ["v[0-9]+.[0-9]+.[0-9]+"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_mermaid_svg_normalization.py b/tests/test_mermaid_svg_normalization.py new file mode 100644 index 0000000..6d81fc6 --- /dev/null +++ b/tests/test_mermaid_svg_normalization.py @@ -0,0 +1,369 @@ +import os +import re +import shutil +import subprocess +import tempfile +import unittest +from collections import Counter +from pathlib import Path + +import yaml + + +REPOSITORY_ROOT = Path(__file__).resolve().parents[1] +BUILD_WORKFLOW = REPOSITORY_ROOT / ".github" / "workflows" / "build.yml" +NORMALIZER = REPOSITORY_ROOT / ".github" / "workflows" / "normalize-mermaid-svg.mjs" +UPDATE_SCRIPT = REPOSITORY_ROOT / "scripts" / "update-document-repos.mjs" + +ID_ATTRIBUTE = re.compile(r'\sid="([^"]*)"') + +# Twee diagrammen zoals mermaid ze genereert: identieke -id's, plus een +# intern layout-attribuut dat niet in SVG bestaat. +FIXTURE = """ +Test +
Een
+
Twee
+ +""" + + +def build_steps() -> list[dict]: + workflow = yaml.safe_load(BUILD_WORKFLOW.read_text(encoding="utf-8")) + return workflow["jobs"]["build"]["steps"] + + +def step_names() -> list[str]: + return [step.get("name") for step in build_steps()] + + +def normalize(html: str) -> str: + with tempfile.TemporaryDirectory() as directory: + target = Path(directory) / "snapshot.html" + target.write_text(html, encoding="utf-8") + subprocess.run( + ["node", str(NORMALIZER), str(target)], + check=True, + capture_output=True, + ) + return target.read_text(encoding="utf-8") + + +class MermaidSvgNormalizationTest(unittest.TestCase): + def test_build_normalizes_before_validation(self) -> None: + names = step_names() + + self.assertIn( + "Normaliseer mermaid-diagrammen in snapshot", + names, + "De build moet de mermaid-SVG normaliseren voordat de HTML wordt gevalideerd.", + ) + self.assertLess( + names.index("Normaliseer mermaid-diagrammen in snapshot"), + names.index("Prepare publication for validation"), + "Normaliseren moet gebeuren voordat het publicatiepakket wordt samengesteld.", + ) + self.assertGreater( + names.index("Normaliseer mermaid-diagrammen in snapshot"), + names.index("Generate HTML snapshot"), + "Normaliseren kan pas nadat ReSpec de snapshot heeft gegenereerd.", + ) + + def test_normalizer_comes_from_central_tooling_checkout(self) -> None: + names = step_names() + checkout = next(step for step in build_steps() if step.get("name") == "Checkout workflow tooling") + + self.assertLess( + names.index("Checkout workflow tooling"), + names.index("Normaliseer mermaid-diagrammen in snapshot"), + "De centrale hulpbestanden moeten zijn uitgecheckt voordat er genormaliseerd wordt.", + ) + self.assertEqual(checkout["with"]["repository"], "${{ steps.tooling.outputs.repository }}") + self.assertEqual(checkout["with"]["ref"], "${{ steps.tooling.outputs.ref }}") + self.assertIn(".github/mermaid-svg", checkout["with"]["sparse-checkout"]) + + def test_duplicate_mermaid_ids_become_unique(self) -> None: + result = normalize(FIXTURE) + + duplicates = [ + identifier + for identifier, count in Counter(ID_ATTRIBUTE.findall(result)).items() + if count > 1 + ] + self.assertEqual([], duplicates, "vnu meldt dubbele id's als fout.") + + def test_references_follow_the_renamed_ids(self) -> None: + result = normalize(FIXTURE) + + self.assertIn('', result) + self.assertIn('', result) + self.assertIn("url(#diagram-1-arrowhead)", result) + self.assertIn("url(#diagram-2-arrowhead)", result) + self.assertIn("#diagram-1 #diagram-1-arrowhead path", result) + self.assertNotIn("url(#arrowhead)", result) + + def test_no_reference_is_left_dangling(self) -> None: + result = normalize(FIXTURE) + + identifiers = set(ID_ATTRIBUTE.findall(result)) + references = set(re.findall(r"url\(#([^)]+)\)", result)) + references |= set(re.findall(r'(?:xlink:)?href="#([^"]+)"', result)) + + self.assertEqual(set(), references - identifiers) + + def test_unique_ids_and_respec_anchors_are_left_alone(self) -> None: + result = normalize(FIXTURE) + + # Deze id's zijn al uniek en mogen dus niet worden herschreven; anders + # breken permalinks naar secties en figuren. + self.assertIn('id="diagram-1"', result) + self.assertIn('id="chart-title-diagram-1"', result) + self.assertIn( + 'aria-labelledby="chart-title-diagram-1 chart-desc-diagram-1"', result + ) + + def test_invalid_mermaid_layout_attributes_are_removed(self) -> None: + result = normalize(FIXTURE) + + self.assertNotIn("label-offset-y", result) + + def test_normalization_is_idempotent(self) -> None: + once = normalize(FIXTURE) + self.assertEqual(once, normalize(once)) + + +class MermaidContentPreservationTest(unittest.TestCase): + def with_content(self, content): + return FIXTURE.replace('
', '' + content) + + def test_visible_labels_and_attribute_text_are_preserved(self): + content = 'Verwijzing #arrowhead' + result = normalize(self.with_content(content)) + self.assertEqual(2, result.count(content)) + self.assertIn('id="diagram-1-arrowhead"', result) + + def test_external_urls_are_preserved_and_local_hrefs_follow_ids(self): + content = ('Handleiding' + '' + '') + result = normalize(self.with_content(content)) + self.assertEqual(4, result.count('https://example.org/guide#arrowhead')) + self.assertIn('href="#diagram-1-arrowhead"', result) + self.assertIn('xlink:href="#diagram-2-arrowhead"', result) + + def test_css_pseudoclasses_classes_and_strings(self): + result = normalize(self.with_content('')) + self.assertIn('#diagram-1-arrowhead:hover', result) + self.assertIn('#diagram-2-arrowhead.active', result) + self.assertIn(':is(#diagram-1-arrowhead)', result) + self.assertIn('content:"#arrowhead"', result) + self.assertNotIn('url("#arrowhead")', result) + + def test_css_attribute_selectors_follow_local_id_attributes(self): + result = normalize(self.with_content('')) + self.assertIn('[id="diagram-1-arrowhead"]', result) + self.assertIn('[href="#diagram-2-arrowhead"]', result) + self.assertIn('[href="https://example.org/#arrowhead"]', result) + + def test_css_custom_properties_contain_real_local_urls(self): + result = normalize(self.with_content('')) + self.assertNotIn('url(#arrowhead)', result) + self.assertIn('--end:url(#diagram-1-arrowhead)', result) + + def test_mermaid_inside_a_non_mermaid_svg_is_processed(self): + inner = self.with_content('') + source = ('' + inner + + '') + result = normalize(source) + self.assertIn('', result) + self.assertIn('', result) + self.assertIn('id="diagram-1-arrowhead"', result) + self.assertNotIn('label-offset-y', result) + + def test_color_values_are_not_fragment_references(self): + result = normalize(self.with_content('')) + self.assertEqual(2, result.count('fill="#fff"')) + self.assertEqual(2, result.count('stroke="#fff"')) + self.assertEqual(2, result.count('fill:#fff')) + self.assertIn('url(#diagram-1-fff)', result) + + def test_non_mermaid_svgs_are_byte_identical(self): + ordinary = ('' + '' + '') + self.assertEqual(ordinary, normalize(ordinary)) + self.assertIn(ordinary, normalize(self.with_content('') + ordinary)) + + def test_script_comments_and_data_images_are_not_svg_elements(self): + inert = ('' + '' + 'diagram') + self.assertIn(inert, normalize(FIXTURE + inert)) + + def test_aria_tokens_quoted_urls_and_nested_svg(self): + content = ('NestedInfo' + '' + '') + result = normalize(self.with_content(content)) + self.assertIn('aria-labelledby="diagram-1-nested-title diagram-1-nested-desc"', result) + self.assertIn('aria-describedby="diagram-2-nested-desc"', result) + self.assertNotIn('"#arrowhead"', result) + self.assertEqual(result, normalize(result)) + + def test_css_escaped_ids_and_html_entities(self): + content = (r'') + result = normalize(self.with_content(content)) + self.assertIn(r'#diagram-1-node\.part\:1:hover', result) + self.assertIn('href="#diagram-2-node.part:1"', result) + + def test_single_quoted_attributes_and_unique_new_ids(self): + source = self.with_content('') + source = source.replace('"', "'") + '
' + result = normalize(source) + self.assertIn('id="diagram-1-taken-2"', result) + self.assertIn('href="#diagram-1-taken-2"', result) + self.assertIn('
', result) + self.assertNotIn('label-offset-y', result) + + def test_ambiguous_duplicates_within_one_diagram_fail_without_writing(self): + source = self.with_content('') + with tempfile.TemporaryDirectory() as directory: + target = Path(directory) / 'snapshot.html' + target.write_text(source) + result = subprocess.run(['node', str(NORMALIZER), str(target)], + capture_output=True, text=True) + self.assertNotEqual(0, result.returncode) + self.assertIn('Dubbele id binnen Mermaid-diagram', result.stderr) + self.assertEqual(source, target.read_text()) + + def test_mermaid_container_without_generated_diagram_id(self): + source = ('
' + FIXTURE.split('
')[1].split('
')[0] + .replace('diagram-1', 'custom-diagram') + '

Anchor

') + result = normalize(source) + self.assertIn('id="custom-diagram-arrowhead"', result) + self.assertIn('

Anchor

', result) + + +class MermaidProductionFixtureTest(unittest.TestCase): + def test_sensordata_sequence_and_flowcharts(self): + source = (REPOSITORY_ROOT / 'tests/fixtures/mermaid/sensordata.html').read_text() + self.assertEqual(13, sum(count > 1 for count in Counter(ID_ATTRIBUTE.findall(source)).values())) + result = normalize(source) + self.assertEqual([], [identifier for identifier, count in + Counter(ID_ATTRIBUTE.findall(result)).items() if count > 1]) + self.assertNotIn('label-offset-', result) + refs = set(re.findall(r'url\(#([^)]+)\)', result)) + refs |= set(re.findall(r'(?:xlink:)?href="#([^"]+)"', result)) + self.assertEqual(set(), refs - set(ID_ATTRIBUTE.findall(result))) + self.assertEqual(result, normalize(result)) + + def test_respec_mermaid_1_3_data_images_are_byte_identical(self): + source = (REPOSITORY_ROOT / 'tests/fixtures/mermaid/data-image.html').read_text() + self.assertIn('data:image/svg+xml;base64,', source) + self.assertEqual(source, normalize(source)) + + def test_sparse_tooling_checkout_forms_a_runnable_normalizer(self): + # Een documentrepository zonder eigen .github-hulpbestanden: alleen de + # sparse checkout van het template mag nodig zijn om te normaliseren. + checkout = next(step for step in build_steps() if step.get('name') == 'Checkout workflow tooling') + sparse_paths = checkout['with']['sparse-checkout'].split() + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) / 'document' + tooling = root / '.nl-respec-tooling' + root.mkdir() + for name in sparse_paths: + shutil.copytree(REPOSITORY_ROOT / name, tooling / name, + ignore=shutil.ignore_patterns('node_modules')) + target = root / 'snapshot.html' + target.write_text(FIXTURE) + step = next(step for step in build_steps() if + step.get('name') == 'Normaliseer mermaid-diagrammen in snapshot') + subprocess.run(['bash', '-c', step['run']], cwd=root, + env={**os.environ, 'npm_config_offline': 'true', 'TOOLING_DIR': str(tooling)}, + check=True, capture_output=True) + self.assertEqual(normalize(FIXTURE), target.read_text()) + + +class MermaidVisualWorkflowTest(unittest.TestCase): + def test_visual_head_is_normalized_and_committed_base_is_preserved(self): + workflow = yaml.safe_load((REPOSITORY_ROOT / '.github/workflows/visual-regression-reusable.yml').read_text()) + step = next(step for step in workflow['jobs']['visual-regression']['steps'] + if step.get('name') == 'Prepare ReSpec snapshots') + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + head = root / 'comparison/head' + base = root / 'comparison/base' + head.mkdir(parents=True) + base.mkdir(parents=True) + # De normalizer komt uit de tooling-checkout, niet uit de documentrepository. + template = root / 'comparison/template' + shutil.copytree(REPOSITORY_ROOT / '.github/mermaid-svg', template / '.github/mermaid-svg', + ignore=shutil.ignore_patterns('node_modules')) + (template / '.github/workflows').mkdir(parents=True) + shutil.copyfile(NORMALIZER, template / '.github/workflows' / NORMALIZER.name) + (head / 'index.html').write_text(FIXTURE) + (base / 'snapshot.html').write_text(FIXTURE) + # Alleen de externe ReSpec-renderer vervangen: de echte shellstap, + # dependency-installatie en normalizer worden uitgevoerd. + binary = root / 'bin' + binary.mkdir() + renderer = binary / 'npx' + renderer.write_text('#!/bin/bash\ncp "$SOURCE" "$SNAPSHOT"\n') + renderer.chmod(0o755) + subprocess.run(['bash', '-c', step['run']], cwd=root, check=True, capture_output=True, + env={**os.environ, 'GITHUB_WORKSPACE': str(root), 'WORK_DIR': 'comparison', + 'SOURCE': 'index.html', 'SNAPSHOT': 'snapshot.html', + 'PATH': str(binary) + os.pathsep + os.environ['PATH'], + 'npm_config_offline': 'true'}) + self.assertEqual(FIXTURE, (base / 'snapshot.html').read_text()) + self.assertEqual(normalize(FIXTURE), (head / 'snapshot.html').read_text()) + + + def test_visual_regression_is_skipped_when_base_has_no_document(self): + workflow = yaml.safe_load((REPOSITORY_ROOT / '.github/workflows/visual-regression-reusable.yml').read_text()) + steps = workflow['jobs']['visual-regression']['steps'] + step = next(step for step in steps if step.get('name') == 'Prepare ReSpec snapshots') + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + template = root / 'comparison/template' + shutil.copytree(REPOSITORY_ROOT / '.github/mermaid-svg', template / '.github/mermaid-svg', + ignore=shutil.ignore_patterns('node_modules')) + (root / 'comparison/base').mkdir(parents=True) + (root / 'comparison/head').mkdir(parents=True) + output = root / 'output' + summary = root / 'summary' + subprocess.run(['bash', '-c', step['run']], cwd=root, check=True, capture_output=True, + env={**os.environ, 'GITHUB_WORKSPACE': str(root), 'WORK_DIR': 'comparison', + 'SOURCE': 'index.html', 'SNAPSHOT': 'snapshot.html', + 'GITHUB_OUTPUT': str(output), 'GITHUB_STEP_SUMMARY': str(summary), + 'npm_config_offline': 'true'}) + self.assertIn('skip=true', output.read_text()) + for name in ('Install comparison tooling', 'Compare screenshots', 'Upload visual regression report'): + later = next(step for step in steps if step.get('name') == name) + self.assertIn("steps.prepare.outputs.skip != 'true'", later['if']) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_publication_preflight.py b/tests/test_publication_preflight.py new file mode 100644 index 0000000..f06b2d9 --- /dev/null +++ b/tests/test_publication_preflight.py @@ -0,0 +1,230 @@ +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +import yaml + + +REPOSITORY_ROOT = Path(__file__).resolve().parents[1] +BUILD_WORKFLOW = REPOSITORY_ROOT / ".github" / "workflows" / "build.yml" +PUBLISH_WORKFLOW = REPOSITORY_ROOT / ".github" / "workflows" / "publish.yml" +RESPEC_CONFIG = REPOSITORY_ROOT / "js" / "config.js" + + +def build_steps() -> list[dict]: + workflow = yaml.safe_load(BUILD_WORKFLOW.read_text(encoding="utf-8")) + return workflow["jobs"]["build"]["steps"] + + +def find_step(name: str) -> dict | None: + return next((step for step in build_steps() if step.get("name") == name), None) + + +def publish_steps() -> list[dict]: + workflow = yaml.safe_load(PUBLISH_WORKFLOW.read_text(encoding="utf-8")) + return workflow["jobs"]["release"]["steps"] + + +def find_publish_step(name: str) -> dict | None: + return next((step for step in publish_steps() if step.get("name") == name), None) + + +class PublicationPreflightTest(unittest.TestCase): + def test_local_post_processors_preserve_organisation_processors(self) -> None: + config = RESPEC_CONFIG.read_text(encoding="utf-8") + + self.assertIn( + "...(organisationConfig.postProcess ?? [])", + config, + "Lokale post-processors mogen de Mermaid-processor uit de organisatieconfig niet vervangen.", + ) + + def test_snapshot_uses_pinned_respec_on_supported_node(self) -> None: + setup = find_step("Set up Node.js") + generate = find_step("Generate HTML snapshot") + + self.assertIsNotNone(setup, "De build moet expliciet een ondersteunde Node-versie installeren.") + self.assertTrue(setup["uses"].startswith("actions/setup-node@")) + self.assertEqual(str(setup["with"]["node-version"]), "24") + self.assertIsNotNone(generate) + self.assertIn("npx --yes respec@37.3.2", generate["run"]) + + def test_validation_tree_keeps_assets_but_excludes_respec_source_fragments(self) -> None: + step = find_step("Prepare publication for validation") + self.assertIsNotNone(step, "De build moet het toekomstige publicatiepakket voorbereiden.") + + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) + (source / "snapshot.html").write_text("snapshot", encoding="utf-8") + for asset_directory in ("data", "media", "js", "css"): + target = source / asset_directory + target.mkdir() + (target / "asset.txt").write_text(asset_directory, encoding="utf-8") + fragments = target / "nested" + fragments.mkdir() + (fragments / "model.respec.html").write_text("fragment", encoding="utf-8") + (fragments / "model.respec.catalog.xhtml").write_text( + "catalog", encoding="utf-8" + ) + + stale = source / "publication-validation" + stale.mkdir(parents=True) + (stale / "stale.html").write_text("stale", encoding="utf-8") + + environment = os.environ.copy() + environment["GITHUB_WORKSPACE"] = str(source) + subprocess.run( + ["bash", "-euo", "pipefail", "-c", step["run"]], + cwd=source, + env=environment, + check=True, + capture_output=True, + text=True, + ) + + publication = source / "publication-validation" + self.assertEqual((publication / "index.html").read_text(encoding="utf-8"), "snapshot") + self.assertFalse((publication / "snapshot.html").exists()) + self.assertFalse((publication / "stale.html").exists()) + self.assertFalse((source / ".checks").exists()) + for asset_directory in ("data", "media", "js", "css"): + self.assertEqual( + (publication / asset_directory / "asset.txt").read_text(encoding="utf-8"), + asset_directory, + ) + self.assertFalse( + (publication / asset_directory / "nested" / "model.respec.html").exists() + ) + self.assertFalse( + ( + publication + / asset_directory + / "nested" + / "model.respec.catalog.xhtml" + ).exists() + ) + + published_html = sorted( + path.relative_to(publication).as_posix() + for path in publication.rglob("*") + if path.is_file() and path.suffix.lower() in {".html", ".xhtml"} + ) + self.assertEqual(published_html, ["index.html"]) + + def test_publish_content_keeps_assets_but_excludes_respec_source_fragments(self) -> None: + step = find_publish_step("Prepare content") + self.assertIsNotNone(step, "De publicatie moet het definitieve contentpakket voorbereiden.") + + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) + (source / "snapshot.html").write_text("snapshot", encoding="utf-8") + for asset_directory in ("data", "media", "js", "css"): + target = source / asset_directory + target.mkdir() + (target / "asset.txt").write_text(asset_directory, encoding="utf-8") + fragments = target / "nested" + fragments.mkdir() + (fragments / "model.respec.html").write_text("fragment", encoding="utf-8") + (fragments / "model.respec.catalog.xhtml").write_text( + "catalog", encoding="utf-8" + ) + + subprocess.run( + ["bash", "-euo", "pipefail", "-c", step["run"]], + cwd=source, + check=True, + capture_output=True, + text=True, + ) + + content = source / "content" + self.assertEqual((content / "index.html").read_text(encoding="utf-8"), "snapshot") + for asset_directory in ("data", "media", "js", "css"): + self.assertEqual( + (content / asset_directory / "asset.txt").read_text(encoding="utf-8"), + asset_directory, + ) + self.assertFalse( + (content / asset_directory / "nested" / "model.respec.html").exists() + ) + self.assertFalse( + ( + content / asset_directory / "nested" / "model.respec.catalog.xhtml" + ).exists() + ) + + def test_html_validation_is_blocking_for_the_publication_tree(self) -> None: + step = find_step("Validate publication HTML") + self.assertIsNotNone(step, "De build moet het publicatiepakket als HTML valideren.") + + self.assertNotIn("continue-on-error", step) + self.assertNotIn("if", step) + self.assertEqual( + step["with"]["directory"], + "publication-validation", + ) + self.assertIs(step["with"]["check_html"], True) + self.assertIs(step["with"]["check_css"], False) + self.assertIs(step["with"]["disable_external"], True) + self.assertIs(step["with"]["ignore_empty_alt"], True) + + def test_lychee_checks_only_generated_index_and_fails_on_errors(self) -> None: + step = find_step("Validate publication links") + self.assertIsNotNone(step, "De build moet publicatielinks met Lychee valideren.") + + self.assertNotIn("continue-on-error", step) + self.assertEqual(step.get("if"), "${{ !cancelled() }}") + self.assertTrue(step["uses"].startswith("lycheeverse/lychee-action@")) + self.assertIs(step["with"]["fail"], True) + self.assertEqual( + step["with"]["workingDirectory"], + "${{ github.workspace }}/publication-validation", + ) + self.assertIn("--offline", step["with"]["args"]) + self.assertIn("--root-dir", step["with"]["args"]) + self.assertIn("./index.html", step["with"]["args"]) + self.assertNotIn("./**/*.html", step["with"]["args"]) + + def test_validation_reports_are_artifacts_and_not_committed(self) -> None: + commit_step = find_step("Commit all results") + artifact_step = find_step("Upload validation reports") + + self.assertIsNotNone(commit_step) + self.assertNotIn(".checks", commit_step["run"]) + self.assertNotIn("CHECK_DIR", commit_step["run"]) + self.assertIsNotNone(artifact_step) + self.assertEqual(artifact_step.get("if"), "${{ always() }}") + self.assertIn( + "${{ runner.temp }}/nl-respec-validation/wcag-report.json", + artifact_step["with"]["path"], + ) + self.assertIn( + "${{ runner.temp }}/nl-respec-validation/link-check.txt", + artifact_step["with"]["path"], + ) + + cleanup_step = find_step("Remove validation working directory") + self.assertIsNotNone(cleanup_step) + self.assertEqual(cleanup_step.get("if"), "${{ always() }}") + + def test_summary_always_reports_whether_the_commit_is_ready_for_publication(self) -> None: + html_step = find_step("Validate publication HTML") + link_step = find_step("Validate publication links") + summary_step = find_step("Summarize publication preflight") + + self.assertIsNotNone(html_step) + self.assertIsNotNone(link_step) + self.assertIsNotNone(summary_step, "De build moet de publicatiegereedheid samenvatten.") + self.assertEqual(html_step.get("id"), "publication-html") + self.assertEqual(link_step.get("id"), "publication-links") + self.assertEqual(summary_step.get("if"), "${{ always() }}") + self.assertIn("GITHUB_STEP_SUMMARY", summary_step["run"]) + self.assertIn("Publicatiegereed", summary_step["run"]) + self.assertIn("${{ job.status }}", summary_step["run"]) + self.assertIn('BUILD_STATUS" == "success', summary_step["run"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_release_writeback_policy.py b/tests/test_release_writeback_policy.py new file mode 100644 index 0000000..448740a --- /dev/null +++ b/tests/test_release_writeback_policy.py @@ -0,0 +1,36 @@ +import re +import unittest +from pathlib import Path + + +REPOSITORY_ROOT = Path(__file__).resolve().parents[1] +BUILD_WORKFLOW = REPOSITORY_ROOT / ".github" / "workflows" / "build.yml" + + +def step_block(workflow: str, name: str) -> str: + marker = f" - name: {name}\n" + start = workflow.index(marker) + next_step = workflow.find("\n - name: ", start + len(marker)) + return workflow[start:] if next_step == -1 else workflow[start:next_step] + + +def allowed_events(condition: str) -> set[str]: + return set(re.findall(r"github\.event_name\s*==\s*['\"]([^'\"]+)['\"]", condition)) + + +class ReleaseWritebackPolicyTest(unittest.TestCase): + def test_only_push_can_select_a_source_branch_for_writeback(self) -> None: + workflow = BUILD_WORKFLOW.read_text(encoding="utf-8") + commit_target = step_block(workflow, "Bepaal branch voor terugschrijven") + condition = re.search(r"^\s+if:\s*(.+)$", commit_target, re.MULTILINE) + + self.assertIsNotNone(condition, "De terugschrijfstap moet een eventvoorwaarde hebben.") + self.assertEqual( + allowed_events(condition.group(1)), + {"push"}, + "Alleen een push mag een bronbranch voor terugschrijven selecteren.", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_repository_migration.py b/tests/test_repository_migration.py new file mode 100644 index 0000000..f229875 --- /dev/null +++ b/tests/test_repository_migration.py @@ -0,0 +1,45 @@ +import json +import subprocess +import tempfile +import unittest +from pathlib import Path + + +REPOSITORY_ROOT = Path(__file__).resolve().parents[1] +MIGRATION_MODULE = REPOSITORY_ROOT / "scripts" / "lib" / "repository-migration.mjs" + + +class RepositoryMigrationTest(unittest.TestCase): + def test_removes_checks_directory_without_overwriting_local_ignore_rules(self) -> None: + with tempfile.TemporaryDirectory() as directory: + repository = Path(directory) + (repository / ".gitignore").write_text( + "node_modules/\n.checks/*\n!.checks/*.txt\n!.checks/*.json\nlocal-only/\n", + encoding="utf-8", + ) + checks = repository / ".checks" + checks.mkdir() + (checks / "link-check.txt").write_text("links", encoding="utf-8") + (checks / "wcag-report.json").write_text("{}", encoding="utf-8") + + javascript = ( + f'import {{ migrateChecksDirectory }} from {json.dumps(MIGRATION_MODULE.as_uri())};' + "console.log(JSON.stringify(migrateChecksDirectory(process.argv[1])));" + ) + result = subprocess.run( + ["node", "--input-type=module", "--eval", javascript, str(repository)], + check=True, + capture_output=True, + text=True, + ) + + self.assertEqual(json.loads(result.stdout), [".gitignore", ".checks"]) + self.assertFalse(checks.exists()) + self.assertEqual( + (repository / ".gitignore").read_text(encoding="utf-8"), + "node_modules/\nlocal-only/\n", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_template_leftovers.py b/tests/test_template_leftovers.py new file mode 100644 index 0000000..b9cc09d --- /dev/null +++ b/tests/test_template_leftovers.py @@ -0,0 +1,99 @@ +import json +import subprocess +import tempfile +import unittest +from pathlib import Path + +import yaml + + +REPOSITORY_ROOT = Path(__file__).resolve().parents[1] +LEFTOVERS_MODULE = REPOSITORY_ROOT / "scripts" / "lib" / "template-leftovers.mjs" +UPDATE_SCRIPT = REPOSITORY_ROOT / "scripts" / "update-document-repos.mjs" +ROLLOUT_WORKFLOW = REPOSITORY_ROOT / ".github" / "workflows" / "update-workflows.yml" + + +def git(cwd: Path, *args: str) -> None: + subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True) + + +def commit(repository: Path, files: dict[str, str], message: str) -> None: + for name, content in files.items(): + target = repository / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content, encoding="utf-8") + git(repository, "add", "-A") + git(repository, "-c", "user.name=test", "-c", "user.email=test@example.org", "commit", "-qm", message) + + +class TemplateLeftoversTest(unittest.TestCase): + def test_removes_only_exact_historical_copies(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + history = root / "history" + history.mkdir() + git(history, "init", "-q") + commit(history, {"scripts/sync-repos.mjs": "v1\n", ".github/repos.json": "{}\n"}, "eerste") + commit(history, {"scripts/sync-repos.mjs": "v2\n"}, "tweede") + git(history, "rm", "-q", ".github/repos.json") + git(history, "-c", "user.name=test", "-c", "user.email=test@example.org", "commit", "-qm", "weg") + + target = root / "document" + (target / "scripts").mkdir(parents=True) + (target / ".github").mkdir() + (target / "scripts" / "sync-repos.mjs").write_text("v1\n", encoding="utf-8") # oude versie + (target / ".github" / "repos.json").write_text("{}\n", encoding="utf-8") # verwijderd bestand + (target / "scripts" / "update-document-repos.mjs").write_text("eigen\n", encoding="utf-8") + (target / "scripts" / "eigen.mjs").write_text("v1\n", encoding="utf-8") # niet in de lijst + + files = ["scripts/sync-repos.mjs", ".github/repos.json", "scripts/update-document-repos.mjs"] + javascript = ( + f"import {{ knownTemplateBlobs, removeTemplateLeftovers }} from {json.dumps(LEFTOVERS_MODULE.as_uri())};" + f"const known = knownTemplateBlobs(process.argv[1], {json.dumps(files)});" + "console.log(JSON.stringify(removeTemplateLeftovers(process.argv[2], known)));" + ) + result = subprocess.run( + ["node", "--input-type=module", "--eval", javascript, str(history), str(target)], + check=True, + capture_output=True, + text=True, + ) + + removed = json.loads(result.stdout.strip().splitlines()[-1]) + self.assertEqual(sorted(removed), [".github/repos.json", "scripts/sync-repos.mjs"]) + self.assertTrue((target / "scripts" / "update-document-repos.mjs").exists()) + self.assertTrue((target / "scripts" / "eigen.mjs").exists()) + + def test_candidates_never_include_document_or_caller_files(self) -> None: + javascript = ( + f"import {{ TEMPLATE_LEFTOVER_FILES }} from {json.dumps(LEFTOVERS_MODULE.as_uri())};" + "console.log(JSON.stringify(TEMPLATE_LEFTOVER_FILES));" + ) + result = subprocess.run( + ["node", "--input-type=module", "--eval", javascript], check=True, capture_output=True, text=True + ) + candidates = json.loads(result.stdout) + + for protected in ( + "index.html", + "js/config.js", + "README.md", + "LICENSE", + "snapshot.html", + ".gitignore", + ".github/workflows/main.yml", + ".github/workflows/visual-regression.yml", + ): + self.assertNotIn(protected, candidates) + + def test_rollout_removes_leftovers_with_full_history(self) -> None: + source = UPDATE_SCRIPT.read_text(encoding="utf-8") + self.assertEqual(source.count("removeTemplateLeftovers(repoDir, templateBlobs)"), 2) + + steps = yaml.safe_load(ROLLOUT_WORKFLOW.read_text(encoding="utf-8"))["jobs"]["update"]["steps"] + checkout = next(step for step in steps if step.get("uses", "").startswith("actions/checkout@")) + self.assertEqual(checkout["with"]["fetch-depth"], 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/verify_mermaid_rendering.mjs b/tests/verify_mermaid_rendering.mjs new file mode 100644 index 0000000..dc5eb9c --- /dev/null +++ b/tests/verify_mermaid_rendering.mjs @@ -0,0 +1,114 @@ +// Uitvoeren vanuit een tijdelijke directory met @playwright/test, pngjs en puppeteer. +// node verify_mermaid_rendering.mjs +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { createServer } from "node:http"; +import { createRequire } from "node:module"; +import { copyFile, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { chromium } from "@playwright/test"; +import { PNG } from "pngjs"; + +const require = createRequire(import.meta.url); +const root = path.resolve(process.argv[2]); +const output = path.resolve(process.argv[3]); +const results = []; + +function run(command, args, options = {}) { + return new Promise((resolve, reject) => { + const child = spawn(command, args, { stdio: "inherit", ...options }); + child.on("error", reject); + child.on("exit", code => code === 0 ? resolve() : reject(new Error(`${command}: exit ${code}`))); + }); +} + +async function comparePng(before, after, label) { + const a = PNG.sync.read(await readFile(before)); + const b = PNG.sync.read(await readFile(after)); + assert.equal(b.width, a.width, `${label}: breedte`); + assert.equal(b.height, a.height, `${label}: hoogte`); + let different = 0; + for (let i = 0; i < a.data.length; i += 4) { + if (!a.data.subarray(i, i + 4).equals(b.data.subarray(i, i + 4))) different++; + } + results.push({ label, width: a.width, height: a.height, differentPixels: different }); + assert.equal(different, 0, `${label}: gewijzigde pixels`); +} + +await mkdir(output, { recursive: true }); +const server = createServer(async (request, response) => { + try { + const file = path.resolve(output, `.${new URL(request.url, "http://localhost").pathname}`); + if (!file.startsWith(`${output}${path.sep}`)) throw new Error("outside report"); + response.setHeader("Content-Type", "text/html; charset=utf-8"); + response.end(await readFile(file)); + } catch { + response.writeHead(404).end(); + } +}); +await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); +const url = `http://127.0.0.1:${server.address().port}`; +const browser = await chromium.launch(); +try { + for (const fixture of ["sensordata", "data-image"]) { + for (const variant of ["before", "after"]) { + const dir = path.join(output, fixture, variant); + await rm(dir, { recursive: true, force: true }); + await mkdir(dir, { recursive: true }); + await copyFile(path.join(root, `tests/fixtures/mermaid/${fixture}.html`), path.join(dir, "snapshot.html")); + } + await run(process.execPath, [path.join(root, ".github/workflows/normalize-mermaid-svg.mjs"), + path.join(output, fixture, "after/snapshot.html")]); + + for (const media of ["screen", "print"]) { + for (const width of [1440, 1024, 390]) { + const page = await browser.newPage({ viewport: { width, height: 1000 }, deviceScaleFactor: 1 }); + await page.emulateMedia({ media }); + const filename = `${media}-${width}.png`; + for (const variant of ["before", "after"]) { + await page.goto(`${url}/${fixture}/${variant}/snapshot.html`, { waitUntil: "networkidle" }); + await page.evaluate(() => document.fonts.ready); + if (fixture === "data-image") { + assert.equal(await page.locator("img").evaluateAll(images => + images.length > 0 && images.every(image => image.complete && image.naturalWidth > 0)), true); + } else { + assert.equal(await page.locator("svg").count(), 4); + } + await page.screenshot({ path: path.join(output, fixture, variant, filename), fullPage: true }); + } + await page.close(); + await comparePng(path.join(output, fixture, "before", filename), + path.join(output, fixture, "after", filename), `${fixture}/${media}/${width}`); + } + } + + // Roep precies de bestaande PDF-generator aan met zijn normale config- en + // snapshotcontract. Geen alternatieve testimplementatie van page.pdf(). + for (const variant of ["before", "after"]) { + const dir = path.join(output, fixture, variant); + await copyFile(path.join(root, ".github/workflows/pdf.js"), path.join(dir, "pdf.js")); + await writeFile(path.join(dir, "config.js"), + 'module.exports = {respecConfig:{alternateFormats:[{label:"pdf",uri:"diagram.pdf"}]}};\n'); + await run(process.execPath, ["pdf.js"], { cwd: dir, env: { + ...process.env, + NODE_PATH: path.dirname(path.dirname(require.resolve("puppeteer/package.json"))), + PUPPETEER_EXECUTABLE_PATH: chromium.executablePath(), + PDF_SNAPSHOT_URL: `${url}/${fixture}/${variant}/snapshot.html`, + } }); + await run("pdftoppm", ["-r", "96", "-png", path.join(dir, "diagram.pdf"), path.join(dir, "pdf-page")]); + } + const pages = (await readdir(path.join(output, fixture, "before"))).filter(file => file.startsWith("pdf-page")); + const afterPages = (await readdir(path.join(output, fixture, "after"))).filter(file => file.startsWith("pdf-page")); + assert.ok(pages.length > 0); + assert.deepEqual(afterPages, pages, `${fixture}: gelijk aantal PDF-pagina's`); + for (const page of pages) { + await comparePng(path.join(output, fixture, "before", page), + path.join(output, fixture, "after", page), `${fixture}/${page}`); + } + } +} finally { + await browser.close(); + await new Promise(resolve => server.close(resolve)); + await writeFile(path.join(output, "results.json"), JSON.stringify(results, null, 2)); +} +console.log(JSON.stringify(results, null, 2));