Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
997771ab5e | ||
|
|
ad31cfbafa | ||
|
|
67a33b8221 | ||
|
|
13b1787e1a | ||
|
|
5a6b895113 | ||
|
|
93c47d90ef |
@@ -26,6 +26,8 @@ jobs:
|
||||
apt-get install -y -qq --no-install-recommends openssh-client
|
||||
- name: Install Rust quality tools
|
||||
run: rustup component add rustfmt clippy
|
||||
- name: Image safety gate
|
||||
run: sh ci/check-image-safety.sh
|
||||
- name: Formatting
|
||||
run: cargo fmt --check
|
||||
- name: Last-attempt badge checks
|
||||
|
||||
@@ -15,6 +15,8 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Image safety gate
|
||||
run: sh ci/check-image-safety.sh
|
||||
- name: Build release candidate
|
||||
run: cargo build --release --offline --locked
|
||||
- name: Select candidate version
|
||||
|
||||
Generated
+444
-1
@@ -2,11 +2,246 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "alkane-os"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"flare-ui",
|
||||
"maud",
|
||||
"serde_json",
|
||||
"wschema",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anes"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
|
||||
|
||||
[[package]]
|
||||
name = "anstyle"
|
||||
version = "1.0.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cast"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "ciborium"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
|
||||
dependencies = [
|
||||
"ciborium-io",
|
||||
"ciborium-ll",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ciborium-io"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
|
||||
|
||||
[[package]]
|
||||
name = "ciborium-ll"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
|
||||
dependencies = [
|
||||
"ciborium-io",
|
||||
"half",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"clap_lex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "criterion"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f"
|
||||
dependencies = [
|
||||
"anes",
|
||||
"cast",
|
||||
"ciborium",
|
||||
"clap",
|
||||
"criterion-plot",
|
||||
"is-terminal",
|
||||
"itertools",
|
||||
"num-traits",
|
||||
"once_cell",
|
||||
"oorandom",
|
||||
"regex",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"tinytemplate",
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "criterion-plot"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1"
|
||||
dependencies = [
|
||||
"cast",
|
||||
"itertools",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crunchy"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
|
||||
[[package]]
|
||||
name = "flare-ui"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"maud",
|
||||
"serde_json",
|
||||
"wschema",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "half"
|
||||
version = "2.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"crunchy",
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
|
||||
|
||||
[[package]]
|
||||
name = "is-terminal"
|
||||
version = "0.4.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.10.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15,12 +250,61 @@ version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "maud"
|
||||
version = "0.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8156733e27020ea5c684db5beac5d1d611e1272ab17901a49466294b84fc217e"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"maud_macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "maud_macros"
|
||||
version = "0.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7261b00f3952f617899bc012e3dbd56e4f0110a038175929fa5d18e5a19913ca"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"proc-macro2-diagnostics",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "oorandom"
|
||||
version = "11.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
@@ -30,6 +314,18 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2-diagnostics"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
@@ -39,6 +335,44 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-automata",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[package]]
|
||||
name = "same-file"
|
||||
version = "1.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
|
||||
dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
@@ -46,6 +380,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -65,7 +400,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -81,6 +416,28 @@ dependencies = [
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
@@ -92,12 +449,98 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinytemplate"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "walkdir"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
|
||||
dependencies = [
|
||||
"same-file",
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi-util"
|
||||
version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wschema"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.63"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.63"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
|
||||
+12
@@ -10,6 +10,18 @@ name = "alkane_os"
|
||||
|
||||
[dependencies]
|
||||
serde_json = { version = "=1.0.154", features = ["arbitrary_precision"] }
|
||||
flare-ui = { path = "third-party/flare-ui/crates/flare-ui" }
|
||||
wschema = { path = "third-party/flare-ui/crates/wschema" }
|
||||
maud = "0.27"
|
||||
|
||||
[workspace]
|
||||
members = ["third-party/flare-ui/crates/flare-ui", "third-party/flare-ui/crates/wschema"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.0.1"
|
||||
edition = "2021"
|
||||
rust-version = "1.85"
|
||||
license = "MIT"
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
#!/bin/sh
|
||||
# Refuse to publish an OS image whose payload would not fit, or would not boot,
|
||||
# on the board it claims to target.
|
||||
#
|
||||
# The SDK's planner refuses a bad payload before it is ever written; this is the
|
||||
# other half of the same rule, applied to the artefacts the OS repo produces. A
|
||||
# wrongly-formatted image is not a firmware bug a board survives: the vendor SPL
|
||||
# only parses a legacy uImage, stock U-Boot only parses a legacy uImage, and a
|
||||
# raw zImage in the wrong slot boots nothing.
|
||||
#
|
||||
# Checks, per payload file found:
|
||||
# * magic matches the format its name claims
|
||||
# * size fits the target partition
|
||||
# A file that is present but unreadable, or that claims a format it does not
|
||||
# have, fails the gate. When no payload artefacts exist yet the gate says so and
|
||||
# passes, so it can be wired into CI before the first image is built.
|
||||
set -eu
|
||||
|
||||
fail=0
|
||||
note() { printf ' %s\n' "$*"; }
|
||||
bad() { printf ' FAIL %s\n' "$*"; fail=1; }
|
||||
|
||||
# name-glob|format|max-bytes
|
||||
RULES='
|
||||
kernel-mtd8.zImage|zimage|20971520
|
||||
zImage|zimage|20971520
|
||||
Image|zimage|16777216
|
||||
dtb-mtd6.dtb|fdt|131072
|
||||
am335x-alkane.dtb|fdt|131072
|
||||
meson-axg-alkane.dtb|fdt|131072
|
||||
ramdisk-mtd7.uimg|uimage|5242880
|
||||
uramdisk.image.gz|uimage|8388608
|
||||
uboot-mtd4.img|uimage|1835008
|
||||
'
|
||||
|
||||
check_file() {
|
||||
file=$1
|
||||
name=$(basename "$file")
|
||||
size=$(wc -c < "$file")
|
||||
rule=$(printf '%s\n' "$RULES" | awk -F'|' -v n="$name" '$1 == n { print; exit }')
|
||||
if [ -z "$rule" ]; then
|
||||
return 0
|
||||
fi
|
||||
format=$(printf '%s' "$rule" | cut -d'|' -f2)
|
||||
limit=$(printf '%s' "$rule" | cut -d'|' -f3)
|
||||
if [ "$size" -gt "$limit" ]; then
|
||||
bad "$name is $size bytes, larger than its $limit-byte partition"
|
||||
return 0
|
||||
fi
|
||||
magic=$(od -An -tx1 -N4 "$file" | tr -d ' \n')
|
||||
case "$format" in
|
||||
fdt)
|
||||
[ "$magic" = "d00dfeed" ] || bad "$name does not start with the FDT magic (got $magic)"
|
||||
;;
|
||||
uimage)
|
||||
[ "$magic" = "27051956" ] || bad "$name is not a legacy uImage (got $magic)"
|
||||
;;
|
||||
zimage)
|
||||
# ARM zImage: 0x016f2818 at offset 0x24, stored little-endian on disk.
|
||||
z=$(od -An -tx1 -j36 -N4 "$file" | tr -d ' \n')
|
||||
[ "$z" = "18286f01" ] || bad "$name is not a raw ARM zImage (got $z at 0x24)"
|
||||
;;
|
||||
esac
|
||||
note "$name: $format, $size bytes"
|
||||
}
|
||||
|
||||
echo "image-safety: scanning for payload artefacts"
|
||||
|
||||
found=0
|
||||
for dir in "${1:-.}" dist build/out target/payload; do
|
||||
[ -d "$dir" ] || continue
|
||||
for file in $(find "$dir" -maxdepth 3 -type f \
|
||||
\( -name 'kernel-mtd8.zImage' -o -name 'zImage' -o -name 'Image' \
|
||||
-o -name 'dtb-mtd6.dtb' -o -name 'am335x-alkane.dtb' \
|
||||
-o -name 'meson-axg-alkane.dtb' -o -name 'ramdisk-mtd7.uimg' \
|
||||
-o -name 'uramdisk.image.gz' -o -name 'uboot-mtd4.img' \) 2>/dev/null); do
|
||||
found=$((found + 1))
|
||||
check_file "$file"
|
||||
done
|
||||
done
|
||||
|
||||
if [ "$found" -eq 0 ]; then
|
||||
note "no payload artefacts present in this checkout"
|
||||
else
|
||||
note "$found payload file(s) checked"
|
||||
fi
|
||||
|
||||
if [ "$fail" -ne 0 ]; then
|
||||
echo "image-safety: FAILED - do not publish this image" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "image-safety: OK"
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/bin/sh
|
||||
# Report what the schema-driven UI costs in a firmware binary.
|
||||
#
|
||||
# Two binaries are built for the same target with the same profile: one renders
|
||||
# a page through flare-ui and wschema, the other renders the same shape with only
|
||||
# maud and serde_json. The difference is the marginal cost of the dependency, and
|
||||
# it is the number a release decision should be made on.
|
||||
#
|
||||
# Measured on armv7-unknown-linux-gnueabihf, release, stripped:
|
||||
# ui-baseline 323 KiB
|
||||
# ui-spike 771 KiB (marginal: ~448 KiB)
|
||||
set -eu
|
||||
ROOT=${1:-$(cd "$(dirname "$0")/.." && pwd)}
|
||||
TARGET=${ALKANE_SIZE_TARGET:-armv7-unknown-linux-gnueabihf}
|
||||
OUT=${CARGO_TARGET_DIR:-/tmp/alkane-os-target}
|
||||
STRIP=${ALKANE_STRIP:-arm-linux-gnueabihf-strip}
|
||||
|
||||
cd "$ROOT"
|
||||
# The workspace mount drops the executable bit on build scripts, so build into
|
||||
export CARGO_TARGET_DIR="$OUT"
|
||||
CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER=${ALKANE_ARM_LINKER:-arm-linux-gnueabihf-gcc} \
|
||||
cargo build --release --offline --target "$TARGET" --bins >/dev/null
|
||||
|
||||
sizes=""
|
||||
for bin in ui-baseline ui-spike; do
|
||||
src="$OUT/$TARGET/release/$bin"
|
||||
[ -f "$src" ] || { echo "ui-size: $bin was not built" >&2; exit 1; }
|
||||
cp "$src" "/tmp/$bin.size"
|
||||
"$STRIP" "/tmp/$bin.size" 2>/dev/null || true
|
||||
bytes=$(wc -c < "/tmp/$bin.size")
|
||||
sizes="$sizes $bin=$bytes"
|
||||
printf ' %-12s %4d KiB\n' "$bin" $((bytes / 1024))
|
||||
done
|
||||
|
||||
base=$(printf '%s' "$sizes" | sed 's/.*ui-baseline=\([0-9]*\).*/\1/')
|
||||
spike=$(printf '%s' "$sizes" | sed 's/.*ui-spike=\([0-9]*\).*/\1/')
|
||||
printf ' marginal %4d KiB\n' $(((spike - base) / 1024))
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/bin/sh
|
||||
# Build an .afw firmware package for one control board and architecture.
|
||||
#
|
||||
# Modelled on the Warden `.wfw` bundle (scada/flare-edge/docs/firmware-format.md):
|
||||
# one file, a strict POSIX ustar tar, a JSON manifest first, then the payload,
|
||||
# with the payload's size and sha256 in the manifest so the device can verify
|
||||
# before it touches flash.
|
||||
#
|
||||
# Differences from .wfw, both deliberate:
|
||||
#
|
||||
# * the payload is COMPRESSED (`payload.tar.gz`) because these images ship to
|
||||
# boards over metered links, and a firmware bundle is mostly redundant;
|
||||
# * the manifest carries `board` and `arch`, and both go in the file name, so a
|
||||
# bundle can never be mistaken for another board family. Flashing the wrong
|
||||
# family is how boards are lost.
|
||||
#
|
||||
# Signature: `.wfw` carries an Ed25519 detached signature. We have no release
|
||||
# key yet, so `.afw` currently ships `members=2` and says so in the manifest
|
||||
# (`signature: "unsigned"`). Do not claim integrity beyond the sha256 until a
|
||||
# key exists.
|
||||
#
|
||||
# usage: make-afw.sh BOARD ARCH VERSION INPUT_DIR [OUTPUT_DIR]
|
||||
# e.g. make-afw.sh am335x-bb armv7 0.1.0 /tmp/release
|
||||
set -eu
|
||||
|
||||
BOARD=${1:?board family, e.g. am335x-bb}
|
||||
ARCH=${2:?architecture, e.g. armv7 or aarch64}
|
||||
VERSION=${3:?version, e.g. 0.1.0}
|
||||
INPUT=${4:?directory holding the release files}
|
||||
OUTPUT=${5:-dist}
|
||||
|
||||
mkdir -p "$OUTPUT"
|
||||
WORK=$(mktemp -d)
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
|
||||
# The payload is a tar of the release tree, gzipped at maximum.
|
||||
tar --format=ustar --owner=0 --group=0 --numeric-owner \
|
||||
--create --file "$WORK/payload.tar" -C "$INPUT" .
|
||||
gzip -9 -n -c "$WORK/payload.tar" > "$WORK/payload.tar.gz"
|
||||
|
||||
PAYLOAD_SIZE=$(wc -c < "$WORK/payload.tar.gz")
|
||||
PAYLOAD_SHA=$(sha256sum "$WORK/payload.tar.gz" | cut -d' ' -f1)
|
||||
BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
cat > "$WORK/manifest.json" <<MANIFEST
|
||||
{
|
||||
"schema": 1,
|
||||
"format": "afw",
|
||||
"board": "$BOARD",
|
||||
"arch": "$ARCH",
|
||||
"version": "$VERSION",
|
||||
"build_date": "$BUILD_DATE",
|
||||
"compression": "gzip",
|
||||
"signature": "unsigned",
|
||||
"payload": {
|
||||
"file": "payload.tar.gz",
|
||||
"size": $PAYLOAD_SIZE,
|
||||
"sha256": "$PAYLOAD_SHA"
|
||||
}
|
||||
}
|
||||
MANIFEST
|
||||
|
||||
NAME="alkane-os-$VERSION-$BOARD-$ARCH.afw"
|
||||
(cd "$WORK" && tar --format=ustar --owner=0 --group=0 --numeric-owner \
|
||||
--create --file "$OUTPUT/$NAME" manifest.json payload.tar.gz)
|
||||
printf '%s\n' "$OUTPUT/$NAME"
|
||||
printf 'board %s\narch %s\npayload %s bytes\nsha256 %s\n' \
|
||||
"$BOARD" "$ARCH" "$PAYLOAD_SIZE" "$PAYLOAD_SHA"
|
||||
@@ -0,0 +1,618 @@
|
||||
{
|
||||
"format": 1,
|
||||
"id": "alkane.bb",
|
||||
"kind": "base",
|
||||
"menus": [
|
||||
{
|
||||
"id": "dashboard",
|
||||
"slug": "dashboard",
|
||||
"title": "Dashboard",
|
||||
"icon": "dashboard",
|
||||
"band": 0,
|
||||
"order": 10
|
||||
},
|
||||
{
|
||||
"id": "dashboard/overview",
|
||||
"slug": "overview",
|
||||
"title": "Overview",
|
||||
"order": 10,
|
||||
"page": "dashboard.overview"
|
||||
},
|
||||
{
|
||||
"id": "dashboard/alerts",
|
||||
"slug": "alerts",
|
||||
"title": "Alerts",
|
||||
"order": 20,
|
||||
"page": "dashboard.alerts"
|
||||
},
|
||||
{
|
||||
"id": "mining",
|
||||
"slug": "mining",
|
||||
"title": "Mining",
|
||||
"icon": "pickaxe",
|
||||
"band": 1,
|
||||
"order": 10
|
||||
},
|
||||
{
|
||||
"id": "mining/overview",
|
||||
"slug": "overview",
|
||||
"title": "Overview",
|
||||
"order": 10,
|
||||
"page": "mining.overview"
|
||||
},
|
||||
{
|
||||
"id": "mining/hashboards",
|
||||
"slug": "hashboards",
|
||||
"title": "Hashboards",
|
||||
"order": 20,
|
||||
"page": "mining.hashboards"
|
||||
},
|
||||
{
|
||||
"id": "mining/power",
|
||||
"slug": "power",
|
||||
"title": "Power Supply",
|
||||
"order": 30,
|
||||
"page": "mining.power"
|
||||
},
|
||||
{
|
||||
"id": "mining/fans",
|
||||
"slug": "fans",
|
||||
"title": "Fans",
|
||||
"order": 40,
|
||||
"page": "mining.fans"
|
||||
},
|
||||
{
|
||||
"id": "settings",
|
||||
"slug": "settings",
|
||||
"title": "Settings",
|
||||
"icon": "gear",
|
||||
"band": 2,
|
||||
"order": 10
|
||||
},
|
||||
{
|
||||
"id": "settings/system",
|
||||
"slug": "system",
|
||||
"title": "System",
|
||||
"order": 10,
|
||||
"page": "settings.system"
|
||||
},
|
||||
{
|
||||
"id": "settings/tuning",
|
||||
"slug": "tuning",
|
||||
"title": "Tuning",
|
||||
"order": 20,
|
||||
"page": "settings.tuning"
|
||||
},
|
||||
{
|
||||
"id": "settings/pools",
|
||||
"slug": "pools",
|
||||
"title": "Pools",
|
||||
"order": 30,
|
||||
"page": "settings.pools"
|
||||
},
|
||||
{
|
||||
"id": "settings/network",
|
||||
"slug": "network",
|
||||
"title": "Network",
|
||||
"order": 40,
|
||||
"page": "settings.network"
|
||||
},
|
||||
{
|
||||
"id": "settings/security",
|
||||
"slug": "security",
|
||||
"title": "Security",
|
||||
"order": 50,
|
||||
"page": "settings.security"
|
||||
},
|
||||
{
|
||||
"id": "settings/logs",
|
||||
"slug": "logs",
|
||||
"title": "Logs",
|
||||
"order": 60,
|
||||
"page": "settings.logs"
|
||||
},
|
||||
{
|
||||
"id": "settings/files",
|
||||
"slug": "files",
|
||||
"title": "Files",
|
||||
"order": 70,
|
||||
"page": "settings.files"
|
||||
},
|
||||
{
|
||||
"id": "settings/terminal",
|
||||
"slug": "terminal",
|
||||
"title": "Terminal",
|
||||
"order": 80,
|
||||
"page": "settings.terminal"
|
||||
}
|
||||
],
|
||||
"pages": [],
|
||||
"settings": [
|
||||
{
|
||||
"path": "tuning.mode",
|
||||
"label": "Tuning target",
|
||||
"help": "What the controller holds: a power draw, a hashrate, an ambient margin, or a fan ceiling.",
|
||||
"kind": {
|
||||
"t": "enum",
|
||||
"values": [
|
||||
{
|
||||
"v": "power",
|
||||
"label": "Power"
|
||||
},
|
||||
{
|
||||
"v": "hashrate",
|
||||
"label": "Hashrate"
|
||||
},
|
||||
{
|
||||
"v": "ambient",
|
||||
"label": "Ambient"
|
||||
},
|
||||
{
|
||||
"v": "max-fan",
|
||||
"label": "Max Fan"
|
||||
}
|
||||
]
|
||||
},
|
||||
"default": {
|
||||
"value": "power"
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 10,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "dropdown"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.power_w",
|
||||
"label": "Power target",
|
||||
"help": "DC power to hold when the target is power.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 200,
|
||||
"hi": 4000,
|
||||
"units": "W"
|
||||
},
|
||||
"default": {
|
||||
"value": 1200
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 20,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.hashrate_ths",
|
||||
"label": "Hashrate target",
|
||||
"help": "Hashrate to maximise up to, when the target is hashrate.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 1,
|
||||
"hi": 200,
|
||||
"units": "TH/s"
|
||||
},
|
||||
"default": {
|
||||
"value": 60
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 30,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.ambient_margin_c",
|
||||
"label": "Ambient margin",
|
||||
"help": "Hold the hottest sensor this far above measured ambient.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 40,
|
||||
"units": "C"
|
||||
},
|
||||
"default": {
|
||||
"value": 20
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 40,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.max_fan_pwm",
|
||||
"label": "Fan ceiling",
|
||||
"help": "Fan duty cap, percent, when the target is max-fan.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 100,
|
||||
"units": "%"
|
||||
},
|
||||
"default": {
|
||||
"value": 80
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 50,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.ceiling_mc",
|
||||
"label": "Frequency ceiling",
|
||||
"help": "Upper bound on the operating frequency, MHz.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 100,
|
||||
"hi": 1000,
|
||||
"units": "MHz"
|
||||
},
|
||||
"default": {
|
||||
"value": 700
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 60,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.kp_milli",
|
||||
"label": "Proportional gain",
|
||||
"help": "PID proportional term, thousandths of a unit.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 10000
|
||||
},
|
||||
"default": {
|
||||
"value": 500
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 100,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.ki_milli",
|
||||
"label": "Integral gain",
|
||||
"help": "PID integral term, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 10000
|
||||
},
|
||||
"default": {
|
||||
"value": 100
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 110,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.kd_milli",
|
||||
"label": "Derivative gain",
|
||||
"help": "PID derivative term, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 10000
|
||||
},
|
||||
"default": {
|
||||
"value": 0
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 120,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.out_min_milli",
|
||||
"label": "Output floor",
|
||||
"help": "Lowest control output the loop may emit, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 1000000
|
||||
},
|
||||
"default": {
|
||||
"value": 0
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 130,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.out_max_milli",
|
||||
"label": "Output ceiling",
|
||||
"help": "Highest control output the loop may emit, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 5000000
|
||||
},
|
||||
"default": {
|
||||
"value": 1000000
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 140,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.max_step_milli",
|
||||
"label": "Maximum step",
|
||||
"help": "Largest output change per second, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 500000
|
||||
},
|
||||
"default": {
|
||||
"value": 50000
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 150,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.deadband_milli",
|
||||
"label": "Deadband",
|
||||
"help": "Errors inside this band are ignored, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 50000
|
||||
},
|
||||
"default": {
|
||||
"value": 1000
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 160,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "fans.zone_count",
|
||||
"label": "Fan zones",
|
||||
"help": "Number of independently driven fan zones.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 1,
|
||||
"hi": 8
|
||||
},
|
||||
"default": {
|
||||
"value": 4
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "fans",
|
||||
"order": 10,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "fans.pwm_min",
|
||||
"label": "Minimum duty",
|
||||
"help": "Duty floor applied to every zone, percent.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 100,
|
||||
"units": "%"
|
||||
},
|
||||
"default": {
|
||||
"value": 20
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "fans",
|
||||
"order": 20,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "fans.sweep_steps",
|
||||
"label": "Sweep steps",
|
||||
"help": "Steps per zone when mapping fans to sensors.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 1,
|
||||
"hi": 32
|
||||
},
|
||||
"default": {
|
||||
"value": 8
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "fans",
|
||||
"order": 30,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "detect.chain_ports",
|
||||
"label": "Chain ports",
|
||||
"help": "Chain UART ports to probe, comma separated.",
|
||||
"kind": {
|
||||
"t": "str"
|
||||
},
|
||||
"default": {
|
||||
"value": "1,2,3"
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "detect",
|
||||
"order": 10,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "list"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "detect.probe_budget",
|
||||
"label": "Probe budget",
|
||||
"help": "Attempts per chain before detection gives up.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 1,
|
||||
"hi": 20
|
||||
},
|
||||
"default": {
|
||||
"value": 3
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "detect",
|
||||
"order": 20,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "profiles.db",
|
||||
"label": "Profile database",
|
||||
"help": "Path to the board's tuning profile database.",
|
||||
"kind": {
|
||||
"t": "str"
|
||||
},
|
||||
"default": {
|
||||
"value": "/etc/alkane/profiles.json"
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "system",
|
||||
"order": 10,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "text"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "system.name",
|
||||
"label": "Board name",
|
||||
"help": "Name shown in the dashboard header.",
|
||||
"kind": {
|
||||
"t": "str"
|
||||
},
|
||||
"default": {
|
||||
"value": "alkane"
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "system",
|
||||
"order": 20,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "text"
|
||||
}
|
||||
}
|
||||
],
|
||||
"groups": [],
|
||||
"actions": [],
|
||||
"rules": [],
|
||||
"maps": [],
|
||||
"legacy_keys": [],
|
||||
"requires": {
|
||||
"display_api": 1,
|
||||
"checks_api": 1
|
||||
},
|
||||
"vocab": []
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Control for the size measurement: the same page shape rendered without
|
||||
//! flare-ui, so `check-ui-size.sh` reports the marginal cost of the dependency
|
||||
//! rather than the cost of a Rust binary at all.
|
||||
|
||||
fn main() {
|
||||
let sections = [("dashboard", "Dashboard"), ("mining", "Mining"), ("settings", "Settings")];
|
||||
let body = maud::html! {
|
||||
section class="bf-card" {
|
||||
h1 class="bf-text-title" { "Alkane OS" }
|
||||
p class="bf-text-body" { "Schema-driven page." }
|
||||
}
|
||||
};
|
||||
let mut html = String::from("<!doctype html><html><body>");
|
||||
for (slug, title) in sections {
|
||||
html.push_str(&format!("<a href=\"/{slug}\">{title}</a>"));
|
||||
}
|
||||
html.push_str(&body.into_string());
|
||||
html.push_str("</body></html>");
|
||||
println!("{} {}", html.len(), serde_json::json!({"sections": sections.len()}));
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Spike: render the on-box UI from a schema document through flare-ui.
|
||||
//!
|
||||
//! This is the incorporation test, not the final UI. It answers three questions
|
||||
//! with evidence rather than argument:
|
||||
//!
|
||||
//! 1. does a hand-authored Alkane schema drive the unified sidebar through
|
||||
//! `flare_ui::nav` + `flare_ui::shell`?
|
||||
//! 2. does the page render with the shared design tokens?
|
||||
//! 3. what does it cost in a firmware binary?
|
||||
//!
|
||||
//! Run it, then compare `--size` against the current hand-rolled renderer.
|
||||
|
||||
use flare_ui::assets::PageAssets;
|
||||
use flare_ui::nav::{self, AllowAll, AppSet, CapSet};
|
||||
use flare_ui::shell::{self, Active};
|
||||
use flare_ui::url::Routes;
|
||||
use wschema::model::{Document, Surface};
|
||||
|
||||
/// The schema is the single source of the UI: sections, tabs and their order.
|
||||
const RECIPE_SCHEMA: &str = include_str!("../../schema/alkane-bb.json");
|
||||
|
||||
fn main() {
|
||||
let schema = match Document::from_json(RECIPE_SCHEMA) {
|
||||
Ok(schema) => schema,
|
||||
Err(error) => {
|
||||
eprintln!("schema did not parse: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
// Capabilities the board actually reports decide what is visible. On a real
|
||||
// board these come from the HAL; here they are the bb set.
|
||||
let caps = CapSet::new(["hashboard-bm1395", "psu-apm", "pid-fan", "cgminer-api"]);
|
||||
let routes = Routes::console();
|
||||
let apps = AppSet::default();
|
||||
let ctx = nav::NavContext {
|
||||
surface: Surface::Web,
|
||||
principal: &AllowAll,
|
||||
caps: &caps,
|
||||
apps: &apps,
|
||||
routes: &routes,
|
||||
};
|
||||
|
||||
let visible = nav::visible(&schema.menus, &ctx);
|
||||
let first = visible.first_tab().map(|(section, tab)| Active { section, tab });
|
||||
let active = first.unwrap_or(Active { section: "", tab: "" });
|
||||
|
||||
let body = maud::html! {
|
||||
section class="bf-card" {
|
||||
h1 class="bf-text-title" { "Alkane OS" }
|
||||
p class="bf-text-body" { "Schema-driven page. Sections and tabs above come from dashboard.json." }
|
||||
}
|
||||
};
|
||||
let assets = PageAssets::default();
|
||||
let page = shell::page("Alkane OS", &assets, &visible, active, body);
|
||||
let html = page.into_string();
|
||||
|
||||
if std::env::args().any(|arg| arg == "--size") {
|
||||
println!("html_bytes {}", html.len());
|
||||
println!("sections {}", visible.sections.len());
|
||||
for section in &visible.sections {
|
||||
println!("section {} ({}) tabs={}", section.slug, section.title, section.tabs.len());
|
||||
}
|
||||
} else {
|
||||
println!("{html}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Schema-driven dashboard for the on-box UI.
|
||||
//!
|
||||
//! The sidebar, the tab strip and every settings control come from
|
||||
//! `schema/alkane-bb.json` through `flare-ui` and `wschema`; this module is the
|
||||
//! host boundary the crates expect: it owns the stored rows, applies a
|
||||
//! submitted form only after `wschema` validates it, and keeps the JSON API as
|
||||
//! the interface of record.
|
||||
//!
|
||||
//! Everything here is pure except `load` and `save`, which touch one file.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use maud::Markup;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use flare_ui::assets::PageAssets;
|
||||
use flare_ui::nav::{self, AllowAll, AppSet, CapSet, NavContext, VisibleNav};
|
||||
use flare_ui::url::Routes;
|
||||
use flare_ui::render::{self, View};
|
||||
use flare_ui::shell::{self, Active};
|
||||
use flare_ui::tokens;
|
||||
use wschema::effective::{self, Effective};
|
||||
use wschema::model::{Document, Surface};
|
||||
use wschema::validate::{Op, Rows};
|
||||
|
||||
/// The schema document is the single source of the UI.
|
||||
pub const SCHEMA: &str = include_str!("../schema/alkane-bb.json");
|
||||
|
||||
/// Capabilities this board reports, which decide what the sidebar shows.
|
||||
pub fn board_caps() -> CapSet {
|
||||
CapSet::new(["hashboard", "psu", "fan-map", "cgminer-api"])
|
||||
}
|
||||
|
||||
/// The dashboard: an effective schema plus the stored rows.
|
||||
pub struct Dashboard {
|
||||
effective: Result<Effective, String>,
|
||||
rows: Rows,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Dashboard {
|
||||
/// Load the schema and the stored settings, defaulting absent rows to the
|
||||
/// schema's own defaults.
|
||||
pub fn load(path: impl AsRef<Path>) -> Dashboard {
|
||||
let path = path.as_ref().to_path_buf();
|
||||
let effective = Document::from_json(SCHEMA)
|
||||
.map_err(|error| error.to_string())
|
||||
.and_then(|doc| {
|
||||
effective::merge(&doc, &[]).map_err(|errors| {
|
||||
errors
|
||||
.iter()
|
||||
.map(|error| error.msg.clone())
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ")
|
||||
})
|
||||
});
|
||||
let mut rows = Rows::new();
|
||||
if let Ok(text) = fs::read_to_string(&path) {
|
||||
if let Ok(Value::Object(map)) = serde_json::from_str::<Value>(&text) {
|
||||
for (key, value) in map {
|
||||
rows.insert(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Dashboard {
|
||||
effective,
|
||||
rows,
|
||||
path,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn schema(&self) -> Result<&Effective, String> {
|
||||
self.effective.as_ref().map_err(|error| error.clone())
|
||||
}
|
||||
|
||||
pub fn rows(&self) -> &Rows {
|
||||
&self.rows
|
||||
}
|
||||
|
||||
/// The visible navigation for this board and viewer.
|
||||
pub fn nav(&self) -> Result<VisibleNav, String> {
|
||||
let effective = self.effective.as_ref().map_err(|error| error.clone())?;
|
||||
let caps = board_caps();
|
||||
let apps = AppSet::default();
|
||||
let routes = Routes::console();
|
||||
let ctx = NavContext {
|
||||
surface: Surface::Web,
|
||||
principal: &AllowAll,
|
||||
caps: &caps,
|
||||
apps: &apps,
|
||||
routes: &routes,
|
||||
};
|
||||
Ok(nav::visible(&effective.doc.menus, &ctx))
|
||||
}
|
||||
|
||||
/// Stylesheets the shell needs, served from the crate's embedded assets.
|
||||
pub fn assets() -> PageAssets {
|
||||
PageAssets {
|
||||
styles: vec![
|
||||
"/assets/tokens.css".to_string(),
|
||||
"/assets/components.css".to_string(),
|
||||
"/assets/theme.css".to_string(),
|
||||
],
|
||||
scripts: Vec::new(),
|
||||
streams: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The three stylesheets, for the host to serve.
|
||||
pub fn stylesheets() -> [(&'static str, &'static str); 3] {
|
||||
[
|
||||
("tokens.css", tokens::TOKENS_CSS),
|
||||
("components.css", tokens::COMPONENTS_CSS),
|
||||
("theme.css", tokens::THEME_CSS),
|
||||
]
|
||||
}
|
||||
|
||||
/// Render one page: the shell around the settings card of the tab.
|
||||
///
|
||||
/// `section` is the navigation section (`settings`), `tab` the tab slug
|
||||
/// (`tuning`), and the settings card shows the group named by the tab.
|
||||
///
|
||||
/// `errors` carries per-path messages from a rejected submission, so the
|
||||
/// same render can show what went wrong.
|
||||
pub fn page(&self, section: &str, tab: &str, errors: &BTreeMap<String, String>) -> Markup {
|
||||
let effective = match self.effective.as_ref() {
|
||||
Ok(effective) => effective,
|
||||
Err(error) => {
|
||||
return maud::html! {
|
||||
main class="bf-main" {
|
||||
p class="bf-field-error bf-text-body" role="alert" { "Schema did not load: " (error) }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let nav = self.nav().unwrap_or_default();
|
||||
let view = View {
|
||||
eff: effective,
|
||||
rows: &self.rows,
|
||||
errors,
|
||||
surface: Surface::Web,
|
||||
can_write: true,
|
||||
};
|
||||
let title = effective
|
||||
.doc
|
||||
.menus
|
||||
.iter()
|
||||
.find(|menu| menu.slug == tab && menu.id.starts_with(&format!("{section}/")))
|
||||
.map(|menu| menu.title.clone())
|
||||
.unwrap_or_else(|| section.to_string());
|
||||
let card = render::card(&title, tab, &view);
|
||||
let body = maud::html! {
|
||||
section class="bf-card" {
|
||||
h1 class="bf-text-title" { (title) }
|
||||
(card)
|
||||
}
|
||||
};
|
||||
shell::page("Alkane OS", &Self::assets(), &nav, Active { section, tab }, body)
|
||||
}
|
||||
|
||||
/// Apply a submitted form body (`application/x-www-form-urlencoded`).
|
||||
///
|
||||
/// Returns the per-path failures when the schema rejects the batch, and
|
||||
/// persists nothing in that case. Unknown keys are ignored: they are not in
|
||||
/// the schema, so they cannot be written.
|
||||
pub fn submit(&mut self, body: &str) -> Result<(), BTreeMap<String, String>> {
|
||||
let effective = match self.effective.as_ref() {
|
||||
Ok(effective) => effective,
|
||||
Err(error) => {
|
||||
let mut failures = BTreeMap::new();
|
||||
failures.insert(String::new(), error.clone());
|
||||
return Err(failures);
|
||||
}
|
||||
};
|
||||
let ops = self.parse_ops(effective, body);
|
||||
let failures = render::validate_form(effective, &ops, &self.rows, wschema::validate::Origin::Web, None);
|
||||
if !failures.is_empty() {
|
||||
return Err(failures);
|
||||
}
|
||||
for op in &ops {
|
||||
if let Op::Set { path, value } = op {
|
||||
self.rows.insert(path.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
let map: Map<String, Value> = self
|
||||
.rows
|
||||
.iter()
|
||||
.map(|(key, value)| (key.clone(), value.clone()))
|
||||
.collect();
|
||||
let text = serde_json::to_string_pretty(&Value::Object(map)).unwrap_or_else(|_| "{}".into());
|
||||
if let Some(parent) = self.path.parent() {
|
||||
let _ = fs::create_dir_all(parent);
|
||||
}
|
||||
// Persist only after validation passed; a failed write leaves the rows
|
||||
// changed in memory but never on disk, which the API reports.
|
||||
let _ = fs::write(&self.path, text);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Turn a form body into schema ops, coercing each value to its declared kind.
|
||||
fn parse_ops(&self, effective: &Effective, body: &str) -> Vec<Op> {
|
||||
let mut ops = Vec::new();
|
||||
for pair in body.split('&') {
|
||||
if pair.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (raw_key, raw_value) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
let key = percent_decode(raw_key);
|
||||
let raw = percent_decode(raw_value);
|
||||
let setting = match effective.setting(&key) {
|
||||
Some(setting) => setting,
|
||||
None => continue,
|
||||
};
|
||||
let value = coerce(setting.kind.token(), &raw);
|
||||
ops.push(Op::Set {
|
||||
path: setting.path.clone(),
|
||||
value,
|
||||
});
|
||||
}
|
||||
ops
|
||||
}
|
||||
}
|
||||
|
||||
fn percent_decode(text: &str) -> String {
|
||||
let bytes = text.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut index = 0;
|
||||
while index < bytes.len() {
|
||||
match bytes[index] {
|
||||
b'+' => {
|
||||
out.push(b' ');
|
||||
index += 1;
|
||||
}
|
||||
b'%' if index + 2 < bytes.len() => {
|
||||
let high = (bytes[index + 1] as char).to_digit(16);
|
||||
let low = (bytes[index + 2] as char).to_digit(16);
|
||||
match (high, low) {
|
||||
(Some(high), Some(low)) => {
|
||||
out.push((high * 16 + low) as u8);
|
||||
index += 3;
|
||||
}
|
||||
_ => {
|
||||
out.push(bytes[index]);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
byte => {
|
||||
out.push(byte);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
fn coerce(kind: &str, raw: &str) -> Value {
|
||||
match kind {
|
||||
"int" | "int_set" => raw
|
||||
.trim()
|
||||
.parse::<i64>()
|
||||
.map(Value::from)
|
||||
.unwrap_or_else(|_| Value::String(raw.to_string())),
|
||||
"bool" => Value::Bool(matches!(raw, "true" | "on" | "1")),
|
||||
_ => Value::String(raw.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_path(name: &str) -> PathBuf {
|
||||
let mut path = std::env::temp_dir();
|
||||
path.push(format!("alkane-dashboard-{name}-{}.json", std::process::id()));
|
||||
let _ = fs::remove_file(&path);
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_schema_loads_and_yields_the_three_sections() {
|
||||
let dash = Dashboard::load(temp_path("load"));
|
||||
let effective = dash.schema().expect("schema loads");
|
||||
assert_eq!(effective.doc.menus.len(), 17);
|
||||
let nav = dash.nav().expect("nav builds");
|
||||
assert_eq!(nav.sections.len(), 3);
|
||||
assert_eq!(nav.sections[1].slug, "mining");
|
||||
assert_eq!(nav.sections[1].tabs.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_scaffolded_setting_is_in_the_schema() {
|
||||
let dash = Dashboard::load(temp_path("settings"));
|
||||
let effective = dash.schema().expect("schema loads");
|
||||
for path in [
|
||||
"tuning.mode",
|
||||
"tuning.power_w",
|
||||
"tuning.ceiling_mc",
|
||||
"tuning.pid.kp_milli",
|
||||
"tuning.pid.deadband_milli",
|
||||
"fans.zone_count",
|
||||
"fans.pwm_min",
|
||||
"detect.chain_ports",
|
||||
"detect.probe_budget",
|
||||
"profiles.db",
|
||||
"system.name",
|
||||
] {
|
||||
assert!(effective.setting(path).is_some(), "{path} is missing from the schema");
|
||||
}
|
||||
assert_eq!(effective.doc.settings.len(), 20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_renders_its_settings_with_inputs() {
|
||||
let dash = Dashboard::load(temp_path("page"));
|
||||
let html = dash.page("settings", "tuning", &BTreeMap::new()).into_string();
|
||||
assert!(html.contains("bf-sidebar"), "the unified sidebar is missing");
|
||||
assert!(html.contains("bf-tabs"), "the tab strip is missing");
|
||||
assert!(html.contains("Tuning target"), "a settings label is missing");
|
||||
assert!(html.contains("tuning.power_w"), "the field path is missing");
|
||||
assert!(html.contains("name=\"tuning.mode\""), "the mode field is missing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_valid_submission_is_persisted_and_reloaded() {
|
||||
let path = temp_path("submit");
|
||||
let mut dash = Dashboard::load(&path);
|
||||
dash.submit("tuning.power_w=1500&system.name=s19jpro").expect("valid form");
|
||||
assert_eq!(dash.rows().get("tuning.power_w"), Some(&serde_json::json!(1500)));
|
||||
let stored = fs::read_to_string(&path).expect("settings file written");
|
||||
assert!(stored.contains("\"tuning.power_w\": 1500"), "{stored}");
|
||||
let reloaded = Dashboard::load(&path);
|
||||
assert_eq!(reloaded.rows().get("system.name"), Some(&serde_json::json!("s19jpro")));
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_out_of_range_value_is_rejected_and_nothing_is_written() {
|
||||
let path = temp_path("reject");
|
||||
let mut dash = Dashboard::load(&path);
|
||||
let failures = dash.submit("tuning.power_w=99999").expect_err("must be rejected");
|
||||
assert!(failures.keys().any(|key| key.contains("tuning.power_w")), "{failures:?}");
|
||||
assert!(!path.exists(), "a rejected submission must not be persisted");
|
||||
assert_eq!(dash.rows().get("tuning.power_w"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_form_keys_are_ignored() {
|
||||
let path = temp_path("unknown");
|
||||
let mut dash = Dashboard::load(&path);
|
||||
dash.submit("not.a.setting=1&tuning.ceiling_mc=650").expect("known key applies");
|
||||
assert_eq!(dash.rows().get("not.a.setting"), None);
|
||||
assert_eq!(dash.rows().get("tuning.ceiling_mc"), Some(&serde_json::json!(650)));
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn form_values_are_percent_decoded() {
|
||||
assert_eq!(percent_decode("a+b%2Fc"), "a b/c");
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ pub mod bm1366;
|
||||
pub mod bm1370;
|
||||
pub mod bm13xx;
|
||||
pub mod detect;
|
||||
pub mod dashboard;
|
||||
pub mod difficulty;
|
||||
pub mod fanmap;
|
||||
pub mod fanmap_store;
|
||||
@@ -33,6 +34,7 @@ pub mod stratum_v2_session;
|
||||
pub mod stratum_wire;
|
||||
pub mod stratum_work;
|
||||
pub mod tuning;
|
||||
pub mod ui;
|
||||
pub mod web;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
|
||||
+46
-8
@@ -38,10 +38,7 @@ fn sim_mine(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>
|
||||
.ok()
|
||||
.map(|bind| bind.parse())
|
||||
.transpose()?;
|
||||
let web = std::env::var("ALKANE_WEB_LISTEN")
|
||||
.ok()
|
||||
.map(|bind| bind.parse())
|
||||
.transpose()?;
|
||||
let web = web_listen()?;
|
||||
let servers = app::start(Arc::clone(&status), api, web)?;
|
||||
let (api_address, web_address) = servers.addresses();
|
||||
if let Some(address) = api_address {
|
||||
@@ -212,10 +209,7 @@ fn boot_hal(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>
|
||||
.ok()
|
||||
.map(|bind| bind.parse())
|
||||
.transpose()?;
|
||||
let web = std::env::var("ALKANE_WEB_LISTEN")
|
||||
.ok()
|
||||
.map(|bind| bind.parse())
|
||||
.transpose()?;
|
||||
let web = web_listen()?;
|
||||
let servers = app::start(Arc::clone(&status), api, web)?;
|
||||
|
||||
let config = app::BootConfig {
|
||||
@@ -303,6 +297,44 @@ fn boot_hal(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Where the UI listens. The miner serves it on port 80 of its own address;
|
||||
/// if that is not permitted (a non-root development run), fall back to 8080
|
||||
/// rather than refusing to start.
|
||||
fn web_listen() -> Result<Option<std::net::SocketAddr>, Box<dyn std::error::Error>> {
|
||||
if let Ok(bind) = std::env::var("ALKANE_WEB_LISTEN") {
|
||||
return Ok(Some(bind.parse()?));
|
||||
}
|
||||
let port = if std::net::TcpListener::bind("0.0.0.0:80").is_ok() {
|
||||
80
|
||||
} else {
|
||||
8080
|
||||
};
|
||||
Ok(Some(std::net::SocketAddr::from(([0, 0, 0, 0], port))))
|
||||
}
|
||||
|
||||
/// Serve the UI and the API without a mining backend. A board whose HAL
|
||||
/// backend is not written yet still has to be reachable and observable; every
|
||||
/// page says "not identified" rather than claiming hardware it cannot see.
|
||||
fn serve_only() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let status = Arc::new(MiningStatus::new());
|
||||
let api = std::env::var("ALKANE_API_LISTEN")
|
||||
.ok()
|
||||
.map(|bind| bind.parse())
|
||||
.transpose()?;
|
||||
let api = api.or(Some("0.0.0.0:4028".parse()?));
|
||||
let servers = app::start(Arc::clone(&status), api, web_listen()?)?;
|
||||
let (api_address, web_address) = servers.addresses();
|
||||
if let Some(address) = api_address {
|
||||
println!("management API on {address}");
|
||||
}
|
||||
if let Some(address) = web_address {
|
||||
println!("web UI on http://{address}");
|
||||
}
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_secs(3600));
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut args = std::env::args().skip(1);
|
||||
match args.next().as_deref() {
|
||||
@@ -316,6 +348,12 @@ fn main() {
|
||||
}
|
||||
}
|
||||
Some("--version") => println!("alkane-os {}", env!("CARGO_PKG_VERSION")),
|
||||
Some("--serve") => {
|
||||
if let Err(error) = serve_only() {
|
||||
eprintln!("serve failed: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Some("--boot") => {
|
||||
if let Err(error) = boot_hal(args) {
|
||||
eprintln!("boot failed: {error}");
|
||||
|
||||
@@ -0,0 +1,736 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! On-box web UI: navigation, pages, and the editable dashboard document.
|
||||
//!
|
||||
//! The shape follows the Warden/FLARE console: a fixed sidebar of groups and
|
||||
//! items, hash-routed pages, and dashboards that are a JSON document an operator
|
||||
//! edits in place. The document is stored on the box, has a default template per
|
||||
//! deck, and is capped server-side so a bad save cannot grow without bound.
|
||||
//!
|
||||
//! The JSON API remains the interface of record: every value the pages show is
|
||||
//! also available at an `/api/...` route, and the page never becomes the only
|
||||
//! way to see or change the machine.
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// Blocks a dashboard may hold. Docker rows count too, so a tidy layout cannot
|
||||
/// cost an operator a widget.
|
||||
pub const BLOCK_CAP: usize = 32;
|
||||
/// Characters allowed in a dashboard name.
|
||||
pub const NAME_MAX: usize = 120;
|
||||
|
||||
/// One navigable destination.
|
||||
pub struct Item {
|
||||
pub path: &'static str,
|
||||
pub label: &'static str,
|
||||
}
|
||||
|
||||
/// A sidebar group.
|
||||
pub struct Group {
|
||||
pub label: &'static str,
|
||||
pub items: &'static [Item],
|
||||
}
|
||||
|
||||
const DASHBOARD: [Item; 1] = [Item {
|
||||
path: "/",
|
||||
label: "Dashboard",
|
||||
}];
|
||||
const MINING: [Item; 4] = [
|
||||
Item {
|
||||
path: "/mining",
|
||||
label: "Overview",
|
||||
},
|
||||
Item {
|
||||
path: "/mining/hashboards",
|
||||
label: "Hashboards",
|
||||
},
|
||||
Item {
|
||||
path: "/mining/power",
|
||||
label: "Power Supply",
|
||||
},
|
||||
Item {
|
||||
path: "/mining/fans",
|
||||
label: "Fans",
|
||||
},
|
||||
];
|
||||
const SETTINGS: [Item; 8] = [
|
||||
Item {
|
||||
path: "/settings/system",
|
||||
label: "System",
|
||||
},
|
||||
Item {
|
||||
path: "/settings/drivers",
|
||||
label: "Drivers",
|
||||
},
|
||||
Item {
|
||||
path: "/settings/security",
|
||||
label: "Security",
|
||||
},
|
||||
Item {
|
||||
path: "/settings/services",
|
||||
label: "Services",
|
||||
},
|
||||
Item {
|
||||
path: "/settings/monitor",
|
||||
label: "Monitor",
|
||||
},
|
||||
Item {
|
||||
path: "/settings/logs",
|
||||
label: "Logs",
|
||||
},
|
||||
Item {
|
||||
path: "/settings/files",
|
||||
label: "Files",
|
||||
},
|
||||
Item {
|
||||
path: "/settings/terminal",
|
||||
label: "Terminal",
|
||||
},
|
||||
];
|
||||
|
||||
pub const NAV: [Group; 3] = [
|
||||
Group {
|
||||
label: "Overview",
|
||||
items: &DASHBOARD,
|
||||
},
|
||||
Group {
|
||||
label: "Mining",
|
||||
items: &MINING,
|
||||
},
|
||||
Group {
|
||||
label: "Settings",
|
||||
items: &SETTINGS,
|
||||
},
|
||||
];
|
||||
|
||||
/// The dashboard a deck starts with. Every deck has one, so a fresh box is never
|
||||
/// an empty page.
|
||||
pub fn default_deck(deck: &str) -> Value {
|
||||
match deck {
|
||||
"overview" => json!({
|
||||
"version": 1,
|
||||
"name": "Mining overview",
|
||||
"blocks": [
|
||||
{"id": "status", "kind": "status", "span": 1, "title": "State", "source": "status"},
|
||||
{"id": "accepted", "kind": "metric", "span": 1, "title": "Accepted", "source": "accepted", "unit": "shares"},
|
||||
{"id": "rejected", "kind": "metric", "span": 1, "title": "Rejected", "source": "rejected", "unit": "shares"},
|
||||
{"id": "elapsed", "kind": "metric", "span": 1, "title": "Uptime", "source": "elapsed", "unit": "s"},
|
||||
{"id": "chains", "kind": "metric", "span": 1, "title": "Active chains", "source": "active_chains", "unit": ""},
|
||||
{"id": "frequency", "kind": "metric", "span": 1, "title": "Frequency", "source": "frequency", "unit": "MHz"},
|
||||
{"id": "voltage", "kind": "metric", "span": 1, "title": "Voltage", "source": "voltage", "unit": "mV"},
|
||||
{"id": "target", "kind": "metric", "span": 1, "title": "Target", "source": "target", "unit": ""},
|
||||
{"id": "chains_table", "kind": "table", "span": 4, "title": "Hashboards", "source": "chains"}
|
||||
]
|
||||
}),
|
||||
_ => json!({
|
||||
"version": 1,
|
||||
"name": "Dashboard",
|
||||
"blocks": [
|
||||
{"id": "status", "kind": "status", "span": 2, "title": "Miner", "source": "status"},
|
||||
{"id": "accepted", "kind": "metric", "span": 1, "title": "Accepted", "source": "accepted", "unit": "shares"},
|
||||
{"id": "rejected", "kind": "metric", "span": 1, "title": "Rejected", "source": "rejected", "unit": "shares"},
|
||||
{"id": "hardware", "kind": "kv", "span": 2, "title": "Hardware", "source": "hardware"},
|
||||
{"id": "fans", "kind": "table", "span": 2, "title": "Fan map", "source": "fans"}
|
||||
]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate a dashboard document the client wants to store.
|
||||
///
|
||||
/// Returns the parsed document, or a sentence naming the rule that failed. The
|
||||
/// rules are the same ones the page enforces, so a save that the UI allowed is
|
||||
/// never rejected here for a reason the operator cannot see.
|
||||
pub fn validate_deck(text: &str) -> Result<Value, String> {
|
||||
let doc: Value =
|
||||
serde_json::from_str(text).map_err(|_| "document is not valid JSON".to_string())?;
|
||||
let object = doc.as_object().ok_or("document must be an object")?;
|
||||
let version = object
|
||||
.get("version")
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or("version must be a number")?;
|
||||
if version != 1 {
|
||||
return Err(format!("unsupported version {version}"));
|
||||
}
|
||||
if let Some(name) = object.get("name") {
|
||||
let name = name.as_str().ok_or("name must be a string")?;
|
||||
if name.chars().count() > NAME_MAX {
|
||||
return Err(format!("name is longer than {NAME_MAX} characters"));
|
||||
}
|
||||
}
|
||||
let blocks = object
|
||||
.get("blocks")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or("blocks must be a list")?;
|
||||
if blocks.len() > BLOCK_CAP {
|
||||
return Err(format!("more than {BLOCK_CAP} blocks"));
|
||||
}
|
||||
for block in blocks {
|
||||
let block = block.as_object().ok_or("each block must be an object")?;
|
||||
let id = block
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or("block id must be a string")?;
|
||||
if id.is_empty() || id.len() > 64 {
|
||||
return Err("block id must be 1..=64 characters".to_string());
|
||||
}
|
||||
let kind = block
|
||||
.get("kind")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or("block kind must be a string")?;
|
||||
if !["metric", "status", "kv", "table", "text"].contains(&kind) {
|
||||
return Err(format!("unknown block kind {kind}"));
|
||||
}
|
||||
let span = block.get("span").and_then(Value::as_u64).unwrap_or(1);
|
||||
if !(1..=4).contains(&span) {
|
||||
return Err("block span must be 1..=4".to_string());
|
||||
}
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// Render one page inside the shell.
|
||||
///
|
||||
/// The rail follows the FLARE/Warden console: a 232px navy column with a 44px
|
||||
/// head, one native `<details>` per group so the tree opens and closes with no
|
||||
/// script, and the current page marked with `aria-current` rather than a class
|
||||
/// alone. Below 901px it slides off-canvas and comes back as a `:target`
|
||||
/// fragment, which is the one disclosure a locked-down page can still use.
|
||||
pub fn page(active: &str, title: &str, body: &str) -> String {
|
||||
format!(
|
||||
"<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\">\
|
||||
<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
|
||||
<title>{title} - Alkane</title><style>{CSS}</style></head>\
|
||||
<body class=\"shell\"><aside class=\"rail\" id=\"rail\">{rail_head}{nav}</aside><div class=\"rail-backdrop\" id=\"rail-backdrop\"></div>\
|
||||
<main class=\"content\"><header class=\"appbar\">\
|
||||
<a class=\"appbar__menu\" href=\"#rail\" aria-label=\"Open menu\">Menu</a>\
|
||||
<h1 class=\"page-title\">{title}</h1><span id=\"live\" class=\"pill\">connecting</span></header>\
|
||||
<div class=\"frame\">{body}</div></main>\
|
||||
<script>{JS}</script></body></html>",
|
||||
title = escape(title),
|
||||
rail_head = rail_head(),
|
||||
nav = sidebar(active),
|
||||
)
|
||||
}
|
||||
|
||||
fn rail_head() -> String {
|
||||
"<div class=\"rail__head\"><span class=\"rail__brand\">Alkane</span>\
|
||||
<button class=\"rail__toggle\" type=\"button\" aria-label=\"Collapse sidebar\" title=\"Collapse sidebar\">☰</button>\
|
||||
<a class=\"rail__close\" href=\"#\" aria-label=\"Close menu\" title=\"Close menu\">✕</a></div>"
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// An 18px stroke icon for a destination, matching the rail's icon column.
|
||||
fn icon(path: &str) -> &'static str {
|
||||
let body = match path {
|
||||
"/" => "<rect x=\"3\" y=\"3\" width=\"7\" height=\"7\" rx=\"1\"/><rect x=\"14\" y=\"3\" width=\"7\" height=\"7\" rx=\"1\"/><rect x=\"3\" y=\"14\" width=\"7\" height=\"7\" rx=\"1\"/><rect x=\"14\" y=\"14\" width=\"7\" height=\"7\" rx=\"1\"/>",
|
||||
"/mining" => "<path d=\"M4 20V10M10 20V4M16 20v-7M22 20H2\"/>",
|
||||
"/mining/hashboards" => "<rect x=\"5\" y=\"5\" width=\"14\" height=\"14\" rx=\"2\"/><path d=\"M9 2v3M15 2v3M9 19v3M15 19v3M2 9h3M2 15h3M19 9h3M19 15h3\"/>",
|
||||
"/mining/power" => "<path d=\"M13 2 4 14h7l-1 8 9-12h-7z\"/>",
|
||||
"/mining/fans" => "<circle cx=\"12\" cy=\"12\" r=\"2\"/><path d=\"M12 10c0-4 1-7 4-7 2 0 3 2 3 4 0 3-3 5-7 5M14 12c4 0 7 1 7 4 0 2-2 3-4 3-3 0-5-3-5-7M12 14c0 4-1 7-4 7-2 0-3-2-3-4 0-3 3-5 7-5M10 12c-4 0-7-1-7-4 0-2 2-3 4-3 3 0 5 3 5 7\"/>",
|
||||
"/settings/system" => "<rect x=\"3\" y=\"4\" width=\"18\" height=\"6\" rx=\"1\"/><rect x=\"3\" y=\"14\" width=\"18\" height=\"6\" rx=\"1\"/><path d=\"M7 7h.01M7 17h.01\"/>",
|
||||
"/settings/drivers" => "<rect x=\"4\" y=\"4\" width=\"16\" height=\"16\" rx=\"2\"/><path d=\"M9 9h6v6H9z\"/>",
|
||||
"/settings/security" => "<rect x=\"4\" y=\"10\" width=\"16\" height=\"10\" rx=\"2\"/><path d=\"M8 10V7a4 4 0 0 1 8 0v3\"/>",
|
||||
"/settings/services" => "<circle cx=\"12\" cy=\"12\" r=\"9\"/><path d=\"M10 8l6 4-6 4z\"/>",
|
||||
"/settings/monitor" => "<path d=\"M2 12h4l3-8 4 16 3-8h6\"/>",
|
||||
"/settings/logs" => "<path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\"/><path d=\"M14 2v6h6M8 13h8M8 17h5\"/>",
|
||||
"/settings/files" => "<path d=\"M3 7a2 2 0 0 1 2-2h5l2 2h7a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z\"/>",
|
||||
"/settings/terminal" => "<rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\"/><path d=\"M7 9l3 3-3 3M13 15h4\"/>",
|
||||
_ => "<circle cx=\"12\" cy=\"12\" r=\"9\"/>",
|
||||
};
|
||||
// The strings above are static markup, never user input.
|
||||
let html = format!(
|
||||
"<svg class=\"rail__icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" \
|
||||
stroke-width=\"1.7\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">{body}</svg>"
|
||||
);
|
||||
Box::leak(html.into_boxed_str())
|
||||
}
|
||||
|
||||
fn group_icon_svg(label: &str) -> &'static str {
|
||||
let body = match label {
|
||||
"Mining" => "<rect x=\"5\" y=\"5\" width=\"14\" height=\"14\" rx=\"2\"/><path d=\"M9 2v3M15 2v3M9 19v3M15 19v3M2 9h3M2 15h3M19 9h3M19 15h3\"/>",
|
||||
"Settings" => "<circle cx=\"12\" cy=\"12\" r=\"3\"/><path d=\"M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.9-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.9.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.9 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1A1.7 1.7 0 0 0 4.6 9a1.7 1.7 0 0 0-.3-1.9l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.9.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.9-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.9V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z\"/>",
|
||||
_ => "",
|
||||
};
|
||||
if body.is_empty() {
|
||||
return "";
|
||||
}
|
||||
let html = format!(
|
||||
"<svg class=\"rail__icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" \
|
||||
stroke-width=\"1.7\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">{body}</svg>"
|
||||
);
|
||||
Box::leak(html.into_boxed_str())
|
||||
}
|
||||
|
||||
fn sidebar(active: &str) -> String {
|
||||
let mut out = String::from("<nav class=\"rail__nav\">");
|
||||
let mut first = true;
|
||||
for group in NAV.iter() {
|
||||
// A one-item group is a plain link, exactly as the FLARE rail renders
|
||||
// Dashboard: a disclosure around a single leaf is a control that only
|
||||
// hides the thing it names.
|
||||
if group.items.len() == 1 {
|
||||
let item = &group.items[0];
|
||||
out.push_str(&rail_link(item, active, "rail__link"));
|
||||
} else {
|
||||
let open = group.items.iter().any(|item| item.path == active);
|
||||
out.push_str(&format!(
|
||||
"<details class=\"tree\"{open}>\
|
||||
<summary class=\"rail__link tree__summary\">{icon}<span class=\"rail__label\">{label}</span><span class=\"rail__chevron\" aria-hidden=\"true\"></span></summary>\
|
||||
<ul class=\"tree__list\">",
|
||||
open = if open { " open" } else { "" },
|
||||
label = escape(group.label),
|
||||
icon = group_icon_svg(group.label),
|
||||
));
|
||||
for item in group.items {
|
||||
out.push_str(&rail_link(item, active, "rail__link tree__leaf"));
|
||||
}
|
||||
out.push_str("</ul></details>");
|
||||
}
|
||||
first = false;
|
||||
}
|
||||
let _ = first;
|
||||
out.push_str("</nav>");
|
||||
out
|
||||
}
|
||||
|
||||
fn rail_link(item: &Item, active: &str, class: &str) -> String {
|
||||
let current = if item.path == active {
|
||||
" aria-current=\"page\""
|
||||
} else {
|
||||
""
|
||||
};
|
||||
format!(
|
||||
"<a class=\"{class}\" href=\"#{path}\"{current}>{icon}<span class=\"rail__label\">{label}</span></a>",
|
||||
class = class,
|
||||
path = item.path,
|
||||
label = escape(item.label),
|
||||
icon = icon(item.path),
|
||||
)
|
||||
}
|
||||
|
||||
/// A dashboard page: the editor chrome plus the document the client loads.
|
||||
pub fn dashboard_page(deck: &str, editable: bool) -> String {
|
||||
let deck = escape(deck);
|
||||
format!(
|
||||
"<div class=\"bar\">\
|
||||
<label>Template <select id=\"deck-name\"></select></label>\
|
||||
<button id=\"save\"{disabled}>Save</button>\
|
||||
<button id=\"reset\"{disabled}>Reset to template</button>\
|
||||
<button id=\"add\"{disabled}>Add block</button>\
|
||||
<span id=\"edit-msg\" class=\"muted\"></span></div>\
|
||||
<div id=\"grid\" class=\"grid\" data-deck=\"{deck}\" data-editable=\"{editable}\"></div>",
|
||||
disabled = if editable { "" } else { " disabled" },
|
||||
editable = if editable { "1" } else { "0" },
|
||||
)
|
||||
}
|
||||
|
||||
/// Escape text for HTML. Every user-visible string goes through this.
|
||||
pub fn escape(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
for ch in text.chars() {
|
||||
match ch {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A definition-list page for key/value data (settings pages).
|
||||
pub fn kv_page(rows: &[(&str, String)]) -> String {
|
||||
let mut out = String::from("<table class=\"kv\"><tbody>");
|
||||
for (key, value) in rows {
|
||||
out.push_str(&format!(
|
||||
"<tr><th>{}</th><td>{}</td></tr>",
|
||||
escape(key),
|
||||
escape(value)
|
||||
));
|
||||
}
|
||||
out.push_str("</tbody></table>");
|
||||
out
|
||||
}
|
||||
|
||||
/// Several titled sections in one page: the settings pages' shape in the
|
||||
/// Warden console, where each group (Identity, Network, ...) is its own block.
|
||||
pub fn sections_page(sections: &[(&str, String)]) -> String {
|
||||
let mut out = String::new();
|
||||
for (title, body) in sections {
|
||||
out.push_str(&format!(
|
||||
"<section class=\"section\"><h2 class=\"section__title\">{}</h2>{}</section>",
|
||||
escape(title),
|
||||
body
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A table page with a header row.
|
||||
pub fn table_page(headers: &[&str], rows: &[Vec<String>]) -> String {
|
||||
let mut out = String::from("<table><thead><tr>");
|
||||
for header in headers {
|
||||
out.push_str(&format!("<th>{}</th>", escape(header)));
|
||||
}
|
||||
out.push_str("</tr></thead><tbody>");
|
||||
for row in rows {
|
||||
out.push_str("<tr>");
|
||||
for cell in row {
|
||||
out.push_str(&format!("<td>{}</td>", escape(cell)));
|
||||
}
|
||||
out.push_str("</tr>");
|
||||
}
|
||||
if rows.is_empty() {
|
||||
out.push_str(&format!(
|
||||
"<tr><td colspan=\"{}\" class=\"muted\">nothing to show</td></tr>",
|
||||
headers.len().max(1)
|
||||
));
|
||||
}
|
||||
out.push_str("</tbody></table>");
|
||||
out
|
||||
}
|
||||
|
||||
const CSS: &str = r#"
|
||||
:root{
|
||||
color-scheme:dark;
|
||||
/* FLARE tokens: navy scale, cyan action, the same steps portal.css uses. */
|
||||
--navy-900:#070D1D; --navy-800:#0B1020; --navy-700:#192858; --navy-600:#1E4E90;
|
||||
--cyan-400:#3ABCF8; --cyan-500:#31A2D6; --orange-500:#F26522;
|
||||
--text:#FFFFFF; --text-muted:#BABABA;
|
||||
--border:#192858;
|
||||
--space-1:4px; --space-2:8px; --space-3:12px; --space-4:16px; --space-6:24px;
|
||||
--font-display:'Creato Display','Sora','Segoe UI','Selawik',system-ui,-apple-system,sans-serif;
|
||||
--font-body:'Segoe UI','Selawik',system-ui,-apple-system,sans-serif;
|
||||
--text-xs:12px; --text-sm:14px; --text-base:16px;
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
body.shell{margin:0;display:flex;min-height:100vh;background:var(--navy-900);color:var(--text);
|
||||
font:var(--text-sm)/1.45 var(--font-body)}
|
||||
a{color:var(--cyan-400);text-decoration:none}
|
||||
:focus-visible{outline:2px solid var(--cyan-400);outline-offset:2px}
|
||||
|
||||
/* --- rail: the Warden console's sidebar ------------------------------- */
|
||||
.rail{flex:none;width:232px;background:var(--navy-700);border-right:1px solid #1E2A4E;
|
||||
display:flex;flex-direction:column;position:sticky;top:0;height:100vh;overflow-y:auto;
|
||||
overscroll-behavior:contain}
|
||||
.rail__head{display:flex;align-items:center;gap:var(--space-2);min-height:44px;
|
||||
padding:0 var(--space-3);border-bottom:1px solid #1E2A4E}
|
||||
.rail__brand{font-family:var(--font-display);font-weight:700;font-size:var(--text-base);
|
||||
letter-spacing:.02em}
|
||||
.rail__nav{padding:var(--space-2) 0;display:flex;flex-direction:column}
|
||||
.rail__link{display:flex;align-items:center;gap:var(--space-3);min-height:36px;
|
||||
padding:var(--space-2) var(--space-4);color:#E6ECF5;font-size:var(--text-sm);font-weight:600;
|
||||
border-left:2px solid transparent;min-width:0}
|
||||
.rail__link:hover{background:rgba(255,255,255,.06)}
|
||||
.rail__link[aria-current='page']{border-left-color:var(--cyan-400);color:var(--cyan-400);
|
||||
background:rgba(255,255,255,.06)}
|
||||
.tree>summary{list-style:none;cursor:pointer}
|
||||
.tree>summary::-webkit-details-marker{display:none}
|
||||
.rail__chevron{margin-left:auto;width:0;height:0;border-left:4px solid transparent;
|
||||
border-right:4px solid transparent;border-top:5px solid #9AA5BB}
|
||||
.tree[open]>summary .rail__chevron{transform:rotate(180deg)}
|
||||
.tree__list{list-style:none;margin:0;padding:0}
|
||||
.tree__leaf{font-weight:400;color:#9AA5BB;min-height:32px;
|
||||
padding-left:calc(var(--space-4) + var(--space-3))}
|
||||
.tree__leaf:hover{color:#E6ECF5}
|
||||
.tree__leaf[aria-current='page']{color:var(--cyan-400);font-weight:600}
|
||||
.rail a:focus-visible,.rail summary:focus-visible{outline-offset:-2px}
|
||||
.rail__icon{width:18px;height:18px;flex:none}
|
||||
.rail__label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.rail__toggle{margin-left:auto;background:transparent;border:0;color:#9AA5BB;cursor:pointer;
|
||||
padding:4px;font-size:14px;line-height:1}
|
||||
.rail__toggle:hover{color:#E6ECF5}
|
||||
|
||||
/* Collapsed: icons only, and only where the rail is docked. Labels are clipped
|
||||
rather than removed so they keep their accessible name. */
|
||||
@media (min-width:901px){
|
||||
.shell--collapsed .rail{width:41px}
|
||||
.shell--collapsed .rail__label,
|
||||
.shell--collapsed .rail__brand{position:absolute;width:1px;height:1px;overflow:hidden;
|
||||
clip-path:inset(50%);white-space:nowrap}
|
||||
.shell--collapsed .tree__list,
|
||||
.shell--collapsed .rail__chevron{display:none}
|
||||
.shell--collapsed .rail__link{justify-content:center;padding-left:0;padding-right:2px}
|
||||
.shell--collapsed .rail__head{justify-content:center;padding-inline:0}
|
||||
}
|
||||
|
||||
/* --- content column ---------------------------------------------------- */
|
||||
.content{flex:1;min-width:0;display:flex;flex-direction:column}
|
||||
.appbar{display:flex;align-items:center;gap:var(--space-4);min-height:44px;
|
||||
padding:0 var(--space-6);border-bottom:1px solid var(--border);
|
||||
position:sticky;top:0;z-index:40;background:var(--navy-900)}
|
||||
.page-title{font-family:var(--font-display);font-size:22px;font-weight:700;line-height:1.1;
|
||||
margin:0;letter-spacing:-.01em}
|
||||
.appbar__menu{display:none;font-size:var(--text-sm);color:var(--cyan-400)}
|
||||
.pill{border-radius:0;margin-left:auto;font-size:var(--text-xs);padding:3px 9px;
|
||||
background:var(--navy-800);color:var(--text-muted);border:1px solid var(--border)}
|
||||
.pill.ok{color:#7EE787;border-color:#1F4D2C}
|
||||
.pill.bad{color:#FF9B9B;border-color:#552323}
|
||||
.frame{padding:var(--space-6);display:flex;flex-direction:column;gap:var(--space-6)}
|
||||
|
||||
/* --- blocks ------------------------------------------------------------ */
|
||||
.bar{display:flex;gap:var(--space-3);align-items:center;flex-wrap:wrap}
|
||||
h2,.card h2{font-family:var(--font-display);font-size:11px;font-weight:600;line-height:1.15;
|
||||
text-transform:uppercase;letter-spacing:2px;color:var(--text-muted);margin:0 0 var(--space-2)}
|
||||
button{border-radius:0;font:inherit;cursor:pointer;padding:7px 12px;
|
||||
background:var(--navy-700);color:var(--text);border:1px solid #1E2A4E}
|
||||
button:hover:not(:disabled){background:var(--navy-600)}
|
||||
button:disabled{opacity:.4;cursor:default}
|
||||
select,input[type=text]{border-radius:0;font:inherit;color:var(--text);background:var(--navy-900);
|
||||
border:1px solid #1E2A4E;padding:6px 8px}
|
||||
input[type=text]{min-width:320px;padding:8px 10px}
|
||||
.grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:var(--space-4)}
|
||||
.card{background:var(--navy-800);border:1px solid var(--border);border-radius:0;
|
||||
padding:var(--space-4);min-height:96px}
|
||||
.card.drag{outline:1px dashed var(--cyan-400);outline-offset:2px}
|
||||
.card .big{font-family:var(--font-display);font-size:28px;font-weight:700;letter-spacing:-.5px}
|
||||
.card .unit{font-size:var(--text-xs);color:var(--text-muted);margin-left:var(--space-1)}
|
||||
.span2{grid-column:span 2}.span3{grid-column:span 3}.span4{grid-column:span 4}
|
||||
table{width:100%;border-collapse:collapse;font-size:var(--text-sm)}
|
||||
th,td{text-align:left;padding:8px 10px;border-bottom:1px solid #14203C}
|
||||
th{font-family:var(--font-display);font-size:11px;font-weight:600;text-transform:uppercase;
|
||||
letter-spacing:2px;color:var(--text-muted)}
|
||||
table.kv th{width:220px;color:var(--text-muted);font-weight:600;text-transform:none;
|
||||
letter-spacing:0;font-family:var(--font-body);font-size:var(--text-sm)}
|
||||
.muted{color:var(--text-muted)}
|
||||
.section{display:flex;flex-direction:column;gap:var(--space-2)}
|
||||
.section__title{font-family:var(--font-display);font-size:11px;font-weight:600;line-height:1.15;
|
||||
text-transform:uppercase;letter-spacing:2px;color:var(--text-muted);margin:0;
|
||||
padding-bottom:var(--space-2);border-bottom:1px solid var(--border)}
|
||||
pre{background:var(--navy-900);border:1px solid var(--border);border-radius:0;
|
||||
padding:var(--space-4);overflow:auto;max-height:60vh;
|
||||
font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}
|
||||
|
||||
/* Off-canvas below 901px, reopened by the fragment so it works without a
|
||||
script, exactly as portal.css does it. */
|
||||
.rail__close{display:none;margin-left:var(--space-2);background:transparent;border:0;
|
||||
color:#9AA5BB;font-size:16px;line-height:1;padding:6px;cursor:pointer}
|
||||
.rail__close:hover{color:#E6ECF5}
|
||||
.rail-backdrop{display:none}
|
||||
|
||||
@media (max-width:900px){
|
||||
.shell{display:block}
|
||||
/* Full-screen drawer, as the design's mobile menu: page background, its own
|
||||
top bar with the brand and a close, rows split by 1px dividers. */
|
||||
.rail{position:fixed;inset:0;width:100%;max-width:none;transform:translateX(-100%);
|
||||
z-index:60;background:var(--navy-900);border-right:0}
|
||||
.rail:target{transform:none}
|
||||
body.drawer-open .rail{transform:none}
|
||||
body.drawer-open{overflow:hidden}
|
||||
body.drawer-open .rail-backdrop{display:block;position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:55}
|
||||
.rail__head{min-height:56px;padding:0 var(--space-4);border-bottom:1px solid var(--border)}
|
||||
.rail__brand{font-size:18px}
|
||||
.rail__toggle{display:none}
|
||||
.rail__close{display:inline-flex}
|
||||
.rail__link{padding:var(--space-4);border-bottom:1px solid var(--border);border-left:0}
|
||||
.rail__link[aria-current='page']{border-left:0;background:rgba(255,255,255,.06)}
|
||||
.tree__leaf{padding:var(--space-4) var(--space-4) var(--space-4) calc(var(--space-4) * 2);min-height:48px}
|
||||
.appbar__menu{display:inline-flex}
|
||||
.appbar{padding:0 var(--space-4)}
|
||||
.frame{padding:var(--space-4)}
|
||||
.grid{grid-template-columns:1fr}
|
||||
.span2,.span3,.span4{grid-column:span 1}
|
||||
}
|
||||
"#;
|
||||
|
||||
const JS: &str = r#"
|
||||
(function(){
|
||||
"use strict";
|
||||
function $(id){return document.getElementById(id)}
|
||||
function esc(s){return String(s).replace(/[&<>"']/g,function(c){return {'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]})}
|
||||
function route(){var p=location.hash.slice(1)||"/";return p}
|
||||
function go(){location.hash=route()}
|
||||
// Live status pill: the page is a convenience over the JSON API.
|
||||
function poll(){fetch("/api/summary").then(function(r){return r.json()}).then(function(d){
|
||||
var el=$("live"); if(!el)return; var m=(d.miner||d); el.textContent=(m.state||"up"); el.className="pill ok";
|
||||
}).catch(function(){var el=$("live"); if(el){el.textContent="offline"; el.className="pill bad"}})}
|
||||
setInterval(poll,5000); poll();
|
||||
|
||||
// Mobile drawer. The rail is full-screen below 901px; Menu opens it and the
|
||||
// close control, the backdrop or Escape puts it away. Without a script the
|
||||
// :target fragment still opens it, which is why the Menu link is an anchor.
|
||||
(function(){
|
||||
var body=document.body;
|
||||
var menu=document.querySelector(".appbar__menu");
|
||||
var close=document.querySelector(".rail__close");
|
||||
var backdrop=document.getElementById("rail-backdrop");
|
||||
function open(){body.classList.add("drawer-open")}
|
||||
function shut(){body.classList.remove("drawer-open")}
|
||||
if(menu)menu.addEventListener("click",function(e){e.preventDefault();open()});
|
||||
if(close)close.addEventListener("click",function(e){e.preventDefault();shut()});
|
||||
if(backdrop)backdrop.addEventListener("click",shut);
|
||||
document.addEventListener("keydown",function(e){if(e.key==="Escape")shut()});
|
||||
document.querySelectorAll(".rail__link").forEach(function(link){
|
||||
link.addEventListener("click",function(){shut()});
|
||||
});
|
||||
})();
|
||||
|
||||
// Rail collapse. The state is remembered so a reload keeps the operator's
|
||||
// choice; the button is the only control that needs a script.
|
||||
(function(){
|
||||
var key="alkane.rail.collapsed";
|
||||
try{if(localStorage.getItem(key)==="1")document.body.classList.add("shell--collapsed")}catch(e){}
|
||||
var toggle=document.querySelector(".rail__toggle");
|
||||
if(toggle)toggle.addEventListener("click",function(){
|
||||
var on=document.body.classList.toggle("shell--collapsed");
|
||||
try{localStorage.setItem(key,on?"1":"0")}catch(e){}
|
||||
});
|
||||
})();
|
||||
|
||||
var grid=$("grid");
|
||||
if(grid){
|
||||
var deck=grid.dataset.deck, editable=grid.dataset.editable==="1", doc=null, dragId=null;
|
||||
var METRICS={hashrate:["TH/s",1],power_w:["W",1],chains:["",0],chip_temp_c:["C",0],fans:["",0]};
|
||||
function render(){
|
||||
grid.innerHTML="";
|
||||
(doc.blocks||[]).forEach(function(b){
|
||||
var card=document.createElement("div");
|
||||
card.className="card span"+(b.span||1);
|
||||
card.draggable=editable;
|
||||
card.addEventListener("dragstart",function(){dragId=b.id;card.classList.add("drag")});
|
||||
card.addEventListener("dragend",function(){card.classList.remove("drag")});
|
||||
card.addEventListener("dragover",function(e){e.preventDefault()});
|
||||
card.addEventListener("drop",function(e){e.preventDefault(); if(!dragId||dragId===b.id)return;
|
||||
var from=doc.blocks.findIndex(function(x){return x.id===dragId});
|
||||
var to=doc.blocks.findIndex(function(x){return x.id===b.id});
|
||||
if(from<0||to<0)return; var moved=doc.blocks.splice(from,1)[0]; doc.blocks.splice(to,0,moved); render(); msg("unsaved changes")});
|
||||
var h=document.createElement("h2"); h.textContent=b.title||b.id; card.appendChild(h);
|
||||
if(b.kind==="metric"||b.kind==="status"){
|
||||
var big=document.createElement("div"); big.className="big"; big.textContent="--";
|
||||
big.dataset.source=b.source||""; card.appendChild(big);
|
||||
if(b.unit){var u=document.createElement("span"); u.className="unit"; u.textContent=b.unit; card.appendChild(u)}
|
||||
} else if(b.kind==="table"){
|
||||
var t=document.createElement("table");
|
||||
t.dataset[b.source==="fans"?"fans":"table"]=b.source||"";
|
||||
t.innerHTML="<tbody><tr><td class='muted'>loading</td></tr></tbody>";
|
||||
card.appendChild(t);
|
||||
} else {
|
||||
var p=document.createElement("div"); p.className="muted"; p.dataset.kv=b.source||""; p.textContent="loading"; card.appendChild(p);
|
||||
}
|
||||
grid.appendChild(card);
|
||||
});
|
||||
}
|
||||
function msg(text){var el=$("edit-msg"); if(el)el.textContent=text}
|
||||
function fill(){
|
||||
var hw=null, sm=null;
|
||||
function paint(){
|
||||
if(!hw||!sm)return;
|
||||
var s=(sm.SUMMARY||[{}])[0];
|
||||
var src={
|
||||
status:(s.Status||"unknown"),
|
||||
accepted:(s.Accepted||0),
|
||||
rejected:(s.Rejected||0),
|
||||
elapsed:(s.Elapsed||0),
|
||||
active_chains:(hw.active_chains||[]).length,
|
||||
frequency:(hw.frequency_mhz||0),
|
||||
voltage:((hw.operating_point||{}).voltage_mv||0),
|
||||
target:(hw.target||"-")
|
||||
};
|
||||
document.querySelectorAll("[data-source]").forEach(function(el){
|
||||
var v=src[el.dataset.source];
|
||||
if(v===undefined||v===null){el.textContent="not reported"; el.classList.add("muted"); return}
|
||||
el.textContent=String(v);
|
||||
});
|
||||
document.querySelectorAll("[data-table]").forEach(function(t){
|
||||
var rows=(hw.chains||[]).map(function(c){return [c.index,c.chip,c.chips_found,JSON.stringify(c.eeprom),c.response_per_mille]});
|
||||
if(!rows.length){t.innerHTML="<tbody><tr><td class='muted'>no chains reported</td></tr></tbody>";return}
|
||||
t.innerHTML="<thead><tr><th>#</th><th>chip</th><th>chips</th><th>eeprom</th><th>response</th></tr></thead><tbody>"+
|
||||
rows.map(function(r){return "<tr>"+r.map(function(c){return "<td>"+esc(c)+"</td>"}).join("")+"</tr>"}).join("")+"</tbody>";
|
||||
});
|
||||
document.querySelectorAll("[data-kv]").forEach(function(el){
|
||||
var rows=[["profile",hw.profile||"-"],["chip",hw.chip||"-"],["psu",hw.psu||"-"],["target",hw.target||"-"],["stopped",hw.stopped?hw.stopped:"no"]];
|
||||
el.innerHTML=rows.map(function(r){return "<div><span class='muted'>"+esc(r[0])+"</span> "+esc(r[1])+"</div>"}).join("");
|
||||
});
|
||||
document.querySelectorAll("[data-fans]").forEach(function(t){
|
||||
var rows=(hw.fan_zones||[]).map(function(z){return [z.fan,(z.zones||[]).join(", ")]});
|
||||
if(!rows.length){t.innerHTML="<tbody><tr><td class='muted'>not mapped yet</td></tr></tbody>";return}
|
||||
t.innerHTML="<thead><tr><th>fan</th><th>zones</th></tr></thead><tbody>"+
|
||||
rows.map(function(r){return "<tr><td>"+esc(r[0])+"</td><td>"+esc(r[1])+"</td></tr>"}).join("")+"</tbody>";
|
||||
});
|
||||
}
|
||||
fetch("/api/hardware").then(function(r){return r.json()}).then(function(h){hw=h;paint()}).catch(function(){msg("hardware unavailable")});
|
||||
fetch("/api/summary").then(function(r){return r.json()}).then(function(s){sm=s;paint()}).catch(function(){});
|
||||
}
|
||||
fetch("/api/dashboard?deck="+encodeURIComponent(deck)).then(function(r){return r.json()}).then(function(d){doc=d;render();fill()});
|
||||
if(editable){
|
||||
$("save").onclick=function(){fetch("/api/dashboard?deck="+encodeURIComponent(deck),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(doc)}).then(function(r){if(r.ok){msg("saved")}else{r.text().then(msg)}})};
|
||||
$("reset").onclick=function(){fetch("/api/dashboard?deck="+encodeURIComponent(deck)+"&reset=1",{method:"PUT",headers:{"Content-Type":"application/json"},body:"{}"}).then(function(r){return r.json()}).then(function(d){doc=d;render();fill();msg("template restored")})};
|
||||
$("add").onclick=function(){
|
||||
if(doc.blocks.length>=32){msg("32 blocks is the limit");return}
|
||||
var id="block"+(doc.blocks.length+1);
|
||||
doc.blocks.push({id:id,kind:"metric",span:1,title:"New block",source:"power_w",unit:"W"});render();msg("unsaved changes")};
|
||||
}
|
||||
}
|
||||
})();
|
||||
"#;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_sidebar_item_has_a_page() {
|
||||
for group in NAV.iter() {
|
||||
for item in group.items {
|
||||
assert!(item.path.starts_with('/'), "{} has no path", item.label);
|
||||
assert!(!item.label.is_empty());
|
||||
}
|
||||
}
|
||||
assert_eq!(NAV.iter().map(|g| g.items.len()).sum::<usize>(), 13);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_decks_are_valid() {
|
||||
for deck in ["dashboard", "overview"] {
|
||||
let doc = default_deck(deck);
|
||||
let text = doc.to_string();
|
||||
assert!(validate_deck(&text).is_ok(), "{deck} default rejected");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_block_cap_is_enforced() {
|
||||
let mut blocks = Vec::new();
|
||||
for i in 0..=BLOCK_CAP {
|
||||
blocks.push(json!({"id": format!("b{i}"), "kind": "metric", "span": 1}));
|
||||
}
|
||||
let doc = json!({"version": 1, "blocks": blocks});
|
||||
assert!(validate_deck(&doc.to_string()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_documents_are_rejected_with_a_reason() {
|
||||
assert!(validate_deck("not json").is_err());
|
||||
assert!(validate_deck("{}").is_err());
|
||||
assert!(validate_deck(r#"{"version":2,"blocks":[]}"#).is_err());
|
||||
assert!(
|
||||
validate_deck(r#"{"version":1,"blocks":[{"id":"x","kind":"evil","span":1}]}"#).is_err()
|
||||
);
|
||||
assert!(
|
||||
validate_deck(r#"{"version":1,"blocks":[{"id":"x","kind":"metric","span":9}]}"#)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sidebar_marks_the_active_page_and_opens_its_group() {
|
||||
let html = page("/mining/fans", "Fans", "");
|
||||
assert!(html.contains("href=\"#/mining/fans\" aria-current=\"page\""));
|
||||
// Exactly the group holding the current page is open; the other is not.
|
||||
assert_eq!(html.matches("<details class=\"tree\" open>").count(), 1);
|
||||
assert!(html.contains("Power Supply"));
|
||||
assert!(html.contains("href=\"#/settings/terminal\""));
|
||||
// A one-item group is a plain link, not a disclosure around a leaf.
|
||||
assert!(html.contains("class=\"rail__link\" href=\"#/\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_text_is_escaped() {
|
||||
assert_eq!(escape("<script>"), "<script>");
|
||||
let html = kv_page(&[("note", "<b>x</b>".to_string())]);
|
||||
assert!(!html.contains("<b>x</b>"));
|
||||
assert!(html.contains("<b>"));
|
||||
}
|
||||
}
|
||||
+887
-160
File diff suppressed because it is too large
Load Diff
Vendored
+41
@@ -0,0 +1,41 @@
|
||||
# Third-party sources
|
||||
|
||||
Code we consume that is not on crates.io. Both entries are pinned, and both are
|
||||
vendored rather than fetched so an image build works with no network.
|
||||
|
||||
## flare-ui
|
||||
|
||||
`flare-ui/` is a full checkout of the `flare-ui` tag recorded in
|
||||
`flare-ui/flare-ui.lock` (repo, tag, commit). It is used as path dependencies:
|
||||
|
||||
```
|
||||
flare-ui = { path = "third-party/flare-ui/crates/flare-ui" }
|
||||
wschema = { path = "third-party/flare-ui/crates/wschema" }
|
||||
```
|
||||
|
||||
The whole tree is vendored, not just `crates/`, because the crate embeds assets
|
||||
from `dash-editor/` with `include_str!` and will not compile from a partial
|
||||
archive.
|
||||
|
||||
Updating the pin:
|
||||
|
||||
```
|
||||
git archive <new-tag> | tar -x -C third-party/flare-ui # from a flare-ui checkout
|
||||
cargo vendor vendor # refresh registry deps
|
||||
```
|
||||
|
||||
`vendor/` is a cargo directory source (see `.cargo/config.toml`), so every
|
||||
registry dependency flare-ui needs - `maud`, `sha2`, `typenum`, `digest` and the
|
||||
rest - must be re-vendored or the build fails offline.
|
||||
|
||||
## Size
|
||||
|
||||
`ci/check-ui-size.sh` builds two binaries for armv7 with the same profile: one
|
||||
renders through flare-ui, one renders the same shape with `maud` alone. The
|
||||
difference is the marginal cost. Measured 2026-11-03, release, stripped:
|
||||
|
||||
```
|
||||
ui-baseline 323 KiB
|
||||
ui-spike 771 KiB
|
||||
marginal 448 KiB
|
||||
```
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, next]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ gitea.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: "0"
|
||||
|
||||
jobs:
|
||||
check:
|
||||
name: Format, lint and test
|
||||
runs-on: ci-small
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
# rust-toolchain.toml names one exact version. Install it, then require
|
||||
# the compiler cargo will use to report that same version.
|
||||
- name: Toolchain matches the pin
|
||||
run: |
|
||||
want="$(sed -n 's/^channel *= *"\(.*\)"/\1/p' rust-toolchain.toml)"
|
||||
if command -v rustup >/dev/null 2>&1; then
|
||||
rustup toolchain install "$want" --profile minimal --component clippy --component rustfmt
|
||||
fi
|
||||
got="$(rustc --version | cut -d' ' -f2)"
|
||||
echo "pinned $want, rustc $got"
|
||||
[ "$want" = "$got" ]
|
||||
|
||||
- name: Cache cargo registry
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry/index
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/git/db
|
||||
key: ${{ runner.os }}-cargo-${{ hashFiles('Cargo.lock') }}
|
||||
restore-keys: ${{ runner.os }}-cargo-
|
||||
|
||||
- name: Format
|
||||
run: cargo fmt --check
|
||||
|
||||
- name: Clippy
|
||||
run: cargo clippy --workspace --all-targets --locked -- -D warnings
|
||||
|
||||
- name: Test
|
||||
run: cargo test --workspace --locked
|
||||
|
||||
- name: Crate owners
|
||||
run: scripts/check-owners.sh
|
||||
|
||||
- name: Vendor script self-test
|
||||
run: scripts/vendor-selftest.sh
|
||||
|
||||
# The panel crates must keep building for the device target.
|
||||
- name: Build for the panel
|
||||
run: |
|
||||
if command -v rustup >/dev/null 2>&1; then
|
||||
rustup target add armv7-unknown-linux-musleabihf
|
||||
fi
|
||||
cargo build --locked --target armv7-unknown-linux-musleabihf \
|
||||
-p wschema -p warden-sync -p warden-seal -p wapp-core
|
||||
|
||||
# The imported dashboard editor ships plain static files; its tests
|
||||
# are Node's built-in runner, no install step.
|
||||
- name: Dash editor tests
|
||||
run: |
|
||||
cd dash-editor
|
||||
node --test tests/*.test.mjs
|
||||
|
||||
# The automation flowchart model, same runner as the dash editor.
|
||||
- name: Flow builder tests
|
||||
run: |
|
||||
cd flow-builder
|
||||
node --test tests/*.test.mjs
|
||||
|
||||
- name: UI adapter tests
|
||||
run: node --test crates/flare-ui/tests/js/*.test.js
|
||||
|
||||
browser:
|
||||
name: UI browser tests
|
||||
runs-on: ci-small
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
PLAYWRIGHT_BROWSERS_PATH: ${{ runner.tool_cache }}/flare-ui-playwright
|
||||
defaults:
|
||||
run:
|
||||
working-directory: crates/flare-ui/tests/browser
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
- name: Restore browser cache
|
||||
id: browsers
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: ${{ env.PLAYWRIGHT_BROWSERS_PATH }}
|
||||
key: ${{ runner.os }}-flare-ui-playwright-${{ hashFiles('crates/flare-ui/tests/browser/package-lock.json') }}
|
||||
- name: Install test dependencies
|
||||
run: npm ci --ignore-scripts
|
||||
- name: Install headless browsers
|
||||
run: npx playwright install --with-deps chromium firefox
|
||||
- name: Check UI behavior
|
||||
run: npm test
|
||||
# Pull requests read the cache; only trusted next pushes replace it.
|
||||
- name: Save browser cache
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/next' && steps.browsers.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v6
|
||||
with:
|
||||
path: ${{ env.PLAYWRIGHT_BROWSERS_PATH }}
|
||||
key: ${{ runner.os }}-flare-ui-playwright-${{ hashFiles('crates/flare-ui/tests/browser/package-lock.json') }}
|
||||
@@ -0,0 +1,8 @@
|
||||
/target
|
||||
**/node_modules/
|
||||
*.zip
|
||||
.env
|
||||
|
||||
*.env
|
||||
*.pem
|
||||
*.key
|
||||
+942
@@ -0,0 +1,942 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "adler2"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "aead"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aes"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cpufeatures",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aes-gcm"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
|
||||
dependencies = [
|
||||
"aead",
|
||||
"aes",
|
||||
"cipher",
|
||||
"ctr",
|
||||
"ghash",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anes"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
|
||||
|
||||
[[package]]
|
||||
name = "anstyle"
|
||||
version = "1.0.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cast"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "chacha20"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cpufeatures",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chacha20poly1305"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
|
||||
dependencies = [
|
||||
"aead",
|
||||
"chacha20",
|
||||
"cipher",
|
||||
"poly1305",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ciborium"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
|
||||
dependencies = [
|
||||
"ciborium-io",
|
||||
"ciborium-ll",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ciborium-io"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
|
||||
|
||||
[[package]]
|
||||
name = "ciborium-ll"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
|
||||
dependencies = [
|
||||
"ciborium-io",
|
||||
"half",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.4.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"inout",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"clap_lex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "criterion"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f"
|
||||
dependencies = [
|
||||
"anes",
|
||||
"cast",
|
||||
"ciborium",
|
||||
"clap",
|
||||
"criterion-plot",
|
||||
"is-terminal",
|
||||
"itertools",
|
||||
"num-traits",
|
||||
"once_cell",
|
||||
"oorandom",
|
||||
"regex",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"tinytemplate",
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "criterion-plot"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1"
|
||||
dependencies = [
|
||||
"cast",
|
||||
"itertools",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crunchy"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"rand_core 0.6.4",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctr"
|
||||
version = "0.9.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
|
||||
dependencies = [
|
||||
"cipher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek"
|
||||
version = "4.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"curve25519-dalek-derive",
|
||||
"fiat-crypto",
|
||||
"rustc_version",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek-derive"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519-compact"
|
||||
version = "2.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1454db4f2edb7f0e8fe0c5b375b0c978fc63244cc9f010d160e417eb10139aa8"
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||
|
||||
[[package]]
|
||||
name = "flare-plugin-abi"
|
||||
version = "0.0.1"
|
||||
|
||||
[[package]]
|
||||
name = "flare-ui"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"maud",
|
||||
"serde_json",
|
||||
"wschema",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flate2"
|
||||
version = "1.1.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"miniz_oxide",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"wasi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ghash"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
|
||||
dependencies = [
|
||||
"opaque-debug",
|
||||
"polyval",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "half"
|
||||
version = "2.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"crunchy",
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
|
||||
|
||||
[[package]]
|
||||
name = "hkdf"
|
||||
version = "0.12.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
|
||||
dependencies = [
|
||||
"hmac",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hpke"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f65d16b699dd1a1fa2d851c970b0c971b388eeeb40f744252b8de48860980c8f"
|
||||
dependencies = [
|
||||
"aead",
|
||||
"aes-gcm",
|
||||
"chacha20poly1305",
|
||||
"digest",
|
||||
"generic-array",
|
||||
"hkdf",
|
||||
"hmac",
|
||||
"rand_core 0.9.5",
|
||||
"sha2",
|
||||
"subtle",
|
||||
"x25519-dalek",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is-terminal"
|
||||
version = "0.4.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.10.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.190"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
|
||||
|
||||
[[package]]
|
||||
name = "maud"
|
||||
version = "0.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8156733e27020ea5c684db5beac5d1d611e1272ab17901a49466294b84fc217e"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"maud_macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "maud_macros"
|
||||
version = "0.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7261b00f3952f617899bc012e3dbd56e4f0110a038175929fa5d18e5a19913ca"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"proc-macro2-diagnostics",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "miniz_oxide"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
|
||||
dependencies = [
|
||||
"adler2",
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "oorandom"
|
||||
version = "11.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
|
||||
|
||||
[[package]]
|
||||
name = "opaque-debug"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
|
||||
|
||||
[[package]]
|
||||
name = "poly1305"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
|
||||
dependencies = [
|
||||
"cpufeatures",
|
||||
"opaque-debug",
|
||||
"universal-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "polyval"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"opaque-debug",
|
||||
"universal-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2-diagnostics"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-automata",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
|
||||
dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "same-file"
|
||||
version = "1.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
|
||||
dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinytemplate"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "universal-hash"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "walkdir"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
|
||||
dependencies = [
|
||||
"same-file",
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wapp-core"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"ed25519-compact",
|
||||
"flate2",
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wapp-pack"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"sha2",
|
||||
"wapp-core",
|
||||
"wschema",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "warden-seal"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"hpke",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "warden-sync"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.11.1+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||
|
||||
[[package]]
|
||||
name = "winapi-util"
|
||||
version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wschema"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wschema-cli"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"wschema",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wschema-gen"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"regex",
|
||||
"serde_json",
|
||||
"wschema",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x25519-dalek"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
|
||||
dependencies = [
|
||||
"curve25519-dalek",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.62"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "86502bf56ac7c77571a32e2647bb2a15894565e981fb2a48d7bde2d91c965a9d"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.62"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5457206954b06561e2608c7e19cf58b1926586d999c246eebe4502f7e2039d1a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zeroize"
|
||||
version = "1.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
|
||||
dependencies = [
|
||||
"zeroize_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zeroize_derive"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.0.1"
|
||||
edition = "2021"
|
||||
rust-version = "1.85"
|
||||
license = "MIT"
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 FLARE contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+12
@@ -0,0 +1,12 @@
|
||||
# One line per crate: <path> <lane>. Only the owning lane edits a crate;
|
||||
# other lanes ask it through a note. Only lane LD tags (see docs/vendoring.md).
|
||||
# scripts/check-owners.sh keeps this file and crates/ in step.
|
||||
crates/flare-ui LD
|
||||
crates/flare-plugin-abi LD
|
||||
crates/wschema LB
|
||||
crates/wschema-gen LB
|
||||
crates/wschema-cli LB
|
||||
crates/warden-sync LI
|
||||
crates/warden-seal LI
|
||||
crates/wapp-core LM
|
||||
crates/wapp-pack LM
|
||||
Vendored
+70
@@ -0,0 +1,70 @@
|
||||
# flare-ui
|
||||
|
||||
Shared UI and schema crates for FLARE and the Warden console. They provide
|
||||
schema forms, navigation, charts, page assets, editors and package validation.
|
||||
|
||||
- Licence: MIT.
|
||||
- Branches: `main` and `next`, like flare. Work branches from `next`.
|
||||
- Pinning: consumers vendor a tagged commit (`vN.N.N`) and record it in
|
||||
`flare-ui.lock`. They never pin an untagged commit, and CI jobs hold no
|
||||
cross-repo credential.
|
||||
- Layout: worktree per branch, `flare-ui/.bare` plus one folder per branch,
|
||||
kept in step with Gitea by `scripts/sync-worktrees.sh` (outside the repo).
|
||||
- Toolchain: `rust-toolchain.toml` pins one exact version.
|
||||
- Dash editor: `dash-editor/` holds the imported `flare-dash-editor` tree and
|
||||
its history (lane LD owns it). Its tests: `cd dash-editor && node --test tests/*.test.mjs`.
|
||||
- Flow builder: `flow-builder/` holds the automation flowchart (model, form,
|
||||
view). Its tests: `cd flow-builder && node --test tests/*.test.mjs`.
|
||||
- Validation corpus: `corpus/` (lane LB), described in `corpus/README.md`.
|
||||
- Crates and owners: see `OWNERS`. Vendoring and tags: `docs/vendoring.md`.
|
||||
|
||||
## Crates
|
||||
|
||||
| Crate | Role |
|
||||
|---|---|
|
||||
| `flare-ui` | Schema forms, navigation, chart islands, page assets and editor assets |
|
||||
| `wschema` | Schema document model, builder DSL, canonical JSON, hashes, lint L01 to L23 |
|
||||
| `wschema-cli` | `canon`, `hash`, `lint` and corpus `validate` for fragment authors and CI; `verify-lock` and `gen-lock` for consumer locks (`flare-ui.lock`, `gen.lock`) |
|
||||
| `wschema-gen` | Generators: the OpenAPI `components.schemas` of an effective schema and their splice into a template |
|
||||
| `warden-sync` | Sync stamps, HLC, windows, digest and planner (d03), and the wire and value limits both ends share, with golden limit vectors (`tests/vectors/limits-vectors.jsonl`) each end replays |
|
||||
| `warden-seal` | Per-Warden sealing (HPKE Auth): suite, `info` and `aad` builders, padding, kid, shared vectors |
|
||||
| `wapp-core` | App package format, manifests, platform checks and validation |
|
||||
| `wapp-pack` | Package creation, verification, signing, index and release guard CLI |
|
||||
| `flare-plugin-abi` | Reserved plugin ABI placeholder |
|
||||
|
||||
`wschema` depends on `serde`, `serde_json` and `sha2` only, and builds for
|
||||
x86_64 and `armv7-unknown-linux-musleabihf`.
|
||||
|
||||
## Checks
|
||||
|
||||
```
|
||||
cargo fmt --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace
|
||||
scripts/check-owners.sh
|
||||
scripts/vendor-selftest.sh
|
||||
```
|
||||
|
||||
The [chart browser checks](crates/flare-ui/tests/browser/README.md) run on
|
||||
Chromium and Firefox over plain HTTP, with CSP and real SSE samples.
|
||||
The [live client](docs/live.md) documents typed chart props, server tier
|
||||
links, accessible latest values and named series events.
|
||||
|
||||
The shared crates also build for the panel:
|
||||
|
||||
```
|
||||
cargo build --locked --target armv7-unknown-linux-musleabihf \
|
||||
-p wschema -p warden-sync -p warden-seal -p wapp-core
|
||||
```
|
||||
|
||||
The OpenAPI emitter's sample output passes an OpenAPI 3.1 validator
|
||||
(`openapi-spec-validator`, not part of CI here; the consumer's CI runs it on
|
||||
the real document):
|
||||
|
||||
```
|
||||
cargo run -q -p wschema-gen --example openapi_sample > sample.yaml
|
||||
openapi-spec-validator sample.yaml
|
||||
```
|
||||
|
||||
Benchmarks for `wschema` (canonical JSON, hash, lint on a 140-setting
|
||||
document): `cargo bench -p wschema --bench canon_hash`.
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
# Validation corpus
|
||||
|
||||
Cases that every implementation of the settings schema must answer the same
|
||||
way: `wschema` (flared and the FLARE server) and anything that ports it. The
|
||||
format is d02 "Corpus"; the reference is the module doc of
|
||||
`crates/wschema/src/corpus.rs`.
|
||||
|
||||
## Files
|
||||
|
||||
| File | What it holds |
|
||||
|---|---|
|
||||
| `generic.jsonl` | One or more cases per validation stage and code: path, key, cap, scope, `write_via`, type, range, enum, length, check, the cross-field rules, permissions, resets |
|
||||
| `flare-ported.jsonl` | The leaf cases of FLARE's `flare-server/src/tests_wardencfg.rs`, each with a `note` naming its test |
|
||||
| `schema/warden-base.json` | The schema both files run against: the Warden base as flare-edge emits it (`data/schema/base.json`, commit f6bc5281) |
|
||||
|
||||
A case's `schema` member names a base id (the base alone) or a fragment id
|
||||
(the base plus that fragment). Both files use `base`.
|
||||
|
||||
## Differences from FLARE
|
||||
|
||||
- An empty `system.hostname` is refused (V_LEN, d02 D25); FLARE stored it.
|
||||
- `network.interfaces.Eth0` is outside the path grammar (V_PATH), so the key
|
||||
check never sees it; `0eth` is the key-check case (V_KEY).
|
||||
- A VPN field written alone carries the other VPN fields in `ctx.rows`, since
|
||||
the `vpn` rules (all or none, allowed IPs once an address is set) now run.
|
||||
|
||||
## Running
|
||||
|
||||
```
|
||||
cargo test -p wschema --test corpus
|
||||
wschema-cli validate --schema corpus/schema/warden-base.json \
|
||||
--corpus corpus/generic.jsonl --corpus corpus/flare-ported.jsonl
|
||||
```
|
||||
|
||||
`validate_corpus` runs every `*.jsonl` here. It also fails when the generic
|
||||
file stops reaching a validation code the base can produce, and when any one
|
||||
flipped expectation goes unreported.
|
||||
|
||||
## Editing
|
||||
|
||||
Edit the JSON lines directly; one case per line, ASCII only. When flare-edge
|
||||
changes a row the cases touch, refresh `schema/warden-base.json` from its
|
||||
emitted `data/schema/base.json` and record the commit above. Each firmware
|
||||
also emits its own corpus from the `valid` and `invalid` vectors of its
|
||||
settings (`wschema::corpus::emit`). A setting that a cross-field rule
|
||||
refuses in the empty context declares a `vector_ctx` (DSL `vector_path`,
|
||||
`vector_row`): the concrete path and the stored rows its vectors run at.
|
||||
Each emitted case carries those rows in `ctx.rows`. Like the vectors, it is
|
||||
never emitted into the schema or hashed.
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.wifi.country", "value": "CA", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs wifi_country_is_two_uppercase_letters_or_unset"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.wifi.country", "value": "ca", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs wifi_country_is_two_uppercase_letters_or_unset"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.wifi.country", "value": "C", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs wifi_country_is_two_uppercase_letters_or_unset"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.wifi.country", "value": "CAN", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs wifi_country_is_two_uppercase_letters_or_unset"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.wifi.country", "value": "00", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs wifi_country_is_two_uppercase_letters_or_unset"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.wifi.country", "value": "C1", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs wifi_country_is_two_uppercase_letters_or_unset"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.wifi.country", "value": " CA", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs wifi_country_is_two_uppercase_letters_or_unset"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.wifi.country", "value": 12, "expect": {"code": "V_TYPE"}, "note": "flare tests_wardencfg.rs wifi_country_is_two_uppercase_letters_or_unset"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.wifi.regdomain", "value": "CA", "expect": {"code": "V_PATH"}, "note": "flare tests_wardencfg.rs wifi_country_is_two_uppercase_letters_or_unset"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "display.brightness", "value": 101, "expect": {"code": "V_RANGE"}, "note": "flare tests_wardencfg.rs out_of_range_values_read_like_the_wardens_own_details"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "display.sleep_minutes", "value": 2, "expect": {"code": "V_ENUM"}, "note": "flare tests_wardencfg.rs out_of_range_values_read_like_the_wardens_own_details"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "display.theme", "value": "sepia", "expect": {"code": "V_ENUM"}, "note": "flare tests_wardencfg.rs out_of_range_values_read_like_the_wardens_own_details"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "rs485.baud", "value": 9601, "expect": {"code": "V_ENUM"}, "note": "flare tests_wardencfg.rs out_of_range_values_read_like_the_wardens_own_details"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "rs485.timeout_ms", "value": 60001, "expect": {"code": "V_RANGE"}, "note": "flare tests_wardencfg.rs out_of_range_values_read_like_the_wardens_own_details"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.vpn.keepalive_seconds", "value": 65536, "expect": {"code": "V_RANGE"}, "note": "flare tests_wardencfg.rs out_of_range_values_read_like_the_wardens_own_details"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.routing.lease", "value": "2h", "expect": {"code": "V_ENUM"}, "note": "flare tests_wardencfg.rs out_of_range_values_read_like_the_wardens_own_details"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.routing.lease", "value": "12h", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs out_of_range_values_read_like_the_wardens_own_details"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "display.sleep_minutes", "value": 0, "expect": {"ok": true}, "note": "flare tests_wardencfg.rs out_of_range_values_read_like_the_wardens_own_details"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "system.timezone", "value": "CET-1CEST,M3.5.0,M10.5.0/3", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs timezone_is_curated_or_empty"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "system.timezone", "value": "Europe/Berlin", "expect": {"code": "V_ENUM"}, "note": "flare tests_wardencfg.rs timezone_is_curated_or_empty"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "system.hostname", "value": "warden-07", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs hostname_is_an_rfc1123_label_or_empty"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "system.hostname", "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs hostname_is_an_rfc1123_label_or_empty"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "system.hostname", "value": "", "expect": {"code": "V_LEN"}, "note": "flare tests_wardencfg.rs hostname_is_an_rfc1123_label_or_empty; d02 D25 refuses an empty hostname where FLARE stored it"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "system.hostname", "value": "-edge", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs hostname_is_an_rfc1123_label_or_empty"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "system.hostname", "value": "edge-", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs hostname_is_an_rfc1123_label_or_empty"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "system.hostname", "value": "no.dots", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs hostname_is_an_rfc1123_label_or_empty"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "system.hostname", "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs hostname_is_an_rfc1123_label_or_empty"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.ap.address", "value": "10.0.0.1/24", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.ap.address", "value": "10.0.0.1/31", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.ap.address", "value": "", "expect": {"code": "V_LEN"}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.routing.lan_address", "value": "300.1.1.1/24", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.vpn.address", "value": "10.99.0.2/33", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"rows": {"network.vpn.peer_endpoint": "hub.example.test:51820", "network.vpn.peer_public_key": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", "network.vpn.allowed_ips": "10.99.0.0/24"}}, "path": "network.vpn.address", "value": "10.99.0.2/32", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns; the other VPN fields set so the vpn rules hold"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.vpn.address", "value": "", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"rows": {"network.vpn.address": "10.99.0.2/32", "network.vpn.peer_public_key": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", "network.vpn.allowed_ips": "10.99.0.0/24"}}, "path": "network.vpn.peer_endpoint", "value": "[2001:db8::1]:51820", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns; the other VPN fields set so the vpn rules hold"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"rows": {"network.vpn.address": "10.99.0.2/32", "network.vpn.peer_endpoint": "hub.example.test:51820", "network.vpn.allowed_ips": "10.99.0.0/24"}}, "path": "network.vpn.peer_public_key", "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns; the other VPN fields set so the vpn rules hold"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.vpn.peer_public_key", "value": "", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.proxy.pac", "value": "", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.proxy.http", "value": "proxy.example.test:3128", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.proxy.http", "value": "no-port", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.proxy.socks", "value": "spaced host:80", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.proxy.pac", "value": "http://wpad.example.test/wpad.dat", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.proxy.pac", "value": "ftp://x", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.vpn.peer_public_key", "value": "short=", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs addresses_and_endpoints_follow_the_yaml_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.vpn.allowed_ips", "value": "10.0.0.0/8, 192.168.0.0/16", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs string_byte_caps_are_the_stores_own"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.vpn.allowed_ips", "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "expect": {"code": "V_LEN"}, "note": "flare tests_wardencfg.rs string_byte_caps_are_the_stores_own"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "system.ntp.server", "value": "two\nlines", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs string_byte_caps_are_the_stores_own"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.ap.ssid", "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs string_byte_caps_are_the_stores_own"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.ap.ssid", "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs string_byte_caps_are_the_stores_own"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.ap.passphrase", "value": "1234567", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs string_byte_caps_are_the_stores_own"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.ap.passphrase", "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "expect": {"code": "V_LEN"}, "note": "flare tests_wardencfg.rs string_byte_caps_are_the_stores_own"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.ap.passphrase", "value": "snowman\u2603pass", "expect": {"code": "V_CHECK"}, "note": "flare tests_wardencfg.rs string_byte_caps_are_the_stores_own"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.interfaces.eth0.zone", "value": "lan", "expect": {"ok": true}, "note": "flare tests_wardencfg.rs interface_names_and_app_ids_follow_their_key_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.interfaces.Eth0.zone", "value": "lan", "expect": {"code": "V_PATH"}, "note": "flare tests_wardencfg.rs interface_names_and_app_ids_follow_their_key_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.interfaces.0eth.zone", "value": "lan", "expect": {"code": "V_KEY"}, "note": "flare tests_wardencfg.rs interface_names_and_app_ids_follow_their_key_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.interfaces.eth-0.zone", "value": "lan", "expect": {"code": "V_KEY"}, "note": "flare tests_wardencfg.rs interface_names_and_app_ids_follow_their_key_patterns"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.interfaces.abcdefghijklmnop.zone", "value": "lan", "expect": {"code": "V_KEY"}, "note": "flare tests_wardencfg.rs interface_names_and_app_ids_follow_their_key_patterns"}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.wifi.regdomain", "value": "CA", "expect": {"code": "V_PATH"}, "note": "not a setting"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network..wifi", "value": "x", "expect": {"code": "V_PATH"}, "note": "malformed path"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "display.brightness.extra", "value": 1, "expect": {"code": "V_PATH"}, "note": "a leaf has no children"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.wifi.country", "reset": true, "expect": {"ok": true}, "note": "a reset of a synced setting from FLARE"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "$meta.fp_key", "value": "k", "expect": {"ok": true}, "note": "meta path handled before the schema"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "$meta.unknown", "value": "k", "expect": {"code": "V_PATH"}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.interfaces.Eth0.zone", "value": "lan", "expect": {"code": "V_PATH"}, "note": "uppercase is outside the path grammar, so the key check never sees it"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.interfaces.0eth.zone", "value": "lan", "expect": {"code": "V_KEY"}, "note": "ifname key check: starts with a letter"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "relays.8.safe_state", "value": "open", "expect": {"code": "V_KEY"}, "note": "index key above max 7"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "relays.7.safe_state", "value": "open", "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"rows": {"network.interfaces.eth0.ipv4.method": "dhcp", "network.interfaces.eth1.ipv4.method": "dhcp", "network.interfaces.eth2.ipv4.method": "dhcp", "network.interfaces.eth3.ipv4.method": "dhcp", "network.interfaces.eth4.ipv4.method": "dhcp", "network.interfaces.eth5.ipv4.method": "dhcp", "network.interfaces.eth6.ipv4.method": "dhcp", "network.interfaces.eth7.ipv4.method": "dhcp", "network.interfaces.eth8.ipv4.method": "dhcp", "network.interfaces.eth9.ipv4.method": "dhcp", "network.interfaces.eth10.ipv4.method": "dhcp", "network.interfaces.eth11.ipv4.method": "dhcp", "network.interfaces.eth12.ipv4.method": "dhcp", "network.interfaces.eth13.ipv4.method": "dhcp", "network.interfaces.eth14.ipv4.method": "dhcp", "network.interfaces.eth15.ipv4.method": "dhcp"}}, "path": "network.interfaces.eth16.ipv4.method", "value": "dhcp", "expect": {"code": "V_CAP"}, "note": "17th entry of a 16-entry map"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"rows": {"network.interfaces.eth0.ipv4.method": "dhcp", "network.interfaces.eth1.ipv4.method": "dhcp", "network.interfaces.eth2.ipv4.method": "dhcp", "network.interfaces.eth3.ipv4.method": "dhcp", "network.interfaces.eth4.ipv4.method": "dhcp", "network.interfaces.eth5.ipv4.method": "dhcp", "network.interfaces.eth6.ipv4.method": "dhcp", "network.interfaces.eth7.ipv4.method": "dhcp", "network.interfaces.eth8.ipv4.method": "dhcp", "network.interfaces.eth9.ipv4.method": "dhcp", "network.interfaces.eth10.ipv4.method": "dhcp", "network.interfaces.eth11.ipv4.method": "dhcp", "network.interfaces.eth12.ipv4.method": "dhcp", "network.interfaces.eth13.ipv4.method": "dhcp", "network.interfaces.eth14.ipv4.method": "dhcp", "network.interfaces.eth15.ipv4.method": "dhcp"}}, "path": "network.interfaces.eth15.ipv4.method", "value": "dhcp", "expect": {"ok": true}, "note": "an existing entry never counts twice"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"rows": {"network.interfaces.eth0.ipv4.method": "dhcp", "network.interfaces.eth1.ipv4.method": "dhcp", "network.interfaces.eth2.ipv4.method": "dhcp", "network.interfaces.eth3.ipv4.method": "dhcp", "network.interfaces.eth4.ipv4.method": "dhcp", "network.interfaces.eth5.ipv4.method": "dhcp", "network.interfaces.eth6.ipv4.method": "dhcp", "network.interfaces.eth7.ipv4.method": "dhcp", "network.interfaces.eth8.ipv4.method": "dhcp", "network.interfaces.eth9.ipv4.method": "dhcp", "network.interfaces.eth10.ipv4.method": "dhcp", "network.interfaces.eth11.ipv4.method": "dhcp", "network.interfaces.eth12.ipv4.method": "dhcp", "network.interfaces.eth13.ipv4.method": "dhcp", "network.interfaces.eth14.ipv4.method": "dhcp", "network.interfaces.eth15.ipv4.method": "dhcp"}}, "path": "network.interfaces.eth16.ipv4.method", "reset": true, "expect": {"ok": true}, "note": "a reset never counts against the cap"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "display.debug_overlay", "value": true, "expect": {"code": "V_SCOPE"}, "note": "device_only from FLARE"}
|
||||
{"schema": "base", "origin": "panel", "ctx": {}, "path": "display.debug_overlay", "value": true, "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "panel", "ctx": {}, "path": "network.ap.local.password", "value": "secret12", "expect": {"code": "V_VIA"}, "note": "write_via: only the action writes it"}
|
||||
{"schema": "base", "origin": "system", "ctx": {}, "path": "network.ap.local.password", "value": "secret12", "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "display.brightness", "value": "50", "expect": {"code": "V_TYPE"}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "display.brightness", "value": null, "expect": {"code": "V_TYPE"}, "note": "null is not a value; reset is the op for that"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "display.brightness", "value": 50.5, "expect": {"code": "V_TYPE"}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "display.brightness", "value": -1, "expect": {"code": "V_RANGE"}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "display.brightness", "value": 0, "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "display.theme", "value": "sepia", "expect": {"code": "V_ENUM"}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "display.sleep_minutes", "value": 2, "expect": {"code": "V_ENUM"}, "note": "int_set"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "relays.lease_max_s", "value": 59, "expect": {"code": "V_RANGE"}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "relays.lease_max_s", "value": 86400, "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.interfaces.eth0.ipv4.dns", "value": ["1.1.1.1", "9.9.9.9"], "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.interfaces.eth0.ipv4.dns", "value": ["1.1.1.1", "dns.example"], "expect": {"code": "V_CHECK"}, "note": "list item check"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.interfaces.eth0.ipv4.dns", "value": ["1.1.1.1", "1.1.1.1", "1.1.1.1", "1.1.1.1", "1.1.1.1"], "expect": {"code": "V_LEN"}, "note": "max_items 4"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.interfaces.eth0.ipv4.dns", "value": [1], "expect": {"code": "V_TYPE"}, "note": "list items are strings"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.scan_ranges", "value": ["10.0.0.0/8"], "expect": {"ok": true}, "note": "a CIDR counts once toward the expansion cap"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.scan_ranges", "value": ["10.0-255.0-1.1-255"], "expect": {"code": "V_CHECK"}, "note": "scan_expansion_cap: 512 /24 ranges"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.scan_ranges", "value": ["192.168.1.0/24"], "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.ap.passphrase", "value": "short", "expect": {"code": "V_CHECK"}, "note": "secret kind with a check"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.ap.passphrase", "value": "12345678", "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "panel", "ctx": {}, "path": "display.debug_overlay", "value": "true", "expect": {"code": "V_TYPE"}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "display.brightness", "reset": true, "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.wifi.nope", "reset": true, "expect": {"code": "V_PATH"}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.ap.security", "value": "WPA2", "expect": {"code": "V_REQUIRES"}, "note": "PSK needs a passphrase"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"rows": {"network.ap.passphrase": "12345678"}}, "path": "network.ap.security", "value": "WPA2", "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.ap.security", "value": "Open", "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.interfaces.eth0.ipv4.method", "value": "manual", "expect": {"code": "V_REQUIRES"}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"rows": {"network.interfaces.eth0.ipv4.address": "10.1.0.2/24"}}, "path": "network.interfaces.eth0.ipv4.method", "value": "manual", "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"rows": {"network.interfaces.eth0.zone": "wan"}}, "path": "network.interfaces.eth1.zone", "value": "wan", "expect": {"code": "V_EXCLUSIVE"}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"rows": {"network.interfaces.eth0.zone": "wan"}}, "path": "network.interfaces.eth1.zone", "value": "lan", "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"rows": {"network.interfaces.eth0.zone": "wan"}}, "path": "network.interfaces.eth0.zone", "value": "wan", "expect": {"ok": true}, "note": "rewriting the entry that holds the value"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"rows": {"network.routing.lan_address": "192.168.50.1/24"}}, "path": "network.ap.address", "value": "192.168.50.1/24", "expect": {"code": "V_OVERLAP"}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"rows": {"network.routing.lan_address": "192.168.50.1/24"}}, "path": "network.ap.address", "value": "10.254.1.1/24", "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.vpn.peer_endpoint", "value": "hub.example.test:51820", "expect": {"code": "V_ALL_OR_NONE"}, "note": "flare-ui#13: the other two hold their empty default"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"rows": {"network.vpn.peer_endpoint": "hub.example.test:51820", "network.vpn.peer_public_key": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="}}, "path": "network.vpn.address", "value": "10.99.0.2/32", "expect": {"code": "V_REQUIRES"}, "note": "flare-ui#13: allowed_ips is empty"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"rows": {"network.vpn.peer_endpoint": "hub.example.test:51820", "network.vpn.peer_public_key": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", "network.vpn.allowed_ips": "10.99.0.0/24"}}, "path": "network.vpn.address", "value": "10.99.0.2/32", "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.vpn.address", "value": "", "expect": {"ok": true}, "note": "all three empty is the none state"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"usable_wifi_credentials": false, "rows": {"network.ap.local.enabled": false}}, "path": "network.ap.security", "value": "WPA2-Enterprise", "expect": {"code": "V_RULE"}, "note": "ap_enterprise_credentials"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"usable_wifi_credentials": false, "rows": {"network.ap.local.enabled": true}}, "path": "network.ap.security", "value": "WPA2-Enterprise", "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "flare", "ctx": {}, "path": "network.ap.security", "value": "WPA2-Enterprise", "expect": {"ok": true}, "note": "named rules without their context input are skipped"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"tls_state": "self_signed"}, "path": "network.ap.security", "value": "WPA2-Enterprise", "expect": {"code": "V_RULE"}, "note": "ap_enterprise_cert"}
|
||||
{"schema": "base", "origin": "flare", "ctx": {"tls_state": "public"}, "path": "network.ap.security", "value": "WPA2-Enterprise", "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "web", "ctx": {"perms": ["site.view"]}, "path": "display.brightness", "value": 50, "expect": {"code": "V_PERM"}}
|
||||
{"schema": "base", "origin": "web", "ctx": {"perms": ["site.manage"]}, "path": "display.brightness", "value": 50, "expect": {"ok": true}}
|
||||
{"schema": "base", "origin": "migration", "ctx": {"perms": []}, "path": "display.brightness", "value": 50, "expect": {"ok": true}, "note": "internal origins skip permissions"}
|
||||
+5725
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "flare-plugin-abi"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
description = "Plugin ABI shared by FLARE and the Warden console"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Plugin ABI shared by FLARE and the Warden console.
|
||||
//!
|
||||
//! Placeholder until its owning lane lands the real crate (see OWNERS).
|
||||
|
||||
/// Crate name, used by consumers to check which pin they vendored.
|
||||
pub const NAME: &str = "flare-plugin-abi";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn name_is_stable() {
|
||||
assert_eq!(NAME, "flare-plugin-abi");
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "flare-ui"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
description = "Shared UI crate for FLARE and the Warden console: schema renderer, nav model, dash editor assets, LVGL table generator"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
wschema = { path = "../wschema" }
|
||||
serde_json = "1"
|
||||
maud = "0.27"
|
||||
|
||||
[dev-dependencies]
|
||||
criterion = { version = "0.5", default-features = false }
|
||||
|
||||
[[bench]]
|
||||
name = "chart"
|
||||
harness = false
|
||||
@@ -0,0 +1,184 @@
|
||||
/* Shared component styles. Every value comes from tokens.css. */
|
||||
.bf-btn {
|
||||
display: inline-block;
|
||||
padding: var(--bf-space-2) var(--bf-space-4);
|
||||
cursor: pointer;
|
||||
}
|
||||
.bf-btn-primary {
|
||||
font-weight: 600;
|
||||
}
|
||||
.bf-badge {
|
||||
display: inline-block;
|
||||
padding: 0 var(--bf-space-2);
|
||||
}
|
||||
.bf-badge-ok {
|
||||
font-weight: 600;
|
||||
}
|
||||
.bf-badge-warn {
|
||||
font-weight: 600;
|
||||
}
|
||||
.bf-badge-err {
|
||||
font-weight: 700;
|
||||
}
|
||||
.bf-card {
|
||||
padding: var(--bf-space-4);
|
||||
}
|
||||
.bf-card-title {
|
||||
margin: 0 0 var(--bf-space-2);
|
||||
}
|
||||
.bf-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
.bf-stale {
|
||||
opacity: 0.6;
|
||||
}
|
||||
.bf-shell {
|
||||
display: flex;
|
||||
min-height: 100vh;
|
||||
}
|
||||
.bf-sidebar {
|
||||
padding: var(--bf-space-4);
|
||||
}
|
||||
.bf-nav-section {
|
||||
margin: 0 0 var(--bf-space-4);
|
||||
}
|
||||
.bf-nav-section-title {
|
||||
margin: 0 0 var(--bf-space-2);
|
||||
}
|
||||
.bf-nav-link {
|
||||
display: block;
|
||||
padding: var(--bf-space-1) var(--bf-space-2);
|
||||
text-decoration: none;
|
||||
}
|
||||
.bf-nav-active {
|
||||
font-weight: 700;
|
||||
}
|
||||
.bf-main {
|
||||
flex: 1;
|
||||
padding: var(--bf-space-4);
|
||||
}
|
||||
.bf-tabs {
|
||||
display: flex;
|
||||
gap: var(--bf-space-2);
|
||||
margin: 0 0 var(--bf-space-4);
|
||||
}
|
||||
.bf-field {
|
||||
margin: 0 0 var(--bf-space-4);
|
||||
}
|
||||
.bf-field-label {
|
||||
display: block;
|
||||
margin: 0 0 var(--bf-space-1);
|
||||
}
|
||||
.bf-field-help {
|
||||
margin: var(--bf-space-1) 0 0;
|
||||
}
|
||||
.bf-field-error {
|
||||
margin: var(--bf-space-1) 0 0;
|
||||
font-weight: 600;
|
||||
}
|
||||
.bf-input {
|
||||
width: 100%;
|
||||
padding: var(--bf-space-2);
|
||||
}
|
||||
.bf-segmented {
|
||||
display: flex;
|
||||
gap: var(--bf-space-2);
|
||||
}
|
||||
.bf-segment {
|
||||
padding: var(--bf-space-1) var(--bf-space-2);
|
||||
cursor: pointer;
|
||||
}
|
||||
.bf-switch {
|
||||
display: inline-flex;
|
||||
gap: var(--bf-space-2);
|
||||
cursor: pointer;
|
||||
}
|
||||
.bf-kv {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: var(--bf-space-2);
|
||||
padding: var(--bf-space-1) 0;
|
||||
}
|
||||
.bf-kv-label {
|
||||
display: inline-block;
|
||||
}
|
||||
.bf-kv-value {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.bf-gauge {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--bf-space-2);
|
||||
}
|
||||
.bf-gauge-bar {
|
||||
flex: 1;
|
||||
}
|
||||
.bf-hero {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
.bf-hero-value {
|
||||
font-size: 3rem;
|
||||
font-weight: 700;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.bf-hero-units {
|
||||
display: inline-block;
|
||||
}
|
||||
.bf-log {
|
||||
margin: 0;
|
||||
padding: 0 0 0 var(--bf-space-4);
|
||||
font-family: monospace;
|
||||
}
|
||||
.bf-chart {
|
||||
margin: 0;
|
||||
}
|
||||
.bf-chart-canvas {
|
||||
width: 100%;
|
||||
height: 12rem;
|
||||
}
|
||||
.bf-vh {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.bf-note {
|
||||
margin: 0 0 var(--bf-space-2);
|
||||
}
|
||||
.bf-plate {
|
||||
display: grid;
|
||||
grid-template-columns: max-content 1fr;
|
||||
gap: var(--bf-space-1) var(--bf-space-4);
|
||||
margin: 0;
|
||||
}
|
||||
.bf-btn-danger {
|
||||
background: var(--bf-color-danger);
|
||||
color: #fff;
|
||||
}
|
||||
.bf-action {
|
||||
display: inline-block;
|
||||
margin: 0 var(--bf-space-2) var(--bf-space-2) 0;
|
||||
}
|
||||
.bf-action-confirm {
|
||||
margin: 0 0 var(--bf-space-1);
|
||||
}
|
||||
.bf-approvals {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.bf-approval {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--bf-space-2);
|
||||
align-items: center;
|
||||
padding: var(--bf-space-2) 0;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/* flare-ui page glue (UI-6): one call wires the live stream, stale marker,
|
||||
* chart island, table sort and the htmx CSRF header. Reads two optional
|
||||
* <meta> tags: bf-stream (SSE URL) and bf-csrf (token). No dependencies. */
|
||||
(function (root, factory) {
|
||||
if (typeof module === "object" && module.exports) module.exports = factory(root);
|
||||
else root.FlareBoot = factory(root);
|
||||
})(typeof self !== "undefined" ? self : this, function (root) {
|
||||
"use strict";
|
||||
|
||||
function meta(doc, name) {
|
||||
var m = doc.querySelector('meta[name="' + name + '"]');
|
||||
return m ? m.getAttribute("content") : null;
|
||||
}
|
||||
|
||||
/* Same-origin check on a stream URL: path-absolute, not protocol-relative. */
|
||||
function safeStream(url) {
|
||||
return typeof url === "string" && url.charAt(0) === "/" && url.charAt(1) !== "/" &&
|
||||
url.indexOf("\\") < 0 && !/[\x00-\x20\x7f]/.test(url);
|
||||
}
|
||||
|
||||
/* htmx:configRequest handler: adds the CSRF header to every htmx request. */
|
||||
function csrfHeader(token) {
|
||||
return function (evt) {
|
||||
if (token && evt && evt.detail && evt.detail.headers) {
|
||||
evt.detail.headers["X-CSRF-Token"] = token;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/* env: { Live, Charts, Islands, doc, loc } injected so tests need no browser. */
|
||||
function boot(env) {
|
||||
var doc = env.doc;
|
||||
var result = { live: null, csrf: false };
|
||||
var token = meta(doc, "bf-csrf");
|
||||
if (token) {
|
||||
doc.body.addEventListener("htmx:configRequest", csrfHeader(token));
|
||||
result.csrf = true;
|
||||
}
|
||||
if (env.Islands) env.Islands.bindTableSort(doc, env.loc);
|
||||
var url = meta(doc, "bf-stream");
|
||||
if (url && safeStream(url) && env.Live) {
|
||||
var live = new env.Live.Live(url);
|
||||
env.Live.bindStaleMarker(live, doc);
|
||||
if (env.Charts) env.Charts.bindCharts(live, doc);
|
||||
live.start();
|
||||
result.live = live;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function auto() {
|
||||
if (typeof document === "undefined") return;
|
||||
boot({
|
||||
doc: document, loc: location,
|
||||
Live: root.FlareLive, Charts: root.FlareChart, Islands: root.FlareIslands
|
||||
});
|
||||
}
|
||||
if (typeof document !== "undefined") {
|
||||
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", auto);
|
||||
else auto();
|
||||
}
|
||||
|
||||
return { boot: boot, safeStream: safeStream, csrfHeader: csrfHeader };
|
||||
});
|
||||
@@ -0,0 +1,533 @@
|
||||
(function (root, factory) {
|
||||
if (typeof module === "object" && module.exports) module.exports = factory();
|
||||
else root.FlareChart = factory();
|
||||
})(typeof self !== "undefined" ? self : this, function () {
|
||||
"use strict";
|
||||
|
||||
/* Retained Warden renderer. */
|
||||
function createEngine(env) {
|
||||
env = env || {};
|
||||
var window = env.window;
|
||||
var document = env.document || (window && window.document);
|
||||
if (!window || !document) throw new Error("canvas engine needs a window and document");
|
||||
var state = env.state || { chartTier: "min", prevGenMs: 0 };
|
||||
var reduceMotion = env.reduceMotion || window.matchMedia("(prefers-reduced-motion: reduce)");
|
||||
var now = env.now || function () { return window.performance.now(); };
|
||||
var getComputedStyle = env.getComputedStyle || function (el) { return window.getComputedStyle(el); };
|
||||
var paletteMemo = null; // invalidated by the binding on each new feed
|
||||
function palette(){
|
||||
if (paletteMemo) return paletteMemo;
|
||||
var cs = getComputedStyle(document.documentElement);
|
||||
function c(n){ return (cs.getPropertyValue('--'+n)||'').trim(); }
|
||||
return (paletteMemo = { accent:c('accent')||'#3776BE', flame:c('flame')||'#F26522',
|
||||
ok:c('ok')||'#1E8E4E', border:c('border')||'#D5DAE3',
|
||||
muted:c('text-muted')||'#5A6577', font:c('font-body')||'sans-serif' });
|
||||
}
|
||||
function hexToRgba(hex, a){
|
||||
var m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((hex||'').trim());
|
||||
if(!m) return hex;
|
||||
var h = m[1]; if(h.length===3) h = h[0]+h[0]+h[1]+h[1]+h[2]+h[2];
|
||||
return 'rgba('+parseInt(h.slice(0,2),16)+','+parseInt(h.slice(2,4),16)+','+parseInt(h.slice(4,6),16)+','+a+')';
|
||||
}
|
||||
function fitCanvas(cv){
|
||||
var r = cv.getBoundingClientRect();
|
||||
var w = Math.round(r.width), h = Math.round(r.height);
|
||||
if(w<=0 || h<=0) return null;
|
||||
var dpr = Math.min(2.5, window.devicePixelRatio || 1);
|
||||
var bw = Math.round(w*dpr), bh = Math.round(h*dpr);
|
||||
if(cv.width !== bw) cv.width = bw;
|
||||
if(cv.height !== bh) cv.height = bh;
|
||||
var ctx = cv.getContext('2d');
|
||||
ctx.setTransform(dpr,0,0,dpr,0,0);
|
||||
return { ctx:ctx, w:w, h:h, dpr:dpr };
|
||||
}
|
||||
var GRAPH_SUBDIV = 12;
|
||||
function catmull(p0,p1,p2,p3,t){
|
||||
var t2 = t*t, t3 = t2*t;
|
||||
return 0.5*((2*p1) + (-p0+p2)*t + (2*p0-5*p1+4*p2-p3)*t2 + (-p0+3*p1-3*p2+p3)*t3);
|
||||
}
|
||||
function sampleAt(v,n,i){ if(i<0)i=0; if(i>n-1)i=n-1; return v[i]; }
|
||||
|
||||
var SLIDE_SLOTS = 9;
|
||||
var LAG_LOW = 2.5;
|
||||
var LAG_START = 3;
|
||||
var LAG_OVERRUN = 3;
|
||||
var MAX_ADVANCE = 8;
|
||||
var MAX_HISTORY = 72;
|
||||
|
||||
function chartSlide(frame, ts){
|
||||
if (!frame.vel) return frame.slide0;
|
||||
return Math.min(frame.maxSlide, frame.slide0 + frame.vel * Math.max(0, ts - frame.feedAt));
|
||||
}
|
||||
|
||||
function alignAdvance(prior, fresh, expected){
|
||||
var best = -1, bestGap = 1e9;
|
||||
for (var k = 0; k <= MAX_ADVANCE; k++) {
|
||||
var ok = true, judged = 0;
|
||||
for (var i = 0; ok && i < fresh.length; i++) {
|
||||
var a = prior[i], b = fresh[i];
|
||||
if (!a || !b) continue;
|
||||
var n = Math.min(a.length, b.length - k, 30);
|
||||
if (n < 4) continue;
|
||||
judged++;
|
||||
for (var j = 0; j < n; j++) {
|
||||
var x = b[b.length - 1 - k - j], y = a[a.length - 1 - j];
|
||||
if (Math.abs(x - y) > 1e-6 * (1 + Math.abs(y))) { ok = false; break; }
|
||||
}
|
||||
}
|
||||
if (ok && judged) {
|
||||
var gap = Math.abs(k - expected);
|
||||
if (gap < bestGap) { best = k; bestGap = gap; }
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function layerFor(cv, key, w, h, dpr){
|
||||
var l = cv[key] || (cv[key] = document.createElement('canvas'));
|
||||
var bw = Math.max(1, Math.ceil(w * dpr)), bh = Math.max(1, Math.ceil(h * dpr));
|
||||
if (l.width !== bw) l.width = bw;
|
||||
if (l.height !== bh) l.height = bh;
|
||||
var c = l.getContext('2d');
|
||||
c.setTransform(1,0,0,1,0,0); c.clearRect(0,0,bw,bh);
|
||||
c.setTransform(dpr,0,0,dpr,0,0);
|
||||
return { el:l, ctx:c };
|
||||
}
|
||||
|
||||
function paintLines(cv, spec){
|
||||
var generation = state.prevGenMs || 0, t = now();
|
||||
var minute = state.chartTier === 'min';
|
||||
var animated = minute && !reduceMotion.matches;
|
||||
var slots = animated ? SLIDE_SLOTS : 0;
|
||||
|
||||
var advanced = -1, total = 0;
|
||||
if (minute) {
|
||||
var prior = cv.__history, fresh = spec.series.map(function(s){ return (s.data || []).slice(); });
|
||||
if (prior) advanced = alignAdvance(prior.series, fresh, Math.round((generation - prior.gen) / 1000));
|
||||
spec.series = spec.series.map(function(s, i){
|
||||
var data = fresh[i], old = prior && advanced >= 0 && prior.series[i];
|
||||
if (old) {
|
||||
var joined = advanced > 0 ? old.concat(data.slice(-advanced)) : old;
|
||||
if (joined.length >= data.length) data = joined;
|
||||
}
|
||||
return { data:data.slice(-MAX_HISTORY), color:s.color, area:s.area };
|
||||
});
|
||||
total = advanced >= 0 ? prior.total + advanced : 0;
|
||||
cv.__history = { gen:generation, revision:spec.historyRevision, total:total,
|
||||
series:spec.series.map(function(s){ return s.data.slice(); }) };
|
||||
} else cv.__history = null;
|
||||
|
||||
var clk = null;
|
||||
if (animated) {
|
||||
clk = cv.__clock;
|
||||
if (!clk || advanced < 0) clk = { lag:LAG_START, v:1, t:t, arrived:t, T:2 };
|
||||
else {
|
||||
clk.lag = Math.max(-LAG_OVERRUN, clk.lag - clk.v * (t - clk.t) / 1000); clk.t = t;
|
||||
if (advanced > 0) {
|
||||
clk.T = Math.min(6, Math.max(0.8, 0.6 * clk.T + 0.4 * (t - clk.arrived) / 1000));
|
||||
clk.arrived = t;
|
||||
clk.lag = Math.min(slots, clk.lag + advanced);
|
||||
clk.v = Math.min(2.5, Math.max(0.5, (clk.lag - LAG_LOW) / clk.T));
|
||||
} else if ((t - clk.arrived) / 1000 > 0.8 * clk.T) {
|
||||
clk.v = Math.min(2.5, Math.max(0.5, (clk.lag - LAG_LOW) / clk.T));
|
||||
}
|
||||
}
|
||||
cv.__clock = clk;
|
||||
} else cv.__clock = null;
|
||||
|
||||
var f = fitCanvas(cv); if(!f) return;
|
||||
var W=f.w, H=f.h, dpr=f.dpr, pal=palette();
|
||||
var labelled = !!spec.fmtY;
|
||||
var padL = labelled?46:10, padR=12, padT=10, padB=8;
|
||||
var plotW = Math.max(1, W-padL-padR), plotH = Math.max(1, H-padT-padB);
|
||||
var yMin = spec.yMin, yMax = spec.yMax; if(!(yMax>yMin)) yMax = yMin+1;
|
||||
var baseY = padT+plotH;
|
||||
function yPx(v){ if(v<yMin)v=yMin; if(v>yMax)v=yMax; return padT+plotH-(v-yMin)/(yMax-yMin)*plotH; }
|
||||
|
||||
var maxLen=0, hasData=false;
|
||||
spec.series.forEach(function(s){ var n=(s.data&&s.data.length)||0; if(n>maxLen)maxLen=n; if(n>0)hasData=true; });
|
||||
|
||||
var frame = {
|
||||
W:W, H:H, dpr:dpr, padL:padL, padR:padR, padT:padT, plotW:plotW, plotH:plotH, baseY:baseY,
|
||||
yMin:yMin, yMax:yMax, divs:spec.grid||4, labelled:labelled, fmtY:spec.fmtY||null,
|
||||
gridColor:pal.border, labelColor:pal.muted, mutedColor:pal.muted, font:pal.font,
|
||||
empty:!hasData, dx:0, slots:slots, feedAt:t, slide0:0, vel:0, maxSlide:0,
|
||||
newestId:total, series:[],
|
||||
slideAt:function(ts){ return chartSlide(frame, ts); }
|
||||
};
|
||||
|
||||
if(hasData){
|
||||
var N = minute ? 60 : Math.max(2, maxLen), dx = plotW/(N-1);
|
||||
frame.dx = dx;
|
||||
frame.maxSlide = (slots + LAG_OVERRUN)*dx;
|
||||
frame.slide0 = clk ? (slots - clk.lag) * dx : 0;
|
||||
frame.vel = clk ? clk.v * dx / 1000 : 0;
|
||||
function xBase(len,j){ return padL + plotW + slots*dx - (len-1-j)*dx; }
|
||||
spec.series.forEach(function(s){
|
||||
var data=s.data||[], len=data.length;
|
||||
var entry = { color:s.color, area:!!s.area, pts:[], endpoint:null };
|
||||
if(len>=1) entry.endpoint = { x:xBase(len,len-1), y:yPx(data[len-1]) };
|
||||
if(len>=2){
|
||||
for(var j=0;j<len-1;j++){
|
||||
var p0=sampleAt(data,len,j-1), p1=sampleAt(data,len,j),
|
||||
p2=sampleAt(data,len,j+1), p3=sampleAt(data,len,j+2), x0=xBase(len,j);
|
||||
var subdivisions = Math.max(GRAPH_SUBDIV, Math.ceil(dx / 2));
|
||||
for(var k=0;k<subdivisions;k++){
|
||||
var tt=k/subdivisions, v=catmull(p0,p1,p2,p3,tt);
|
||||
if(v<yMin)v=yMin; if(v>yMax)v=yMax; // a spline through noisy data overshoots; keep it in range
|
||||
entry.pts.push({ x:x0 + tt*dx, y:yPx(v) });
|
||||
}
|
||||
}
|
||||
entry.pts.push({ x:xBase(len,len-1), y:yPx(data[len-1]) }); // the newest sample, exactly
|
||||
}
|
||||
frame.series.push(entry);
|
||||
});
|
||||
}
|
||||
|
||||
var base = layerFor(cv, '__base', W, H, dpr);
|
||||
drawBase(base.ctx, frame);
|
||||
frame.base = base.el;
|
||||
if (!frame.empty) {
|
||||
var lw = W + slots*frame.dx + 2, ly = layerFor(cv, '__layer', lw, H, dpr);
|
||||
drawSeries(ly.ctx, frame);
|
||||
frame.layer = ly.el; frame.layerW = ly.el.width / dpr;
|
||||
}
|
||||
cv.__cframe = frame;
|
||||
drawFrame(cv, frame, t);
|
||||
}
|
||||
|
||||
function drawBase(ctx, frame){
|
||||
var padL=frame.padL, padR=frame.padR, padT=frame.padT, plotW=frame.plotW, plotH=frame.plotH, W=frame.W;
|
||||
var yMin=frame.yMin, yMax=frame.yMax, divs=frame.divs;
|
||||
function yPx(v){ return padT+plotH-(v-yMin)/(yMax-yMin)*plotH; }
|
||||
ctx.save();
|
||||
ctx.lineWidth=1; ctx.strokeStyle=frame.gridColor;
|
||||
ctx.font='11px '+frame.font; ctx.textBaseline='middle'; ctx.textAlign='right';
|
||||
for(var g=0; g<=divs; g++){
|
||||
var gv = yMin+(yMax-yMin)*g/divs, gy = Math.round(yPx(gv))+0.5;
|
||||
ctx.globalAlpha=0.4; ctx.beginPath(); ctx.moveTo(padL,gy); ctx.lineTo(W-padR,gy); ctx.stroke();
|
||||
if(frame.labelled){ ctx.globalAlpha=0.9; ctx.fillStyle=frame.labelColor; ctx.fillText(frame.fmtY(gv), padL-6, yPx(gv)); }
|
||||
}
|
||||
ctx.restore();
|
||||
if(frame.empty){
|
||||
ctx.save(); ctx.fillStyle=frame.mutedColor; ctx.font='12px '+frame.font;
|
||||
ctx.textAlign='center'; ctx.textBaseline='middle';
|
||||
ctx.fillText('Collecting trend data...', padL+plotW/2, padT+plotH/2); ctx.restore();
|
||||
}
|
||||
}
|
||||
|
||||
function drawSeries(ctx, frame){
|
||||
var padT=frame.padT, baseY=frame.baseY;
|
||||
frame.series.forEach(function(s){
|
||||
var pts=s.pts, len=pts.length;
|
||||
if(len>1){
|
||||
if(s.area){
|
||||
ctx.save(); ctx.beginPath();
|
||||
for(var j=0;j<len;j++){ if(j===0)ctx.moveTo(pts[j].x,pts[j].y); else ctx.lineTo(pts[j].x,pts[j].y); }
|
||||
ctx.lineTo(pts[len-1].x, baseY); ctx.lineTo(pts[0].x, baseY); ctx.closePath();
|
||||
var grad = ctx.createLinearGradient(0,padT,0,baseY);
|
||||
grad.addColorStop(0, hexToRgba(s.color,0.26)); grad.addColorStop(1, hexToRgba(s.color,0.02));
|
||||
ctx.fillStyle=grad; ctx.fill(); ctx.restore();
|
||||
}
|
||||
ctx.save(); ctx.beginPath();
|
||||
for(var k=0;k<len;k++){ if(k===0)ctx.moveTo(pts[k].x,pts[k].y); else ctx.lineTo(pts[k].x,pts[k].y); }
|
||||
ctx.lineWidth=2; ctx.lineJoin='round'; ctx.lineCap='round'; ctx.strokeStyle=s.color; ctx.stroke(); ctx.restore();
|
||||
}
|
||||
if(s.endpoint){
|
||||
var e=s.endpoint;
|
||||
ctx.save();
|
||||
ctx.globalAlpha=0.2; ctx.beginPath(); ctx.arc(e.x,e.y,6,0,6.2832); ctx.fillStyle=s.color; ctx.fill();
|
||||
ctx.globalAlpha=1; ctx.beginPath(); ctx.arc(e.x,e.y,3.4,0,6.2832); ctx.fillStyle=s.color; ctx.fill();
|
||||
ctx.restore();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function drawFrame(cv, frame, ts){
|
||||
var ctx = cv.getContext('2d'), dpr = frame.dpr;
|
||||
ctx.setTransform(1,0,0,1,0,0); ctx.clearRect(0,0,cv.width,cv.height);
|
||||
ctx.setTransform(dpr,0,0,dpr,0,0);
|
||||
ctx.drawImage(frame.base, 0, 0, frame.W, frame.H);
|
||||
if(frame.empty || !frame.layer) return;
|
||||
ctx.save();
|
||||
ctx.beginPath(); ctx.rect(frame.padL, frame.padT, frame.plotW, frame.plotH); ctx.clip();
|
||||
ctx.drawImage(frame.layer, -chartSlide(frame, ts), 0, frame.layerW, frame.H);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
return { paintLines: paintLines, drawFrame: drawFrame, catmull: catmull,
|
||||
chartSlide: chartSlide, alignAdvance: alignAdvance, state: state,
|
||||
invalidatePalette: function () { paletteMemo = null; } };
|
||||
}
|
||||
|
||||
function numeric(samples) {
|
||||
return samples.filter(function (s) {
|
||||
return typeof s.v === "number" && isFinite(s.v) && typeof s.t === "number" && isFinite(s.t);
|
||||
});
|
||||
}
|
||||
|
||||
function bounds(samples) {
|
||||
var pts = numeric(samples);
|
||||
if (!pts.length) return [0, 1];
|
||||
var lo = Infinity, hi = -Infinity;
|
||||
pts.forEach(function (s) { if (s.v < lo) lo = s.v; if (s.v > hi) hi = s.v; });
|
||||
var pad = lo === hi ? Math.max(1, Math.abs(lo) * 0.05) : (hi / 2 - lo / 2) * 0.1;
|
||||
var low = lo - pad, high = hi + pad;
|
||||
return [isFinite(low) ? low : lo, isFinite(high) ? high : hi];
|
||||
}
|
||||
|
||||
/* Keep a stable scale for history; reserve spline headroom and lift subnormals. */
|
||||
function fitSeries(series, scale) {
|
||||
var peak = 0, values = [], floor = Number.MIN_VALUE * Math.pow(2, 52), limit = Number.MAX_VALUE / 32;
|
||||
series.forEach(function (s) { s.data.forEach(function (v) { peak = Math.max(peak, Math.abs(v)); }); });
|
||||
scale = scale || 1;
|
||||
var magnitude = peak / scale;
|
||||
if (!isFinite(magnitude) || magnitude > limit || (peak > 0 && magnitude < floor)) {
|
||||
scale = peak > limit ? limit : peak < floor ? floor : 1;
|
||||
}
|
||||
var fitted = series.map(function (s) {
|
||||
var data = s.data.map(function (v) { var n = v / scale; values.push({ t: 0, v: n }); return n; });
|
||||
return Object.assign({}, s, { data: data });
|
||||
});
|
||||
return { series: fitted, range: bounds(values), scale: scale };
|
||||
}
|
||||
|
||||
function plotPoints(samples, w, h) {
|
||||
var pts = numeric(samples);
|
||||
if (!pts.length || w <= 0 || h <= 0) return [];
|
||||
var fitted = fitSeries([{ data: pts.map(function (s) { return s.v; }) }]);
|
||||
var times = fitSeries([{ data: pts.map(function (s) { return s.t; }) }]).series[0].data;
|
||||
var b = fitted.range, values = fitted.series[0].data;
|
||||
var t0 = times[0], t1 = times[times.length - 1];
|
||||
var span = t1 - t0;
|
||||
return pts.map(function (s, i) {
|
||||
var x = span > 0 ? ((times[i] - t0) / span) * w : (pts.length === 1 ? w / 2 : (i / (pts.length - 1)) * w);
|
||||
var y = h - ((values[i] - b[0]) / (b[1] - b[0])) * h;
|
||||
return [x, y];
|
||||
});
|
||||
}
|
||||
|
||||
function draw(ctx, samples, w, h, style) {
|
||||
style = style || {};
|
||||
ctx.clearRect(0, 0, w, h);
|
||||
var p = plotPoints(samples, w, h);
|
||||
if (!p.length) return 0;
|
||||
ctx.strokeStyle = style.stroke || "currentColor";
|
||||
ctx.lineWidth = style.width || 2;
|
||||
ctx.beginPath();
|
||||
p.forEach(function (q, i) { if (i === 0) ctx.moveTo(q[0], q[1]); else ctx.lineTo(q[0], q[1]); });
|
||||
ctx.stroke();
|
||||
return p.length;
|
||||
}
|
||||
|
||||
function formatValue(v) {
|
||||
if (typeof v === "number") {
|
||||
if (!isFinite(v)) return "--";
|
||||
return String(Number(v.toFixed(3)));
|
||||
}
|
||||
return typeof v === "object" ? "--" : String(v);
|
||||
}
|
||||
|
||||
function withValue(text, value) {
|
||||
var m = /^\s*\S*(\s.*)?$/.exec(String(text));
|
||||
return value + (m && m[1] ? m[1] : "");
|
||||
}
|
||||
|
||||
function applyReadings(live, doc) {
|
||||
var els = doc.querySelectorAll("[data-live][data-key]");
|
||||
for (var i = 0; i < els.length; i++) {
|
||||
var el = els[i];
|
||||
if (el.getAttribute("data-island")) continue;
|
||||
var key = el.getAttribute("data-key");
|
||||
var s = live.samples(key);
|
||||
if (!s.length) continue;
|
||||
var v = s[s.length - 1].v;
|
||||
var txt = formatValue(v);
|
||||
var kv = el.querySelector(".bf-kv-value");
|
||||
if (kv) kv.textContent = withValue(kv.textContent, txt);
|
||||
var hero = el.querySelector(".bf-hero-value");
|
||||
if (hero) hero.textContent = txt;
|
||||
var meter = el.querySelector("meter");
|
||||
if (meter && typeof v === "number" && isFinite(v)) meter.value = v;
|
||||
}
|
||||
}
|
||||
|
||||
var chartBindings = new WeakMap();
|
||||
|
||||
function chartProps(raw) {
|
||||
var p;
|
||||
try { p = JSON.parse(raw); } catch (_) { return null; }
|
||||
function text(s, max) { return typeof s === "string" && s.length > 0 && s.length <= max && !/[\x00-\x1f\x7f]/.test(s); }
|
||||
if (!p || !text(p.id, 128) || !Array.isArray(p.series) || !p.series.length || p.series.length > 64 ||
|
||||
!["min", "hour", "day"].includes(p.tier) || !p.tiers || !p.points || typeof p.points !== "object" || Array.isArray(p.points)) return null;
|
||||
var keys = new Set();
|
||||
for (var s of p.series) {
|
||||
if (!s || !text(s.key, 256) || !text(s.label, 256) || typeof s.unit !== "string" || s.unit.length > 64 ||
|
||||
/[\x00-\x1f\x7f]/.test(s.unit) || typeof s.color !== "string" || !/^#(?:[\da-f]{3}|[\da-f]{6})$/i.test(s.color) || keys.has(s.key)) return null;
|
||||
keys.add(s.key);
|
||||
}
|
||||
for (var tier of ["min", "hour", "day"]) {
|
||||
var t = p.tiers[tier];
|
||||
if (!t || t.n !== 60 || !Number.isInteger(t.step_s) || t.step_s <= 0 || t.step_s > 4294967295) return null;
|
||||
}
|
||||
for (var key of Object.keys(p.points)) {
|
||||
var points = p.points[key];
|
||||
if (!keys.has(key) || !Array.isArray(points) || points.length > 60 || points.some(function (q, i) {
|
||||
return !Array.isArray(q) || q.length !== 2 || !q.every(Number.isFinite) || (i > 0 && points[i - 1][0] >= q[0]);
|
||||
})) return null;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
function chartData(props, live) {
|
||||
var all = [], latest = Object.create(null), generation = 0;
|
||||
var series = props.series.map(function (s) {
|
||||
var points = new Map();
|
||||
if (Object.prototype.hasOwnProperty.call(props.points, s.key)) props.points[s.key].forEach(function (p) { points.set(p[0], p[1]); });
|
||||
if (live.chartSamples) numeric(live.chartSamples(props.id, s.key)).forEach(function (p) { points.set(p.t, p.v); });
|
||||
var samples = Array.from(points, function (p) { return { t: p[0], v: p[1] }; })
|
||||
.sort(function (a, b) { return a.t - b.t; }).slice(-props.tiers[props.tier].n);
|
||||
all = all.concat(samples);
|
||||
var last = samples[samples.length - 1];
|
||||
latest[s.key] = (last ? formatValue(last.v) : "--") + " " + s.unit;
|
||||
if (last) generation = Math.max(generation, last.t);
|
||||
return { data: samples.map(function (p) { return p.v; }), color: s.color };
|
||||
});
|
||||
return { series: series, range: bounds(all), latest: latest, generation: generation };
|
||||
}
|
||||
|
||||
function bindCharts(live, doc) {
|
||||
var prior = chartBindings.get(doc);
|
||||
if (prior) prior();
|
||||
var view = doc.defaultView;
|
||||
if (!view) throw new Error("chart binding needs a browser document");
|
||||
var motion = view.matchMedia("(prefers-reduced-motion: reduce)");
|
||||
var entries = new Map(), raf = null, disposed = false;
|
||||
function attached(canvas) { return doc.documentElement.contains(canvas); }
|
||||
function visible(canvas) {
|
||||
var rect = canvas.getBoundingClientRect();
|
||||
return Math.round(rect.width) > 0 && Math.round(rect.height) > 0;
|
||||
}
|
||||
function prune() {
|
||||
entries.forEach(function (_, canvas) { if (!attached(canvas)) entries.delete(canvas); });
|
||||
}
|
||||
function cancel() {
|
||||
if (raf !== null) view.cancelAnimationFrame(raf);
|
||||
raf = null;
|
||||
}
|
||||
function moving() {
|
||||
if (disposed || motion.matches || doc.hidden || live.stale === true || live.closed === true) return false;
|
||||
var result = false, stamp = view.performance.now();
|
||||
entries.forEach(function (entry, canvas) {
|
||||
var frame = entry.frame;
|
||||
if (frame && frame.vel && attached(canvas) && visible(canvas) && frame.slideAt(stamp) < frame.maxSlide) result = true;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
function schedule() {
|
||||
if (!moving()) { cancel(); return; }
|
||||
if (raf === null) raf = view.requestAnimationFrame(tick);
|
||||
}
|
||||
function tick(stamp) {
|
||||
raf = null;
|
||||
prune();
|
||||
if (!disposed && !motion.matches && !doc.hidden && live.stale !== true && live.closed !== true) {
|
||||
entries.forEach(function (entry, canvas) {
|
||||
if (entry.frame && entry.frame.vel && visible(canvas)) entry.engine.drawFrame(canvas, entry.frame, stamp);
|
||||
});
|
||||
}
|
||||
schedule();
|
||||
}
|
||||
function tierFor(figure) {
|
||||
var tier = figure.getAttribute("data-tier") || new URLSearchParams(view.location.search).get("tier");
|
||||
return tier === "hour" || tier === "day" ? tier : "min";
|
||||
}
|
||||
function redraw(initial) {
|
||||
if (disposed) return;
|
||||
prune();
|
||||
var figures = doc.querySelectorAll('[data-island="chart"]');
|
||||
for (var i = 0; i < figures.length; i++) {
|
||||
var figure = figures[i], canvas = figure.querySelector("canvas");
|
||||
if (!canvas || !canvas.getContext || !attached(canvas)) continue;
|
||||
var raw = figure.getAttribute("data-chart"), key = figure.getAttribute("data-key"), tier = tierFor(figure);
|
||||
if (initial === true && !raw) continue;
|
||||
var entry = entries.get(canvas);
|
||||
if (raw && entry && entry.raw === raw && entry.props) tier = entry.props.tier;
|
||||
if (!entry || entry.key !== key || entry.tier !== tier || entry.raw !== raw) {
|
||||
var props = raw ? chartProps(raw) : null;
|
||||
if (raw && !props) { entries.delete(canvas); continue; }
|
||||
if (props) tier = props.tier;
|
||||
delete canvas.__history; delete canvas.__clock; delete canvas.__cframe;
|
||||
var reduced = { matches: false };
|
||||
entry = { key: key, tier: tier, raw: raw, props: props, motion: reduced, engine: createEngine({ window: view, document: doc,
|
||||
reduceMotion: reduced, state: { chartTier: tier, prevGenMs: 0 } }) };
|
||||
entries.set(canvas, entry);
|
||||
}
|
||||
if (!visible(canvas)) { entry.frame = null; continue; }
|
||||
var data;
|
||||
if (entry.props) {
|
||||
data = chartData(entry.props, live);
|
||||
var values = figure.querySelectorAll("[data-chart-value]");
|
||||
for (var j = 0; j < values.length; j++) {
|
||||
var valueKey = values[j].getAttribute("data-chart-value");
|
||||
if (Object.prototype.hasOwnProperty.call(data.latest, valueKey)) values[j].textContent = data.latest[valueKey];
|
||||
}
|
||||
} else {
|
||||
var samples = numeric(live.samples(key)).slice(-60);
|
||||
data = { series: [{ data: samples.map(function (s) { return s.v; }), color: figure.getAttribute("data-color") || "#3776BE" }],
|
||||
range: bounds(samples), generation: samples.length ? samples[samples.length - 1].t : 0 };
|
||||
}
|
||||
entry.engine.state.prevGenMs = data.generation;
|
||||
entry.engine.invalidatePalette();
|
||||
var fitted = fitSeries(data.series, entry.scale);
|
||||
if (entry.scale && entry.scale !== fitted.scale) { delete canvas.__history; delete canvas.__clock; }
|
||||
entry.scale = fitted.scale;
|
||||
// Keep short seeds inside the plot.
|
||||
entry.motion.matches = motion.matches || live.stale === true || fitted.series.some(s => s.data.length > 0 && s.data.length < 4);
|
||||
entry.engine.paintLines(canvas, { series: fitted.series, yMin: fitted.range[0], yMax: fitted.range[1], grid: 4 });
|
||||
entry.frame = canvas.__cframe;
|
||||
}
|
||||
schedule();
|
||||
}
|
||||
function clean(event) {
|
||||
var element = event && event.detail && event.detail.elt;
|
||||
if (element && element.contains) {
|
||||
entries.forEach(function (_, canvas) { if (element.contains(canvas)) entries.delete(canvas); });
|
||||
}
|
||||
schedule();
|
||||
}
|
||||
function visibility() { if (doc.hidden) cancel(); else redraw(); }
|
||||
var unsubscribe = live.onChange(function (what) {
|
||||
if (disposed) return;
|
||||
if (what === "data") { applyReadings(live, doc); redraw(); }
|
||||
else if (what === "stale") schedule();
|
||||
});
|
||||
doc.addEventListener("htmx:afterSwap", redraw);
|
||||
doc.addEventListener("htmx:beforeCleanupElement", clean);
|
||||
doc.addEventListener("htmx:beforeCleanup", clean);
|
||||
doc.addEventListener("visibilitychange", visibility);
|
||||
view.addEventListener("resize", redraw);
|
||||
motion.addEventListener("change", redraw);
|
||||
function stop() {
|
||||
if (disposed) return;
|
||||
disposed = true; cancel(); entries.clear();
|
||||
if (typeof unsubscribe === "function") unsubscribe();
|
||||
doc.removeEventListener("htmx:afterSwap", redraw);
|
||||
doc.removeEventListener("htmx:beforeCleanupElement", clean);
|
||||
doc.removeEventListener("htmx:beforeCleanup", clean);
|
||||
doc.removeEventListener("visibilitychange", visibility);
|
||||
view.removeEventListener("resize", redraw);
|
||||
motion.removeEventListener("change", redraw);
|
||||
if (chartBindings.get(doc) === stop) chartBindings.delete(doc);
|
||||
}
|
||||
chartBindings.set(doc, stop);
|
||||
redraw(true);
|
||||
return stop;
|
||||
}
|
||||
|
||||
return {
|
||||
createEngine: createEngine, bounds: bounds, plotPoints: plotPoints, draw: draw, formatValue: formatValue,
|
||||
withValue: withValue, applyReadings: applyReadings, bindCharts: bindCharts,
|
||||
chartProps: chartProps, chartData: chartData
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
/* flare-ui islands (UI-6): table sort kept in the URL and column resize.
|
||||
* Pure helpers are exported for Node tests; the DOM binders are thin. */
|
||||
(function (root, factory) {
|
||||
if (typeof module === "object" && module.exports) module.exports = factory();
|
||||
else root.FlareIslands = factory();
|
||||
})(typeof self !== "undefined" ? self : this, function () {
|
||||
"use strict";
|
||||
|
||||
var MIN_COL = 40;
|
||||
var MAX_COL = 800;
|
||||
|
||||
/* "?sort=name&dir=desc" -> {key, dir}; dir defaults to asc, junk -> null. */
|
||||
function parseSort(search) {
|
||||
var key = null, dir = "asc";
|
||||
new URLSearchParams(search || "").forEach(function (v, k) {
|
||||
if (k === "sort" && /^[A-Za-z0-9_.-]{1,64}$/.test(v)) key = v;
|
||||
if (k === "dir" && (v === "asc" || v === "desc")) dir = v;
|
||||
});
|
||||
return key ? { key: key, dir: dir } : null;
|
||||
}
|
||||
|
||||
/* Query string after clicking column `key`: toggles dir on the same key. */
|
||||
function nextSortQuery(search, key) {
|
||||
var cur = parseSort(search);
|
||||
var dir = cur && cur.key === key && cur.dir === "asc" ? "desc" : "asc";
|
||||
var params = new URLSearchParams(search || "");
|
||||
params.delete("sort"); params.delete("dir");
|
||||
params.append("sort", key); params.append("dir", dir);
|
||||
return "?" + params.toString();
|
||||
}
|
||||
|
||||
/* Numbers compare numerically, everything else as case-folded text. */
|
||||
function compareCells(a, b) {
|
||||
var na = Number(a), nb = Number(b);
|
||||
if (a !== "" && b !== "" && isFinite(na) && isFinite(nb)) return na - nb;
|
||||
var x = String(a).toLowerCase(), y = String(b).toLowerCase();
|
||||
return x < y ? -1 : x > y ? 1 : 0;
|
||||
}
|
||||
|
||||
/* Stable sort of rows (arrays of strings) by column index. */
|
||||
function sortRows(rows, col, dir) {
|
||||
var sign = dir === "desc" ? -1 : 1;
|
||||
return rows
|
||||
.map(function (r, i) { return { r: r, i: i }; })
|
||||
.sort(function (p, q) {
|
||||
return sign * compareCells(p.r[col], q.r[col]) || p.i - q.i;
|
||||
})
|
||||
.map(function (p) { return p.r; });
|
||||
}
|
||||
|
||||
function clampWidth(px) {
|
||||
var n = Math.round(Number(px));
|
||||
if (!isFinite(n)) return MIN_COL;
|
||||
return Math.max(MIN_COL, Math.min(MAX_COL, n));
|
||||
}
|
||||
|
||||
/* Keep column headers semantic; native controls supply keyboard activation. */
|
||||
function bindTableSort(doc, loc) {
|
||||
var ths = doc.querySelectorAll("th[data-sort]");
|
||||
for (var i = 0; i < ths.length; i++) {
|
||||
(function (th) {
|
||||
if (th.querySelector("a[href],button,input,select,textarea,[tabindex],[role=button],[role=link]")) return;
|
||||
var button = doc.createElement("button");
|
||||
button.type = "button";
|
||||
while (th.firstChild) button.appendChild(th.firstChild);
|
||||
th.appendChild(button);
|
||||
button.addEventListener("click", function () {
|
||||
loc.search = nextSortQuery(loc.search, th.getAttribute("data-sort"));
|
||||
});
|
||||
})(ths[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
parseSort: parseSort, nextSortQuery: nextSortQuery, compareCells: compareCells,
|
||||
sortRows: sortRows, clampWidth: clampWidth, bindTableSort: bindTableSort,
|
||||
MIN_COL: MIN_COL, MAX_COL: MAX_COL
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
/* flare-ui live client (UI-6): SSE stream with a bounded ring, reconnect
|
||||
* backoff and a stale marker. No dependencies; works in a browser and in
|
||||
* Node (tests inject EventSource, timers and a clock). */
|
||||
(function (root, factory) {
|
||||
if (typeof module === "object" && module.exports) module.exports = factory();
|
||||
else root.FlareLive = factory();
|
||||
})(typeof self !== "undefined" ? self : this, function () {
|
||||
"use strict";
|
||||
|
||||
var DEFAULTS = {
|
||||
ringCap: 600, // samples kept per series
|
||||
maxSeries: 64, // series tracked per stream; extra keys are dropped
|
||||
staleAfterMs: 15000, // no event for this long marks the stream stale
|
||||
backoffMinMs: 1000,
|
||||
backoffMaxMs: 30000,
|
||||
staleClass: "bf-stale"
|
||||
};
|
||||
|
||||
/* Fixed-capacity ring of {t, v}; oldest sample is overwritten. */
|
||||
function Ring(cap) {
|
||||
this.cap = cap;
|
||||
this.buf = [];
|
||||
this.head = 0;
|
||||
}
|
||||
Ring.prototype.push = function (item) {
|
||||
if (this.buf.length < this.cap) this.buf.push(item);
|
||||
else {
|
||||
this.buf[this.head] = item;
|
||||
this.head = (this.head + 1) % this.cap;
|
||||
}
|
||||
};
|
||||
Ring.prototype.toArray = function () {
|
||||
return this.buf.slice(this.head).concat(this.buf.slice(0, this.head));
|
||||
};
|
||||
Ring.prototype.size = function () { return this.buf.length; };
|
||||
|
||||
/* Reconnect delay for attempt n (0-based): doubles, capped. */
|
||||
function backoff(attempt, min, max) {
|
||||
var d = min * Math.pow(2, attempt);
|
||||
return d > max || !isFinite(d) ? max : d;
|
||||
}
|
||||
|
||||
/* env: { EventSource, setTimeout, clearTimeout, now } (all optional in a browser). */
|
||||
function Live(url, opts, env) {
|
||||
env = env || {};
|
||||
var o = {};
|
||||
var k;
|
||||
for (k in DEFAULTS) o[k] = DEFAULTS[k];
|
||||
for (k in (opts || {})) o[k] = opts[k];
|
||||
this.opts = o;
|
||||
this.url = url;
|
||||
this.ES = env.EventSource || (typeof EventSource !== "undefined" ? EventSource : null);
|
||||
var st = env.setTimeout || setTimeout;
|
||||
var ct = env.clearTimeout || clearTimeout;
|
||||
/* Wrapped so the timers run unbound; browsers reject a foreign `this`. */
|
||||
this.setT = function (fn, ms) { return st(fn, ms); };
|
||||
this.clearT = function (id) { return ct(id); };
|
||||
this.now = env.now || Date.now;
|
||||
this.series = Object.create(null);
|
||||
this.chartSeries = Object.create(null);
|
||||
this.seriesCount = 0;
|
||||
this.dropped = 0;
|
||||
this.attempt = 0;
|
||||
this.lastEventAt = null;
|
||||
this.stale = true;
|
||||
this.es = null;
|
||||
this.timer = null;
|
||||
this.staleTimer = null;
|
||||
this.closed = false;
|
||||
this.listeners = [];
|
||||
}
|
||||
|
||||
Live.prototype.onChange = function (fn) {
|
||||
var self = this, active = true;
|
||||
this.listeners.push(fn);
|
||||
return function () {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
var index = self.listeners.indexOf(fn);
|
||||
if (index >= 0) self.listeners.splice(index, 1);
|
||||
};
|
||||
};
|
||||
Live.prototype._emit = function (what) {
|
||||
var listeners = this.listeners.slice();
|
||||
for (var i = 0; i < listeners.length; i++) listeners[i](what, this);
|
||||
};
|
||||
|
||||
Live.prototype.start = function () {
|
||||
var self = this;
|
||||
if (this.es || this.timer !== null) return;
|
||||
if (!this.ES) throw new Error("EventSource unavailable");
|
||||
this.closed = false;
|
||||
var source = this.es = new this.ES(this.url);
|
||||
function current() { return !self.closed && self.es === source; }
|
||||
source.onopen = function () { if (current()) { self.attempt = 0; self._arm(); } };
|
||||
source.onmessage = function (ev) { if (current()) self.ingest(ev.data); };
|
||||
if (source.addEventListener) source.addEventListener("series", function (ev) {
|
||||
if (current()) self.ingestSeries(ev.data);
|
||||
});
|
||||
source.onerror = function () {
|
||||
if (!current()) return;
|
||||
self._setStale(true);
|
||||
if (self.es) { self.es.close(); self.es = null; }
|
||||
if (self.closed) return;
|
||||
var d = backoff(self.attempt++, self.opts.backoffMinMs, self.opts.backoffMaxMs);
|
||||
self.timer = self.setT(function () { self.timer = null; self.start(); }, d);
|
||||
};
|
||||
this._arm();
|
||||
};
|
||||
|
||||
Live.prototype.close = function () {
|
||||
this.closed = true;
|
||||
if (this.es) { this.es.close(); this.es = null; }
|
||||
if (this.timer !== null) { this.clearT(this.timer); this.timer = null; }
|
||||
if (this.staleTimer !== null) { this.clearT(this.staleTimer); this.staleTimer = null; }
|
||||
};
|
||||
|
||||
/* Restart the stale watchdog. */
|
||||
Live.prototype._arm = function () {
|
||||
var self = this;
|
||||
if (this.staleTimer !== null) this.clearT(this.staleTimer);
|
||||
this.staleTimer = this.setT(function () {
|
||||
self.staleTimer = null;
|
||||
self._setStale(true);
|
||||
}, this.opts.staleAfterMs);
|
||||
};
|
||||
|
||||
Live.prototype._setStale = function (v) {
|
||||
if (this.stale === v) return;
|
||||
this.stale = v;
|
||||
this._emit("stale");
|
||||
};
|
||||
|
||||
/* One SSE data payload: JSON {"k": key, "v": value, "t": ms} or an array of those. */
|
||||
Live.prototype.ingest = function (data) {
|
||||
var msg;
|
||||
try { msg = JSON.parse(data); } catch (e) { this.dropped++; return; }
|
||||
var items = Array.isArray(msg) ? msg : [msg];
|
||||
var t0 = this.now(), accepted = 0;
|
||||
for (var i = 0; i < items.length; i++) {
|
||||
var m = items[i];
|
||||
if (!m || typeof m.k !== "string" || m.v === undefined) { this.dropped++; continue; }
|
||||
if (typeof m.t === "number" && !isFinite(m.t)) { this.dropped++; continue; }
|
||||
var r = this.series[m.k];
|
||||
if (!r) {
|
||||
if (this.seriesCount >= this.opts.maxSeries) { this.dropped++; continue; }
|
||||
r = this.series[m.k] = new Ring(this.opts.ringCap);
|
||||
this.seriesCount++;
|
||||
}
|
||||
r.push({ t: typeof m.t === "number" ? m.t : t0, v: m.v });
|
||||
accepted++;
|
||||
}
|
||||
if (!accepted) return;
|
||||
this.lastEventAt = t0;
|
||||
this._arm();
|
||||
this._setStale(false);
|
||||
this._emit("data");
|
||||
};
|
||||
|
||||
Live.prototype.samples = function (key) {
|
||||
return this.series[key] ? this.series[key].toArray() : [];
|
||||
};
|
||||
|
||||
/* Named chart events are isolated from readings and other chart ids. */
|
||||
Live.prototype.ingestSeries = function (data) {
|
||||
var m;
|
||||
try { m = JSON.parse(data); } catch (e) { this.dropped++; return; }
|
||||
if (!m || typeof m.id !== "string" || !m.id.length || m.id.length > 128 ||
|
||||
typeof m.key !== "string" || !m.key.length || m.key.length > 256 ||
|
||||
!Array.isArray(m.p) || m.p.length !== 2 ||
|
||||
!m.p.every(function (v) { return typeof v === "number" && isFinite(v); })) {
|
||||
this.dropped++; return;
|
||||
}
|
||||
var key = JSON.stringify([m.id, m.key]), ring = this.chartSeries[key];
|
||||
if (!ring) {
|
||||
if (this.seriesCount >= this.opts.maxSeries) { this.dropped++; return; }
|
||||
ring = this.chartSeries[key] = new Ring(this.opts.ringCap);
|
||||
this.seriesCount++;
|
||||
}
|
||||
ring.push({ t: m.p[0], v: m.p[1] });
|
||||
this.lastEventAt = this.now(); this._arm(); this._setStale(false); this._emit("data");
|
||||
};
|
||||
|
||||
Live.prototype.chartSamples = function (id, key) {
|
||||
var ring = this.chartSeries[JSON.stringify([id, key])];
|
||||
return ring ? ring.toArray() : [];
|
||||
};
|
||||
|
||||
/* Toggle the stale class on every element carrying data-live. */
|
||||
function bindStaleMarker(live, doc, cls) {
|
||||
cls = cls || live.opts.staleClass;
|
||||
function mark() {
|
||||
var els = doc.querySelectorAll("[data-live]");
|
||||
for (var i = 0; i < els.length; i++) {
|
||||
if (live.stale) els[i].classList.add(cls);
|
||||
else els[i].classList.remove(cls);
|
||||
}
|
||||
}
|
||||
mark();
|
||||
var unsubscribe = live.onChange(function (what) { if (what === "stale") mark(); });
|
||||
if (doc.addEventListener) doc.addEventListener("htmx:afterSwap", mark);
|
||||
return function () {
|
||||
unsubscribe();
|
||||
if (doc.removeEventListener) doc.removeEventListener("htmx:afterSwap", mark);
|
||||
};
|
||||
}
|
||||
|
||||
return { Live: Live, Ring: Ring, backoff: backoff, bindStaleMarker: bindStaleMarker, DEFAULTS: DEFAULTS };
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
/* Shared app theme (UI-4): the --app-* semantic layer over tokens.css.
|
||||
* Dark is the default; light follows an explicit data-theme or, when absent,
|
||||
* the system preference. Extracted from the FLARE portal stylesheet so FLARE
|
||||
* and the Warden console read one palette. Embedded as flare_ui::tokens::THEME_CSS.
|
||||
*/
|
||||
|
||||
:root {
|
||||
--app-bg: var(--bf-bg-page); /* #070D1D */
|
||||
--app-surface: var(--bf-bg-surface); /* #0B1020 */
|
||||
--app-surface-alt: var(--bf-bg-surface-alt); /* #192858 */
|
||||
--app-text: var(--bf-text-on-dark);
|
||||
--app-text-muted: var(--bf-text-on-dark-muted);
|
||||
--app-border: var(--bf-border-default);
|
||||
--app-link: var(--bf-color-cyan-400);
|
||||
--app-elevation: var(--bf-shadow-flare-soft); /* the signature flare */
|
||||
--app-input-bg: var(--bf-bg-page);
|
||||
--app-btn2-hover: var(--bf-action-secondary);
|
||||
/* A whisper of the signature cyan under a hovered row - enough to say
|
||||
"live", never enough to fight the text on it. */
|
||||
--app-row-hover: rgba(58, 188, 248, 0.07);
|
||||
/* The brand red is 3.22:1 on the dark surface. Lightened for dark only, so
|
||||
destructive actions clear AA in both themes rather than one. */
|
||||
--app-danger: #FF6B6B;
|
||||
--app-danger-hover-tint: rgba(255, 107, 107, 0.12);
|
||||
/* Same step-down as --app-link: --bf-border-accent is flat cyan-400 in
|
||||
every theme, which is ~2.16:1 on light backgrounds and fails the 3:1
|
||||
WCAG 1.4.11 floor for a focus indicator. */
|
||||
--app-focus-ring: var(--bf-color-cyan-400);
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
:root[data-theme='light'] {
|
||||
--app-bg: var(--bf-bg-page-light); /* #FFFFFF */
|
||||
--app-surface: var(--bf-color-neutral-100); /* #F6F6F6 */
|
||||
--app-surface-alt: var(--bf-color-neutral-100);
|
||||
--app-text: var(--bf-text-on-light);
|
||||
--app-text-muted: var(--bf-text-on-light-muted);
|
||||
--app-border: var(--bf-border-subtle); /* #D9D9D9 hairline */
|
||||
/* One shade darker so link text clears AA on white. */
|
||||
--app-link: var(--bf-color-cyan-600);
|
||||
--app-danger: #C7162B;
|
||||
--app-danger-hover-tint: rgba(199, 22, 43, 0.12);
|
||||
/* The flare mutes on white - never a cyan glow on a light surface. */
|
||||
--app-elevation: var(--bf-shadow-elevation-1);
|
||||
--app-input-bg: var(--bf-bg-page-light);
|
||||
--app-btn2-hover: var(--bf-color-neutral-100);
|
||||
--app-row-hover: rgba(55, 118, 190, 0.06);
|
||||
/* One shade darker, same reasoning as --app-link above. */
|
||||
--app-focus-ring: var(--bf-color-cyan-600);
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
/* System preference, used when the user has not chosen explicitly.
|
||||
`data-theme` is absent in that case, so this must not out-specify the
|
||||
explicit selectors above - hence :root:not([data-theme]). */
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root:not([data-theme]) {
|
||||
--app-bg: var(--bf-bg-page-light);
|
||||
--app-surface: var(--bf-color-neutral-100);
|
||||
--app-surface-alt: var(--bf-color-neutral-100);
|
||||
--app-text: var(--bf-text-on-light);
|
||||
--app-text-muted: var(--bf-text-on-light-muted);
|
||||
--app-border: var(--bf-border-subtle);
|
||||
--app-link: var(--bf-color-cyan-600);
|
||||
--app-danger: #C7162B;
|
||||
--app-danger-hover-tint: rgba(199, 22, 43, 0.12);
|
||||
--app-elevation: var(--bf-shadow-elevation-1);
|
||||
--app-input-bg: var(--bf-bg-page-light);
|
||||
--app-btn2-hover: var(--bf-color-neutral-100);
|
||||
--app-row-hover: rgba(55, 118, 190, 0.06);
|
||||
--app-focus-ring: var(--bf-color-cyan-600);
|
||||
color-scheme: light;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
/* FLARE portal - design tokens as CSS custom properties.
|
||||
* Hand-written; owned by the flare-ui crate (assets/tokens.css) and embedded as flare_ui::tokens::TOKENS_CSS.
|
||||
* Import as the root stylesheet; portal.css builds its components on these.
|
||||
* <link rel="stylesheet" href="tokens.css">
|
||||
* All values are flat (resolved) - semantic tokens reference primitives.
|
||||
*/
|
||||
|
||||
:root {
|
||||
/* --- Color - navy -------------------------------- */
|
||||
--bf-color-navy-50: #F6F6F6;
|
||||
--bf-color-navy-100: #D9D9D9;
|
||||
--bf-color-navy-200: #BABABA;
|
||||
--bf-color-navy-300: #9A9A9A;
|
||||
--bf-color-navy-400: #5D5D5D;
|
||||
--bf-color-navy-500: #295399;
|
||||
--bf-color-navy-600: #1E4E90;
|
||||
--bf-color-navy-700: #192858; /* core brand */
|
||||
--bf-color-navy-800: #0B1020;
|
||||
--bf-color-navy-900: #070D1D;
|
||||
--bf-color-navy-950: #050A16;
|
||||
|
||||
/* --- Color - cyan (signature flare) -------------- */
|
||||
--bf-color-cyan-400: #3ABCF8;
|
||||
--bf-color-cyan-500: #31A2D6;
|
||||
--bf-color-cyan-600: #3776BE;
|
||||
|
||||
/* --- Color - orange (accent) --------------------- */
|
||||
--bf-color-orange-500: #F26522;
|
||||
|
||||
/* --- Color - neutral ----------------------------- */
|
||||
--bf-color-neutral-0: #FFFFFF;
|
||||
--bf-color-neutral-100: #F6F6F6;
|
||||
--bf-color-neutral-200: #D9D9D9;
|
||||
--bf-color-neutral-300: #BABABA;
|
||||
--bf-color-neutral-400: #9A9A9A;
|
||||
--bf-color-neutral-500: #5D5D5D;
|
||||
--bf-color-neutral-600: #484848;
|
||||
--bf-color-neutral-700: #383838;
|
||||
--bf-color-neutral-800: #252525;
|
||||
--bf-color-neutral-900: #000000;
|
||||
|
||||
/* --- Color - feedback ---------------------------- */
|
||||
--bf-color-danger: #FF0202;
|
||||
--bf-color-warning: #F26522;
|
||||
--bf-color-info: #3ABCF8;
|
||||
|
||||
/* --- Semantic aliases (use these in product code) - */
|
||||
--bf-bg-page: var(--bf-color-navy-900);
|
||||
--bf-bg-page-light: var(--bf-color-neutral-0);
|
||||
--bf-bg-surface: var(--bf-color-navy-800);
|
||||
--bf-bg-surface-alt: var(--bf-color-navy-700);
|
||||
--bf-bg-surface-light: var(--bf-color-neutral-100);
|
||||
|
||||
--bf-text-on-dark: var(--bf-color-neutral-0);
|
||||
--bf-text-on-dark-muted: var(--bf-color-neutral-300);
|
||||
--bf-text-on-light: var(--bf-color-neutral-800);
|
||||
--bf-text-on-light-muted: var(--bf-color-neutral-500);
|
||||
--bf-text-link: var(--bf-color-cyan-400);
|
||||
--bf-text-brand: var(--bf-color-navy-700);
|
||||
|
||||
--bf-border-default: var(--bf-color-navy-700);
|
||||
--bf-border-subtle: var(--bf-color-neutral-200);
|
||||
--bf-border-accent: var(--bf-color-cyan-400);
|
||||
--bf-border-on-dark: var(--bf-color-neutral-0);
|
||||
|
||||
--bf-action-primary: var(--bf-color-cyan-400);
|
||||
--bf-action-primary-hover: var(--bf-color-cyan-500);
|
||||
--bf-action-primary-text: var(--bf-color-navy-900);
|
||||
--bf-action-secondary: var(--bf-color-navy-700);
|
||||
--bf-action-secondary-hover: var(--bf-color-navy-600);
|
||||
--bf-action-secondary-text: var(--bf-color-neutral-0);
|
||||
--bf-action-accent: var(--bf-color-orange-500);
|
||||
|
||||
/* --- Typography ----------------------------------
|
||||
* Free-substitute stack: Sora (Google Fonts) for display, Selawik (Microsoft's
|
||||
* open-source Segoe UI clone, SIL OFL 1.1, self-hosted from /fonts) for body.
|
||||
* Native brand fonts (Creato Display, Segoe UI) remain first in the stack so
|
||||
* licensed deployments don't require any token change. See fonts.md.
|
||||
*/
|
||||
--bf-font-display: 'Creato Display', 'Sora', 'Segoe UI', 'Selawik', system-ui, -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Arial, sans-serif;
|
||||
--bf-font-body: 'Segoe UI', 'Selawik', system-ui, -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Arial, sans-serif;
|
||||
|
||||
--bf-font-weight-regular: 400;
|
||||
--bf-font-weight-semibold: 600;
|
||||
--bf-font-weight-bold: 700;
|
||||
|
||||
--bf-text-xs: 12px;
|
||||
--bf-text-sm: 14px;
|
||||
--bf-text-base: 16px;
|
||||
--bf-text-md: 18px;
|
||||
--bf-text-lg: 20px;
|
||||
--bf-text-xl: 24px;
|
||||
--bf-text-2xl: 28px;
|
||||
--bf-text-3xl: 40px;
|
||||
--bf-text-4xl: 56px;
|
||||
|
||||
--bf-leading-tight: 1.0;
|
||||
--bf-leading-snug: 1.15;
|
||||
--bf-leading-normal: 1.25;
|
||||
--bf-leading-relaxed: 1.4;
|
||||
--bf-leading-loose: 1.6;
|
||||
--bf-leading-display: 1.1;
|
||||
|
||||
--bf-tracking-normal: 0;
|
||||
--bf-tracking-wide: 0.03em;
|
||||
--bf-tracking-wider: 0.3em;
|
||||
|
||||
/* --- Spacing (4-px base, 10-px friendly) --------- */
|
||||
--bf-space-0: 0;
|
||||
--bf-space-1: 4px;
|
||||
--bf-space-2: 8px;
|
||||
--bf-space-2_5:10px;
|
||||
--bf-space-3: 12px;
|
||||
--bf-space-4: 16px;
|
||||
--bf-space-5: 20px;
|
||||
--bf-space-6: 24px;
|
||||
--bf-space-8: 32px;
|
||||
--bf-space-9: 36px;
|
||||
--bf-space-10: 40px;
|
||||
--bf-space-13: 53px;
|
||||
--bf-space-16: 64px;
|
||||
--bf-space-20: 80px;
|
||||
--bf-space-24: 96px;
|
||||
|
||||
/* --- Layout -------------------------------------- */
|
||||
--bf-container-max: 1280px;
|
||||
--bf-gutter: 24px;
|
||||
--bf-gutter-mobile: 16px;
|
||||
--bf-section-y: 80px;
|
||||
--bf-section-y-mobile: 53px;
|
||||
|
||||
/* --- Radius ----------------------------------------
|
||||
* Square corners, everywhere (philosophy adopted 2026-07-14).
|
||||
* All steps resolve to 0 and are retained only so existing code
|
||||
* that references them renders square. Omit border-radius in new code.
|
||||
*/
|
||||
--bf-radius-none: 0;
|
||||
--bf-radius-xs: 0;
|
||||
--bf-radius-sm: 0;
|
||||
--bf-radius-md: 0;
|
||||
--bf-radius-lg: 0;
|
||||
--bf-radius-xl: 0;
|
||||
--bf-radius-2xl: 0;
|
||||
--bf-radius-3xl: 0;
|
||||
--bf-radius-pill: 0;
|
||||
|
||||
/* --- Shadows (signature flare glow) -------------- */
|
||||
--bf-shadow-flare-soft: 0 0 79px 0 rgba(58, 188, 248, 0.05);
|
||||
--bf-shadow-flare-medium: 0 0 29px 0 rgba(58, 188, 248, 0.50);
|
||||
--bf-shadow-flare-hover: 0 1px 22px 0 rgba(58, 188, 248, 0.40);
|
||||
--bf-shadow-flare-ring: 0 0 10.3px 1px #31A2D6, 0 0 10.9px 1px #31A2D6;
|
||||
--bf-shadow-elevation-1: 0 0 79px 0 rgba(0, 0, 0, 0.10);
|
||||
--bf-shadow-drift: 22px 0 92px 0 rgba(58, 188, 248, 0.10);
|
||||
|
||||
/* --- Breakpoints (also exposed for JS readers) ---- */
|
||||
--bf-bp-sm: 640px;
|
||||
--bf-bp-md: 768px;
|
||||
--bf-bp-lg: 1024px;
|
||||
--bf-bp-xl: 1280px;
|
||||
--bf-bp-2xl: 1536px;
|
||||
}
|
||||
|
||||
/* --- Reusable text styles ------------------------------------------------ */
|
||||
.bf-text-display-1 { font: var(--bf-font-weight-bold) var(--bf-text-4xl)/var(--bf-leading-display) var(--bf-font-display); letter-spacing: var(--bf-tracking-normal); }
|
||||
.bf-text-display-2 { font: var(--bf-font-weight-bold) var(--bf-text-3xl)/var(--bf-leading-display) var(--bf-font-display); letter-spacing: var(--bf-tracking-normal); }
|
||||
.bf-text-h2 { font: var(--bf-font-weight-semibold) var(--bf-text-2xl)/var(--bf-leading-relaxed) var(--bf-font-body); }
|
||||
.bf-text-h3 { font: var(--bf-font-weight-bold) var(--bf-text-xl)/var(--bf-leading-snug) var(--bf-font-body); }
|
||||
.bf-text-h4 { font: var(--bf-font-weight-bold) var(--bf-text-lg)/var(--bf-leading-normal) var(--bf-font-body); }
|
||||
.bf-text-lead { font: var(--bf-font-weight-regular) var(--bf-text-md)/var(--bf-leading-loose) var(--bf-font-body); letter-spacing: var(--bf-tracking-wide); }
|
||||
.bf-text-body { font: var(--bf-font-weight-regular) var(--bf-text-base)/var(--bf-leading-normal) var(--bf-font-body); }
|
||||
.bf-text-body-loose{ font: var(--bf-font-weight-regular) var(--bf-text-base)/var(--bf-leading-loose) var(--bf-font-body); letter-spacing: var(--bf-tracking-wide); }
|
||||
.bf-text-body-sm { font: var(--bf-font-weight-regular) var(--bf-text-sm)/var(--bf-leading-normal) var(--bf-font-body); }
|
||||
.bf-text-label { font: var(--bf-font-weight-semibold) var(--bf-text-sm)/var(--bf-leading-normal) var(--bf-font-body); }
|
||||
.bf-text-button { font: var(--bf-font-weight-semibold) var(--bf-text-base)/var(--bf-leading-normal) var(--bf-font-body); }
|
||||
.bf-text-caption { font: var(--bf-font-weight-regular) var(--bf-text-xs)/var(--bf-leading-relaxed) var(--bf-font-body); }
|
||||
.bf-text-eyebrow { font: var(--bf-font-weight-bold) var(--bf-text-xs)/var(--bf-leading-tight) var(--bf-font-body); letter-spacing: var(--bf-tracking-wider); text-transform: uppercase; }
|
||||
@@ -0,0 +1,59 @@
|
||||
/* Warden console compatibility layer (UI-4): maps the legacy app.css custom
|
||||
* properties onto the shared theme and token names so the console can drop its
|
||||
* own palette. Load after tokens.css and theme.css. Names with no shared
|
||||
* equivalent (brand chips, layout widths) keep fixed values.
|
||||
*/
|
||||
|
||||
:root {
|
||||
--radius: var(--bf-radius-none);
|
||||
--sp-1: var(--bf-space-1);
|
||||
--sp-2: var(--bf-space-2);
|
||||
--sp-3: var(--bf-space-3);
|
||||
--sp-4: var(--bf-space-4);
|
||||
--sp-6: var(--bf-space-6);
|
||||
--sp-8: var(--bf-space-8);
|
||||
--hair: 1px;
|
||||
--font-display: var(--bf-font-display);
|
||||
--font-body: var(--bf-font-body);
|
||||
|
||||
--bg: var(--app-bg);
|
||||
--surface: var(--app-surface);
|
||||
--surface-alt: var(--app-surface-alt);
|
||||
--border: var(--app-border);
|
||||
--text: var(--app-text);
|
||||
--text-muted: var(--app-text-muted);
|
||||
--accent: var(--app-link);
|
||||
--accent-ink: var(--bf-action-primary-text);
|
||||
--accent-soft: var(--app-row-hover);
|
||||
--crit: var(--app-danger);
|
||||
--focus: var(--app-focus-ring);
|
||||
|
||||
--flame: var(--bf-color-orange-500);
|
||||
--scrim: rgba(0, 0, 0, 0.55);
|
||||
--chip-dark: var(--bf-color-navy-800);
|
||||
--rail-w: 76px;
|
||||
--rail-narrow: 60px;
|
||||
--sidebar-w: 340px;
|
||||
}
|
||||
|
||||
/* Status colors have no shared token yet; values match the console palette. */
|
||||
:root,
|
||||
:root[data-theme='dark'] {
|
||||
--ok: #35C26A; --warn: #F2B441;
|
||||
--dot-ok: #35C26A; --dot-warn: #F2B441; --dot-crit: #F0555A;
|
||||
--dot-new: #3ABCF8; --dot-off: #5A6577;
|
||||
}
|
||||
|
||||
:root[data-theme='light'] {
|
||||
--ok: #1E8E4E; --warn: #9A6700;
|
||||
--dot-ok: #22B25A; --dot-warn: #E0A100; --dot-crit: #E5484D;
|
||||
--dot-new: #3776BE; --dot-off: #9AA3B2;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root:not([data-theme]) {
|
||||
--ok: #1E8E4E; --warn: #9A6700;
|
||||
--dot-ok: #22B25A; --dot-warn: #E0A100; --dot-crit: #E5484D;
|
||||
--dot-new: #3776BE; --dot-off: #9AA3B2;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::hint::black_box;
|
||||
|
||||
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
|
||||
use flare_ui::chart::{Chart, Series, Tier, TierSpec};
|
||||
|
||||
fn fixture(count: usize) -> Chart {
|
||||
Chart {
|
||||
id: "traffic".into(),
|
||||
label: "Network traffic".into(),
|
||||
series: (0..count)
|
||||
.map(|i| Series {
|
||||
key: format!("interface{i}"),
|
||||
label: format!("Interface {i}"),
|
||||
unit: "B/s".into(),
|
||||
color: "#3776BE".into(),
|
||||
})
|
||||
.collect(),
|
||||
tiers: [
|
||||
TierSpec { n: 60, step_s: 60 },
|
||||
TierSpec {
|
||||
n: 60,
|
||||
step_s: 3600,
|
||||
},
|
||||
TierSpec {
|
||||
n: 60,
|
||||
step_s: 86400,
|
||||
},
|
||||
],
|
||||
tier: Tier::Min,
|
||||
points: (0..count)
|
||||
.map(|i| {
|
||||
(
|
||||
format!("interface{i}"),
|
||||
(0..60)
|
||||
.map(|j| (j as f64 * 1000.0, (i + j) as f64))
|
||||
.collect(),
|
||||
)
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>(),
|
||||
}
|
||||
}
|
||||
|
||||
fn charts(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("chart_contract");
|
||||
for count in [2, 64] {
|
||||
let chart = fixture(count);
|
||||
group.bench_with_input(BenchmarkId::new("props", count), &chart, |b, chart| {
|
||||
b.iter(|| black_box(chart).props().unwrap())
|
||||
});
|
||||
group.bench_with_input(BenchmarkId::new("render", count), &chart, |b, chart| {
|
||||
b.iter(|| black_box(chart).render("/network/traffic").unwrap())
|
||||
});
|
||||
}
|
||||
group.finish();
|
||||
}
|
||||
|
||||
criterion_group!(benches, charts);
|
||||
criterion_main!(benches);
|
||||
@@ -0,0 +1,97 @@
|
||||
//! Action and approval block renderers (LD-06): buttons that post through htmx.
|
||||
//!
|
||||
//! Every action is a `<form method="post">` so it works without script; the
|
||||
//! `hx-post` attributes only upgrade it in place. Targets must be same-origin
|
||||
//! absolute paths (`/...`, not `//`), and each form carries the CSRF token the
|
||||
//! caller supplies. Text is escaped by maud and classes are allowlisted.
|
||||
|
||||
use maud::{html, Markup};
|
||||
|
||||
/// True when `path` is a same-origin absolute path safe to post to.
|
||||
pub fn safe_target(path: &str) -> bool {
|
||||
path.starts_with('/')
|
||||
&& !path.starts_with("//")
|
||||
&& !path.contains('\\')
|
||||
&& !path.chars().any(|c| c.is_control() || c.is_whitespace())
|
||||
}
|
||||
|
||||
/// Visual weight of an action button.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Tone {
|
||||
Normal,
|
||||
Primary,
|
||||
Danger,
|
||||
}
|
||||
|
||||
impl Tone {
|
||||
fn class(self) -> &'static str {
|
||||
match self {
|
||||
Tone::Normal => "bf-btn bf-text-button",
|
||||
Tone::Primary => "bf-btn bf-btn-primary bf-text-button",
|
||||
Tone::Danger => "bf-btn bf-btn-danger bf-text-button",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One action button. Returns `None` for an unsafe target so a bad schema
|
||||
/// entry renders nothing instead of a post to another origin.
|
||||
pub fn action_button(
|
||||
target: &str,
|
||||
label: &str,
|
||||
tone: Tone,
|
||||
csrf: &str,
|
||||
confirm: Option<&str>,
|
||||
) -> Option<Markup> {
|
||||
if !safe_target(target) {
|
||||
return None;
|
||||
}
|
||||
Some(html! {
|
||||
form class="bf-action" method="post" action=(target) hx-post=(target) hx-swap="outerHTML" {
|
||||
input type="hidden" name="csrf" value=(csrf);
|
||||
@if let Some(c) = confirm {
|
||||
p class="bf-action-confirm bf-text-body" { (c) }
|
||||
}
|
||||
button type="submit" class=(tone.class()) { (label) }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// A pending approval awaiting a decision.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Approval {
|
||||
pub id: String,
|
||||
pub summary: String,
|
||||
pub requested_by: String,
|
||||
}
|
||||
|
||||
/// Approval list: each row has approve and deny buttons posting to
|
||||
/// `<base>/<id>/approve` and `<base>/<id>/deny`. Ids outside `[A-Za-z0-9_-]`
|
||||
/// are skipped so they cannot alter the path. The empty list shows a note.
|
||||
pub fn approvals(base: &str, items: &[Approval], csrf: &str) -> Markup {
|
||||
let usable: Vec<&Approval> = items
|
||||
.iter()
|
||||
.filter(|a| {
|
||||
!a.id.is_empty()
|
||||
&& a.id
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
|
||||
})
|
||||
.collect();
|
||||
html! {
|
||||
@if usable.is_empty() || !safe_target(base) {
|
||||
p class="bf-note bf-text-body" { "No approvals pending." }
|
||||
} @else {
|
||||
ul class="bf-approvals" {
|
||||
@for a in usable {
|
||||
li class="bf-approval" {
|
||||
span class="bf-text-body" { (a.summary) }
|
||||
span class="bf-text-label" { "Requested by " (a.requested_by) }
|
||||
@let b = base.trim_end_matches('/');
|
||||
(action_button(&format!("{b}/{}/approve", a.id), "Approve", Tone::Primary, csrf, None).unwrap_or_default())
|
||||
(action_button(&format!("{b}/{}/deny", a.id), "Deny", Tone::Danger, csrf, Some("Deny this request?")).unwrap_or_default())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
//! Page assets and the plain-HTTP lint (UI-6, d04).
|
||||
//!
|
||||
//! A page declares the scripts and stylesheets it needs as [`PageAssets`];
|
||||
//! [`PageAssets::head`] renders the tags and [`lint`] checks the declaration
|
||||
//! against the delivery context. Consoles are often served over plain HTTP on
|
||||
//! a site LAN, so secure-context-only browser APIs and an over-large SSE
|
||||
//! budget are lint errors there.
|
||||
|
||||
use maud::{html, Markup};
|
||||
|
||||
use crate::live::LIVE_JS;
|
||||
|
||||
/// Islands script (table sort in the URL, column resize).
|
||||
pub const ISLANDS_JS: &str = include_str!("../assets/js/islands.js");
|
||||
|
||||
/// Page glue: stream, stale marker, charts, table sort, htmx CSRF header.
|
||||
pub const BOOT_JS: &str = include_str!("../assets/js/boot.js");
|
||||
|
||||
/// Chart island and reading glue (draws series, writes pushed values).
|
||||
pub const CHART_JS: &str = include_str!("../assets/js/chart.js");
|
||||
|
||||
/// Browsers cap plain HTTP/1.1 connections per origin at 6. One is kept free
|
||||
/// for page loads and API calls, so at most 5 SSE streams per page.
|
||||
pub const PLAIN_HTTP_SSE_BUDGET: usize = 5;
|
||||
|
||||
/// Browser APIs that exist only in a secure context (HTTPS or localhost).
|
||||
pub const SECURE_ONLY_APIS: &[&str] = &[
|
||||
"crypto.subtle",
|
||||
"navigator.clipboard",
|
||||
"navigator.serviceWorker",
|
||||
"navigator.mediaDevices",
|
||||
"navigator.geolocation",
|
||||
];
|
||||
|
||||
/// What one page loads.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct PageAssets {
|
||||
/// Stylesheet URLs, in order.
|
||||
pub styles: Vec<String>,
|
||||
/// Script URLs, in order. All are emitted `defer`.
|
||||
pub scripts: Vec<String>,
|
||||
/// SSE stream URLs the page opens.
|
||||
pub streams: Vec<String>,
|
||||
}
|
||||
|
||||
impl PageAssets {
|
||||
/// Head tags: stylesheets, then deferred scripts.
|
||||
pub fn head(&self) -> Markup {
|
||||
html! {
|
||||
@for s in &self.styles { link rel="stylesheet" href=(s); }
|
||||
@for s in &self.scripts { script src=(s) defer {} }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the page is delivered.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Delivery {
|
||||
PlainHttp,
|
||||
Secure,
|
||||
}
|
||||
|
||||
/// One lint finding.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Finding {
|
||||
/// More SSE streams than [`PLAIN_HTTP_SSE_BUDGET`] on plain HTTP.
|
||||
SseBudget { streams: usize, budget: usize },
|
||||
/// A script source uses a secure-context-only API.
|
||||
SecureOnlyApi { script: String, api: &'static str },
|
||||
}
|
||||
|
||||
/// Lints a page. `script_source` returns the text of a script URL (the caller
|
||||
/// reads its own static files); unknown scripts return `None` and are skipped.
|
||||
pub fn lint(
|
||||
assets: &PageAssets,
|
||||
delivery: Delivery,
|
||||
script_source: &dyn Fn(&str) -> Option<String>,
|
||||
) -> Vec<Finding> {
|
||||
let mut out = Vec::new();
|
||||
if delivery == Delivery::Secure {
|
||||
return out;
|
||||
}
|
||||
if assets.streams.len() > PLAIN_HTTP_SSE_BUDGET {
|
||||
out.push(Finding::SseBudget {
|
||||
streams: assets.streams.len(),
|
||||
budget: PLAIN_HTTP_SSE_BUDGET,
|
||||
});
|
||||
}
|
||||
for s in &assets.scripts {
|
||||
let Some(src) = script_source(s) else {
|
||||
continue;
|
||||
};
|
||||
for api in SECURE_ONLY_APIS {
|
||||
if src.contains(api) {
|
||||
out.push(Finding::SecureOnlyApi {
|
||||
script: s.clone(),
|
||||
api,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The crate's own scripts never use a secure-context-only API.
|
||||
pub fn builtin_script(name: &str) -> Option<&'static str> {
|
||||
match name {
|
||||
"live.js" => Some(LIVE_JS),
|
||||
"islands.js" => Some(ISLANDS_JS),
|
||||
"chart.js" => Some(CHART_JS),
|
||||
"boot.js" => Some(BOOT_JS),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pa(scripts: &[&str], streams: usize) -> PageAssets {
|
||||
PageAssets {
|
||||
styles: vec!["/a/tokens.css".into()],
|
||||
scripts: scripts.iter().map(|s| s.to_string()).collect(),
|
||||
streams: (0..streams).map(|i| format!("/s/{i}")).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_renders_styles_then_deferred_scripts() {
|
||||
let h = pa(&["live.js"], 0).head().into_string();
|
||||
assert_eq!(
|
||||
h,
|
||||
r#"<link rel="stylesheet" href="/a/tokens.css"><script src="live.js" defer></script>"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_scripts_pass_plain_http_lint() {
|
||||
let a = pa(&["live.js", "islands.js", "chart.js", "boot.js"], 5);
|
||||
let f = lint(&a, Delivery::PlainHttp, &|s| {
|
||||
builtin_script(s).map(String::from)
|
||||
});
|
||||
assert!(f.is_empty(), "{f:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chart_script_is_ascii_and_exports() {
|
||||
assert!(BOOT_JS.is_ascii());
|
||||
assert!(BOOT_JS.contains("FlareBoot"));
|
||||
assert!(CHART_JS.is_ascii());
|
||||
assert!(CHART_JS.contains("FlareChart"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sse_budget_is_enforced_on_plain_http_only() {
|
||||
let a = pa(&[], 6);
|
||||
assert_eq!(
|
||||
lint(&a, Delivery::PlainHttp, &|_| None),
|
||||
vec![Finding::SseBudget {
|
||||
streams: 6,
|
||||
budget: 5
|
||||
}]
|
||||
);
|
||||
assert!(lint(&a, Delivery::Secure, &|_| None).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secure_only_api_is_flagged_on_plain_http() {
|
||||
let a = pa(&["x.js"], 0);
|
||||
let src = |_: &str| Some("navigator.clipboard.writeText(1)".to_string());
|
||||
assert_eq!(
|
||||
lint(&a, Delivery::PlainHttp, &src),
|
||||
vec![Finding::SecureOnlyApi {
|
||||
script: "x.js".into(),
|
||||
api: "navigator.clipboard"
|
||||
}]
|
||||
);
|
||||
assert!(lint(&a, Delivery::Secure, &src).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! `nav-json <schema.json>`: prints `nav.json` for an effective (or base)
|
||||
//! schema document. Exit 2 on a usage or parse error.
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let (Some(path), None) = (args.next(), args.next()) else {
|
||||
eprintln!("usage: nav-json <schema.json>");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let text = match std::fs::read_to_string(&path) {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
eprintln!("nav-json: {path}: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let doc = match wschema::model::Document::from_json(&text) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
eprintln!("nav-json: {path}: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
match serde_json::to_string_pretty(&flare_ui::nav::nav_json(&doc.menus)) {
|
||||
Ok(s) => {
|
||||
println!("{s}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("nav-json: {e}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
//! Chart island props, server navigation and accessible latest values (D63).
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use maud::{html, Markup};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// The retained renderer displays 60 samples at each tier.
|
||||
pub const SAMPLES: usize = 60;
|
||||
pub const MAX_SERIES: usize = 64;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Tier {
|
||||
Min,
|
||||
Hour,
|
||||
Day,
|
||||
}
|
||||
|
||||
impl Tier {
|
||||
pub const ALL: [Self; 3] = [Self::Min, Self::Hour, Self::Day];
|
||||
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Min => "min",
|
||||
Self::Hour => "hour",
|
||||
Self::Day => "day",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TierSpec {
|
||||
pub n: usize,
|
||||
pub step_s: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Series {
|
||||
pub key: String,
|
||||
pub label: String,
|
||||
pub unit: String,
|
||||
/// Three or six hexadecimal RGB digits, prefixed with `#`.
|
||||
pub color: String,
|
||||
}
|
||||
|
||||
/// Timestamps are milliseconds since the Unix epoch, as in live readings.
|
||||
pub type Point = (f64, f64);
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Chart {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub series: Vec<Series>,
|
||||
/// Min, hour and day metadata, in [`Tier::ALL`] order.
|
||||
pub tiers: [TierSpec; 3],
|
||||
pub tier: Tier,
|
||||
/// Selected-tier samples, oldest first. Empty or missing series are valid.
|
||||
pub points: BTreeMap<String, Vec<Point>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
Identity,
|
||||
Series,
|
||||
Tiers,
|
||||
Points,
|
||||
Path,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Identity => "invalid chart identity",
|
||||
Self::Series => "invalid chart series",
|
||||
Self::Tiers => "invalid chart tiers",
|
||||
Self::Points => "invalid chart samples",
|
||||
Self::Path => "invalid chart page path",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
fn text(s: &str, max: usize) -> bool {
|
||||
!s.is_empty() && s.len() <= max && !s.chars().any(char::is_control)
|
||||
}
|
||||
|
||||
impl Chart {
|
||||
pub fn validate(&self) -> Result<(), Error> {
|
||||
if !text(&self.id, 128) || !text(&self.label, 256) {
|
||||
return Err(Error::Identity);
|
||||
}
|
||||
if self.series.is_empty() || self.series.len() > MAX_SERIES {
|
||||
return Err(Error::Series);
|
||||
}
|
||||
let mut keys = BTreeSet::new();
|
||||
for s in &self.series {
|
||||
let hex = s.color.strip_prefix('#').unwrap_or("");
|
||||
if !text(&s.key, 256)
|
||||
|| !text(&s.label, 256)
|
||||
|| s.unit.len() > 64
|
||||
|| s.unit.chars().any(char::is_control)
|
||||
|| !matches!(hex.len(), 3 | 6)
|
||||
|| !hex.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
|| !keys.insert(s.key.as_str())
|
||||
{
|
||||
return Err(Error::Series);
|
||||
}
|
||||
}
|
||||
if self.tiers.iter().any(|t| t.n != SAMPLES || t.step_s == 0) {
|
||||
return Err(Error::Tiers);
|
||||
}
|
||||
for (key, points) in &self.points {
|
||||
if !keys.contains(key.as_str())
|
||||
|| points.len() > SAMPLES
|
||||
|| points.iter().any(|(t, v)| !t.is_finite() || !v.is_finite())
|
||||
|| points.windows(2).any(|p| p[0].0 >= p[1].0)
|
||||
{
|
||||
return Err(Error::Points);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn props(&self) -> Result<Value, Error> {
|
||||
self.validate()?;
|
||||
let tiers: BTreeMap<_, _> = Tier::ALL
|
||||
.iter()
|
||||
.zip(&self.tiers)
|
||||
.map(|(tier, spec)| (tier.as_str(), json!({ "n": spec.n, "step_s": spec.step_s })))
|
||||
.collect();
|
||||
Ok(json!({
|
||||
"id": self.id,
|
||||
"series": self.series.iter().map(|s| json!({
|
||||
"key": s.key, "label": s.label, "unit": s.unit, "color": s.color
|
||||
})).collect::<Vec<_>>(),
|
||||
"tiers": tiers, "tier": self.tier.as_str(), "points": self.points,
|
||||
}))
|
||||
}
|
||||
|
||||
/// `path` is the canonical page path without a query or fragment.
|
||||
/// Tier changes remain normal links when JavaScript is unavailable.
|
||||
pub fn render(&self, path: &str) -> Result<Markup, Error> {
|
||||
if !path.starts_with('/')
|
||||
|| path.starts_with("//")
|
||||
|| path
|
||||
.chars()
|
||||
.any(|c| c.is_control() || matches!(c, '\\' | '?' | '#'))
|
||||
{
|
||||
return Err(Error::Path);
|
||||
}
|
||||
let props = self.props()?.to_string();
|
||||
Ok(html! {
|
||||
figure id=(self.id) class="bf-chart" data-live data-island="chart" data-chart=(props) {
|
||||
figcaption class="bf-text-label" { (self.label) }
|
||||
nav aria-label="Chart tier" {
|
||||
@for tier in Tier::ALL {
|
||||
a href=(crate::url::with_query(path, [("tier", tier.as_str())], &[]))
|
||||
aria-current=[(tier == self.tier).then_some("page")] { (tier.as_str()) }
|
||||
}
|
||||
}
|
||||
canvas class="bf-chart-canvas" role="img" aria-label=(self.label) {}
|
||||
table class="bf-vh" {
|
||||
caption { (self.label) " latest values" }
|
||||
thead { tr { th scope="col" { "Series" } th scope="col" { "Value" } } }
|
||||
tbody {
|
||||
@for series in &self.series {
|
||||
tr {
|
||||
th scope="row" { (series.label) }
|
||||
td data-chart-value=(series.key) {
|
||||
@if let Some((_, value)) = self.points.get(&series.key).and_then(|p| p.last()) {
|
||||
(value)
|
||||
} @else { "--" }
|
||||
" " (series.unit)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Shared HTML components (UI-4), rendered with maud.
|
||||
//!
|
||||
//! Every class a component emits is in the stylesheet allowlist
|
||||
//! ([`crate::tokens::class_allowed`]); a test renders each component and
|
||||
//! checks that. Text is escaped by maud.
|
||||
|
||||
use maud::{html, Markup};
|
||||
|
||||
/// Severity of a [`badge`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Level {
|
||||
Ok,
|
||||
Warn,
|
||||
Err,
|
||||
}
|
||||
|
||||
impl Level {
|
||||
fn class(self) -> &'static str {
|
||||
match self {
|
||||
Level::Ok => "bf-badge bf-badge-ok",
|
||||
Level::Warn => "bf-badge bf-badge-warn",
|
||||
Level::Err => "bf-badge bf-badge-err",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A status badge.
|
||||
pub fn badge(level: Level, text: &str) -> Markup {
|
||||
html! { span class=(level.class()) { (text) } }
|
||||
}
|
||||
|
||||
/// A link styled as a button.
|
||||
pub fn button_link(href: &str, label: &str, primary: bool) -> Markup {
|
||||
let class = if primary {
|
||||
"bf-btn bf-btn-primary bf-text-button"
|
||||
} else {
|
||||
"bf-btn bf-text-button"
|
||||
};
|
||||
html! { a class=(class) href=(href) { (label) } }
|
||||
}
|
||||
|
||||
/// A titled card around caller-supplied content.
|
||||
pub fn card(title: &str, body: Markup) -> Markup {
|
||||
html! {
|
||||
section class="bf-card" {
|
||||
h3 class="bf-card-title bf-text-h3" { (title) }
|
||||
(body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A plain table. `stale` dims it (the SSE client sets this on disconnect).
|
||||
pub fn table(headers: &[&str], rows: &[Vec<String>], stale: bool) -> Markup {
|
||||
let class = if stale {
|
||||
"bf-table bf-stale"
|
||||
} else {
|
||||
"bf-table"
|
||||
};
|
||||
html! {
|
||||
table class=(class) {
|
||||
thead { tr { @for h in headers { th class="bf-text-label" { (h) } } } }
|
||||
tbody { @for r in rows { tr { @for c in r { td class="bf-text-body-sm" { (c) } } } } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::tokens::class_allowed;
|
||||
|
||||
fn classes(html: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut rest = html;
|
||||
while let Some(i) = rest.find("class=\"") {
|
||||
rest = &rest[i + 7..];
|
||||
let end = rest.find('"').unwrap();
|
||||
out.extend(rest[..end].split_whitespace().map(String::from));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_emitted_class_is_allowed() {
|
||||
let rows = vec![vec!["a".to_string(), "b".to_string()]];
|
||||
let outs = [
|
||||
badge(Level::Ok, "up"),
|
||||
badge(Level::Warn, "w"),
|
||||
badge(Level::Err, "e"),
|
||||
button_link("/x", "Go", true),
|
||||
button_link("/x", "Go", false),
|
||||
card("T", html! { p { "x" } }),
|
||||
table(&["A", "B"], &rows, false),
|
||||
table(&["A", "B"], &rows, true),
|
||||
];
|
||||
for o in outs {
|
||||
let s = o.into_string();
|
||||
let cs = classes(&s);
|
||||
assert!(!cs.is_empty(), "{s}");
|
||||
for c in cs {
|
||||
assert!(class_allowed(&c), "class {c} not allowed in {s}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_is_escaped() {
|
||||
let s = badge(Level::Err, "<script>").into_string();
|
||||
assert!(s.contains("<script>") && !s.contains("<script>"));
|
||||
let s = button_link("/x?a=1&b=2", "a\"b", false).into_string();
|
||||
assert!(s.contains("&") && s.contains("""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_table_is_marked() {
|
||||
let s = table(&["A"], &[], true).into_string();
|
||||
assert!(s.contains("bf-stale"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! The display-type list as a versioned file.
|
||||
//!
|
||||
//! `wschema::display::REGISTRY` is the source of truth. This module renders it
|
||||
//! to `docs/display-types.json`, the file generators in other repos read (the
|
||||
//! panel table generator and the golden HTML cases). A test keeps the
|
||||
//! committed file equal to the registry, so a new display type cannot ship
|
||||
//! without the file moving with it.
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use wschema::display::{level, Bind, BLOCK_KINDS, REGISTRY};
|
||||
|
||||
/// Snake-case token of a bind kind, as the file spells it.
|
||||
pub fn bind_token(b: Bind) -> &'static str {
|
||||
match b {
|
||||
Bind::Str => "str",
|
||||
Bind::Enum => "enum",
|
||||
Bind::Int => "int",
|
||||
Bind::IntSet => "int_set",
|
||||
Bind::Bool => "bool",
|
||||
Bind::Secret => "secret",
|
||||
Bind::List => "list",
|
||||
Bind::Map => "map",
|
||||
Bind::MapEntry => "map_entry",
|
||||
Bind::Reading => "reading",
|
||||
Bind::Action => "action",
|
||||
Bind::Block => "block",
|
||||
}
|
||||
}
|
||||
|
||||
/// `{"display_api", "types": [{"id", "binds", "since"}], "block_kinds"}`,
|
||||
/// in registry order. Rows are only ever added.
|
||||
pub fn display_types_json() -> Value {
|
||||
let types: Vec<Value> = REGISTRY
|
||||
.iter()
|
||||
.map(|d| {
|
||||
json!({
|
||||
"id": d.id,
|
||||
"binds": d.binds.iter().map(|b| bind_token(*b)).collect::<Vec<_>>(),
|
||||
"since": d.since,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
json!({
|
||||
"display_api": level(),
|
||||
"types": types,
|
||||
"block_kinds": BLOCK_KINDS,
|
||||
})
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
//! Shared UI crate for FLARE and the Warden console.
|
||||
//!
|
||||
//! - [`display_types`]: the versioned display-type list (`docs/display-types.json`).
|
||||
//! - [`nav`]: evaluates the schema's menu nodes for one viewer and emits
|
||||
//! `nav.json` (d04 section 4.1).
|
||||
//! - [`url`]: URL builders for the console and FLARE route tables, and the
|
||||
//! closed query-parameter set (d04 sections 4.2, 4.3).
|
||||
//! - [`components`]: maud components that emit only allowlisted classes.
|
||||
//! - [`actions`]: action buttons and approval lists (htmx upgrade over plain forms).
|
||||
//! - [`assets`]: page asset declarations, head tags and the plain-HTTP lint.
|
||||
//! - [`live`]: the SSE client script (ring, caps, reconnect, stale marker).
|
||||
//! - [`readings`]: live reading and block renderers.
|
||||
//! - [`chart`]: typed chart props, tier links and latest-value fallback.
|
||||
//! - [`render`]: renders schema settings by display type and validates forms.
|
||||
//! - [`shell`]: page shell (sidebar, tab strip, main area).
|
||||
//! - [`tokens`]: design tokens stylesheet and the CSS class allowlist.
|
||||
//! - [`resolve`]: maps a request path to a route, with canonical redirects
|
||||
//! and the `#/` bookmark rule (d04 sections 4.2, 4.3).
|
||||
//!
|
||||
//! Every function is pure: no I/O, no environment.
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod actions;
|
||||
pub mod assets;
|
||||
pub mod chart;
|
||||
pub mod components;
|
||||
pub mod display_types;
|
||||
pub mod live;
|
||||
pub mod nav;
|
||||
pub mod readings;
|
||||
pub mod render;
|
||||
pub mod resolve;
|
||||
pub mod shell;
|
||||
pub mod studio;
|
||||
pub mod tokens;
|
||||
pub mod url;
|
||||
|
||||
/// Crate name, used by consumers to check which pin they vendored.
|
||||
pub const NAME: &str = "flare-ui";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn name_is_stable() {
|
||||
assert_eq!(NAME, "flare-ui");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Live-data client script (UI-6).
|
||||
//!
|
||||
//! [`LIVE_JS`] is the SSE client served as a static asset: bounded ring per
|
||||
//! series, capped series count, reconnect with capped exponential backoff,
|
||||
//! and a stale marker (`bf-stale` on every `[data-live]` element).
|
||||
|
||||
/// The client script, byte for byte.
|
||||
pub const LIVE_JS: &str = include_str!("../assets/js/live.js");
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn script_is_ascii_and_exports_live() {
|
||||
assert!(LIVE_JS.is_ascii());
|
||||
assert!(LIVE_JS.contains("FlareLive"));
|
||||
assert!(LIVE_JS.contains("bf-stale"));
|
||||
}
|
||||
}
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
//! Navigation model: one evaluation of the schema menus per viewer.
|
||||
//!
|
||||
//! The menu nodes come from the effective schema (`wschema::model::Menu`).
|
||||
//! [`visible`] keeps what the current surface, capabilities, installed apps
|
||||
//! and principal allow, orders it, and attaches the canonical href of every
|
||||
//! tab. [`nav_json`] emits the unfiltered nav listing that flow tooling and
|
||||
//! the browser route table read.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use wschema::model::{Menu, MenuRequires, Surface};
|
||||
|
||||
use crate::url::Routes;
|
||||
|
||||
/// Band used when a section does not set one (core).
|
||||
pub const DEFAULT_BAND: i64 = 1;
|
||||
|
||||
/// What the viewer may see. The page-level grant is the permission check of
|
||||
/// d04 7.3; the nav only asks whether a page shows the viewer anything.
|
||||
pub trait Principal {
|
||||
/// True when the viewer may see at least one block of `page`.
|
||||
fn may_view_page(&self, page: &str) -> bool;
|
||||
}
|
||||
|
||||
/// A principal that may view every page (Warden console tests, panel).
|
||||
pub struct AllowAll;
|
||||
|
||||
impl Principal for AllowAll {
|
||||
fn may_view_page(&self, _page: &str) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of names (platform capabilities or installed app ids).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct NameSet(BTreeSet<String>);
|
||||
|
||||
impl NameSet {
|
||||
pub fn new<I, S>(names: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: Into<String>,
|
||||
{
|
||||
NameSet(names.into_iter().map(Into::into).collect())
|
||||
}
|
||||
|
||||
pub fn contains(&self, name: &str) -> bool {
|
||||
self.0.contains(name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Platform capabilities (`rs485-bus`, `relay-io`, ...).
|
||||
pub type CapSet = NameSet;
|
||||
/// Installed and enabled apps from the app manager.
|
||||
pub type AppSet = NameSet;
|
||||
|
||||
/// Everything `visible` needs about the viewer and the device.
|
||||
pub struct NavContext<'a> {
|
||||
pub surface: Surface,
|
||||
pub principal: &'a dyn Principal,
|
||||
pub caps: &'a CapSet,
|
||||
pub apps: &'a AppSet,
|
||||
/// Builds the tab hrefs; carries the route prefix of the surface.
|
||||
pub routes: &'a Routes,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct VisibleTab {
|
||||
pub slug: String,
|
||||
pub title: String,
|
||||
pub page: String,
|
||||
pub href: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct VisibleSection {
|
||||
pub slug: String,
|
||||
pub title: String,
|
||||
pub icon: String,
|
||||
pub tabs: Vec<VisibleTab>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct VisibleNav {
|
||||
pub sections: Vec<VisibleSection>,
|
||||
}
|
||||
|
||||
impl VisibleNav {
|
||||
/// The section with this slug.
|
||||
pub fn section(&self, slug: &str) -> Option<&VisibleSection> {
|
||||
self.sections.iter().find(|s| s.slug == slug)
|
||||
}
|
||||
|
||||
/// `(section, tab)` slugs of the first visible tab of the first visible
|
||||
/// section: the target of `GET /`.
|
||||
pub fn first_tab(&self) -> Option<(&str, &str)> {
|
||||
let s = self.sections.first()?;
|
||||
let t = s.tabs.first()?;
|
||||
Some((&s.slug, &t.slug))
|
||||
}
|
||||
}
|
||||
|
||||
/// Sort key shared by sections and tabs: band, order, case-folded title, id.
|
||||
fn sort_key(m: &Menu) -> (i64, i64, String, String) {
|
||||
(
|
||||
m.band.unwrap_or(DEFAULT_BAND),
|
||||
m.order.unwrap_or(0),
|
||||
m.title.to_ascii_lowercase(),
|
||||
m.id.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
fn requires_hold(req: &Option<MenuRequires>, cx: &NavContext) -> bool {
|
||||
let Some(r) = req else { return true };
|
||||
r.capabilities.iter().all(|c| cx.caps.contains(c))
|
||||
&& (r.any.is_empty() || r.any.iter().any(|a| cx.apps.contains(a)))
|
||||
}
|
||||
|
||||
/// Surfaces a node appears on. A tab without its own list inherits the
|
||||
/// section's; a section without one appears everywhere.
|
||||
fn effective_surfaces(tab: Option<&Menu>, section: &Menu) -> BTreeSet<Surface> {
|
||||
let list = tab
|
||||
.and_then(|t| t.surfaces.as_ref())
|
||||
.or(section.surfaces.as_ref());
|
||||
match list {
|
||||
Some(v) => v.iter().copied().collect(),
|
||||
None => [Surface::Panel, Surface::Web, Surface::Flare]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn split_id(id: &str) -> (&str, Option<&str>) {
|
||||
match id.split_once('/') {
|
||||
Some((s, t)) => (s, Some(t)),
|
||||
None => (id, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Groups menu nodes into `(section, tabs)`; a tab whose section node is
|
||||
/// missing is dropped (lint reports it).
|
||||
fn group(menus: &[Menu]) -> Vec<(&Menu, Vec<&Menu>)> {
|
||||
let mut tabs: BTreeMap<&str, Vec<&Menu>> = BTreeMap::new();
|
||||
for m in menus {
|
||||
if let (sec, Some(_)) = split_id(&m.id) {
|
||||
tabs.entry(sec).or_default().push(m);
|
||||
}
|
||||
}
|
||||
menus
|
||||
.iter()
|
||||
.filter(|m| split_id(&m.id).1.is_none())
|
||||
.map(|s| (s, tabs.remove(s.id.as_str()).unwrap_or_default()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Evaluates the menus for one viewer. Pure.
|
||||
///
|
||||
/// A section stays when the surface is in its `surfaces`, its `requires`
|
||||
/// hold and at least one tab is visible. A tab stays when the surface is in
|
||||
/// its effective `surfaces`, its own and its section's `requires` hold, it
|
||||
/// names a page and the principal may see that page.
|
||||
pub fn visible(menus: &[Menu], cx: &NavContext) -> VisibleNav {
|
||||
let mut grouped = group(menus);
|
||||
grouped.sort_by_key(|(s, _)| sort_key(s));
|
||||
let mut sections = Vec::new();
|
||||
for (sec, mut tabs) in grouped {
|
||||
if !effective_surfaces(None, sec).contains(&cx.surface) || !requires_hold(&sec.requires, cx)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
tabs.sort_by_key(|t| sort_key(t));
|
||||
let tabs: Vec<VisibleTab> = tabs
|
||||
.into_iter()
|
||||
.filter(|t| effective_surfaces(Some(t), sec).contains(&cx.surface))
|
||||
.filter(|t| requires_hold(&t.requires, cx))
|
||||
.filter_map(|t| {
|
||||
let page = t.page.as_ref()?;
|
||||
cx.principal.may_view_page(page).then(|| VisibleTab {
|
||||
slug: t.slug.clone(),
|
||||
title: t.title.clone(),
|
||||
page: page.clone(),
|
||||
href: cx.routes.page(&sec.slug, &t.slug),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if tabs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
sections.push(VisibleSection {
|
||||
slug: sec.slug.clone(),
|
||||
title: sec.title.clone(),
|
||||
icon: sec.icon.clone().unwrap_or_default(),
|
||||
tabs,
|
||||
});
|
||||
}
|
||||
VisibleNav { sections }
|
||||
}
|
||||
|
||||
fn surface_names(set: &BTreeSet<Surface>) -> Vec<&'static str> {
|
||||
set.iter()
|
||||
.map(|s| match s {
|
||||
Surface::Panel => "panel",
|
||||
Surface::Web => "web",
|
||||
Surface::Flare => "flare",
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The `nav.json` document: every section and tab of the schema in rail
|
||||
/// order, unfiltered by viewer, with the surfaces each appears on.
|
||||
///
|
||||
/// Shape: `{"sections": [{"slug", "title", "icon", "band", "order",
|
||||
/// "surfaces", "tabs": [{"slug", "title", "page", "surfaces"}]}]}`.
|
||||
/// Flow tooling reads only `slug` and `title`; the browser route table also
|
||||
/// reads `page` and `surfaces`. A tab without a page is listed with
|
||||
/// `"page": null`.
|
||||
pub fn nav_json(menus: &[Menu]) -> Value {
|
||||
let mut grouped = group(menus);
|
||||
grouped.sort_by_key(|(s, _)| sort_key(s));
|
||||
let sections: Vec<Value> = grouped
|
||||
.into_iter()
|
||||
.map(|(sec, mut tabs)| {
|
||||
tabs.sort_by_key(|t| sort_key(t));
|
||||
let tabs: Vec<Value> = tabs
|
||||
.into_iter()
|
||||
.map(|t| {
|
||||
json!({
|
||||
"slug": t.slug,
|
||||
"title": t.title,
|
||||
"page": t.page,
|
||||
"surfaces": surface_names(&effective_surfaces(Some(t), sec)),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
json!({
|
||||
"slug": sec.slug,
|
||||
"title": sec.title,
|
||||
"icon": sec.icon,
|
||||
"band": sec.band.unwrap_or(DEFAULT_BAND),
|
||||
"order": sec.order.unwrap_or(0),
|
||||
"surfaces": surface_names(&effective_surfaces(None, sec)),
|
||||
"tabs": tabs,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
json!({ "sections": sections })
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//! Reading and block renderers (LD-06): live values from data to HTML.
|
||||
//!
|
||||
//! Readings carry `data-live` so the stale marker in `live.js` can grey them
|
||||
//! when the stream drops, and `data-key` so a push can find the element.
|
||||
//! Text is escaped by maud and every class is in the stylesheet allowlist.
|
||||
|
||||
use maud::{html, Markup};
|
||||
|
||||
/// Severity of a status reading.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Level {
|
||||
Ok,
|
||||
Warn,
|
||||
Err,
|
||||
}
|
||||
|
||||
impl Level {
|
||||
fn class(self) -> &'static str {
|
||||
match self {
|
||||
Level::Ok => "bf-badge bf-badge-ok",
|
||||
Level::Warn => "bf-badge bf-badge-warn",
|
||||
Level::Err => "bf-badge bf-badge-err",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One live reading. `value` is `None` before the first sample.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Reading {
|
||||
pub key: String,
|
||||
pub label: String,
|
||||
pub value: Option<f64>,
|
||||
pub units: String,
|
||||
/// Decimal places shown.
|
||||
pub digits: usize,
|
||||
}
|
||||
|
||||
impl Reading {
|
||||
fn text(&self) -> String {
|
||||
match self.value {
|
||||
Some(v) if v.is_finite() => format!("{:.*}", self.digits, v),
|
||||
_ => "--".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Label and value row.
|
||||
pub fn kv(r: &Reading) -> Markup {
|
||||
html! {
|
||||
div class="bf-kv" data-live data-key=(r.key) {
|
||||
span class="bf-kv-label bf-text-label" { (r.label) }
|
||||
span class="bf-kv-value bf-text-body" { (r.text()) " " (r.units) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Status badge with a text label (never colour alone).
|
||||
pub fn status(r: &Reading, level: Level, text: &str) -> Markup {
|
||||
html! {
|
||||
div class="bf-kv" data-live data-key=(r.key) {
|
||||
span class="bf-kv-label bf-text-label" { (r.label) }
|
||||
span class=(level.class()) { (text) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fraction of `v` within `lo..hi`, clamped to 0..=1 (0 when the span is empty).
|
||||
pub fn fraction(v: f64, lo: f64, hi: f64) -> f64 {
|
||||
if !v.is_finite() || hi <= lo {
|
||||
return 0.0;
|
||||
}
|
||||
((v - lo) / (hi - lo)).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// Gauge or meter: a native `meter` element with the value as text beside it.
|
||||
pub fn gauge(r: &Reading, lo: f64, hi: f64) -> Markup {
|
||||
let pct = r.value.map(|v| fraction(v, lo, hi) * 100.0).unwrap_or(0.0);
|
||||
html! {
|
||||
div class="bf-gauge" data-live data-key=(r.key) {
|
||||
span class="bf-kv-label bf-text-label" { (r.label) }
|
||||
meter class="bf-gauge-bar" min=(lo) max=(hi) value=(r.value.unwrap_or(lo))
|
||||
aria-label=(r.label) { (format!("{pct:.0}%")) }
|
||||
span class="bf-kv-value bf-text-body" { (r.text()) " " (r.units) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Large single value.
|
||||
pub fn hero(r: &Reading) -> Markup {
|
||||
html! {
|
||||
div class="bf-hero" data-live data-key=(r.key) {
|
||||
span class="bf-hero-value" { (r.text()) }
|
||||
span class="bf-hero-units bf-text-body" { (r.units) }
|
||||
span class="bf-kv-label bf-text-label" { (r.label) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Table of rows; every cell is escaped text.
|
||||
pub fn table(head: &[&str], rows: &[Vec<String>]) -> Markup {
|
||||
html! {
|
||||
table class="bf-table" {
|
||||
thead { tr { @for h in head { th { (h) } } } }
|
||||
tbody { @for row in rows { tr { @for c in row { td { (c) } } } } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Log lines, newest last.
|
||||
pub fn log(lines: &[String]) -> Markup {
|
||||
html! {
|
||||
ol class="bf-log" data-live {
|
||||
@for l in lines { li class="bf-text-body-sm" { (l) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Chart host: the canvas island draws into it from `data-key`.
|
||||
pub fn chart(key: &str, label: &str) -> Markup {
|
||||
html! {
|
||||
figure class="bf-chart" data-live data-island="chart" data-key=(key) {
|
||||
canvas class="bf-chart-canvas" role="img" aria-label=(label) {}
|
||||
figcaption class="bf-text-label" { (label) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Plain note block.
|
||||
pub fn note(text: &str) -> Markup {
|
||||
html! { p class="bf-note bf-text-body" { (text) } }
|
||||
}
|
||||
|
||||
/// Nameplate: label and value pairs.
|
||||
pub fn plate(items: &[(String, String)]) -> Markup {
|
||||
html! {
|
||||
dl class="bf-plate" {
|
||||
@for (k, v) in items {
|
||||
dt class="bf-text-label" { (k) }
|
||||
dd class="bf-text-body" { (v) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
//! Schema renderer (LD-06): settings from the wschema model to HTML.
|
||||
//!
|
||||
//! [`field`] renders one setting by its display type; [`card`] renders every
|
||||
//! setting of one section in `order`. [`validate_form`] runs a submitted
|
||||
//! batch through `wschema::validate_batch`, so the page shows the same
|
||||
//! failures the daemon would return. Secrets are write-only: no stored value
|
||||
//! is ever placed in the output. Text is escaped by maud, and every class is
|
||||
//! in the stylesheet allowlist.
|
||||
|
||||
use maud::{html, Markup};
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use wschema::model::{Kind, Setting, Surface};
|
||||
use wschema::{validate_batch, Ctx, Effective, Op, Origin, Rows};
|
||||
|
||||
/// What the page knows when it renders.
|
||||
pub struct View<'a> {
|
||||
pub eff: &'a Effective,
|
||||
/// Stored rows: concrete path to wire value.
|
||||
pub rows: &'a Rows,
|
||||
/// Failure message per path, from [`validate_form`].
|
||||
pub errors: &'a BTreeMap<String, String>,
|
||||
pub surface: Surface,
|
||||
/// False renders every control disabled.
|
||||
pub can_write: bool,
|
||||
}
|
||||
|
||||
/// One selectable value: wire value and label.
|
||||
struct Choice {
|
||||
v: String,
|
||||
label: String,
|
||||
}
|
||||
|
||||
fn choices(kind: &Kind, eff: &Effective) -> Vec<Choice> {
|
||||
match kind {
|
||||
Kind::Enum { values, vocab } => {
|
||||
let mut out: Vec<Choice> = values
|
||||
.iter()
|
||||
.map(|e| Choice {
|
||||
v: e.v.clone(),
|
||||
label: e.label.clone(),
|
||||
})
|
||||
.collect();
|
||||
if let Some(v) = vocab.as_deref().and_then(|id| eff.vocab(id)) {
|
||||
out.extend(v.values.iter().map(|e| Choice {
|
||||
v: e.v.clone(),
|
||||
label: e.label.clone(),
|
||||
}));
|
||||
}
|
||||
out
|
||||
}
|
||||
Kind::IntSet { values } => values
|
||||
.iter()
|
||||
.map(|e| Choice {
|
||||
v: e.v.to_string(),
|
||||
label: e.label.clone().unwrap_or_else(|| e.v.to_string()),
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The value to show: stored row, else a static default.
|
||||
fn current<'a>(s: &'a Setting, rows: &'a Rows, path: &str) -> Option<&'a Value> {
|
||||
rows.get(path).or(s.default.value.as_ref())
|
||||
}
|
||||
|
||||
fn text_of(v: Option<&Value>) -> String {
|
||||
match v {
|
||||
Some(Value::String(x)) => x.clone(),
|
||||
Some(Value::Null) | None => String::new(),
|
||||
Some(other) => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_text(v: Option<&Value>) -> String {
|
||||
match v {
|
||||
Some(Value::Array(a)) => a
|
||||
.iter()
|
||||
.map(|x| text_of(Some(x)))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn control(
|
||||
s: &Setting,
|
||||
path: &str,
|
||||
v: Option<&Value>,
|
||||
eff: &Effective,
|
||||
off: bool,
|
||||
description: Option<&str>,
|
||||
invalid: bool,
|
||||
) -> Markup {
|
||||
let cur = text_of(v);
|
||||
let ch = choices(&s.kind, eff);
|
||||
let (lo, hi, step) = match &s.kind {
|
||||
Kind::Int { lo, hi, step, .. } => (*lo, *hi, step.unwrap_or(1)),
|
||||
_ => (0, 0, 1),
|
||||
};
|
||||
match s.display.t.as_str() {
|
||||
"text" => html! {
|
||||
input class="bf-input" type="text" name=(path) value=(cur) disabled[off]
|
||||
aria-description=[description] aria-invalid=[invalid.then_some("true")];
|
||||
},
|
||||
"secret" => html! {
|
||||
input class="bf-input" type="password" name=(path) value=""
|
||||
placeholder="unchanged" autocomplete="new-password" disabled[off]
|
||||
aria-description=[description] aria-invalid=[invalid.then_some("true")];
|
||||
},
|
||||
"dropdown" => html! {
|
||||
select class="bf-input" name=(path) disabled[off]
|
||||
aria-description=[description] aria-invalid=[invalid.then_some("true")] {
|
||||
@for c in &ch { option value=(c.v) selected[c.v == cur] { (c.label) } }
|
||||
}
|
||||
},
|
||||
"segmented" | "swatch" => html! {
|
||||
div class="bf-segmented" role="radiogroup" aria-label=(s.label)
|
||||
aria-description=[description] aria-invalid=[invalid.then_some("true")] {
|
||||
@for c in &ch {
|
||||
label class="bf-segment" {
|
||||
input type="radio" name=(path) value=(c.v) checked[c.v == cur] disabled[off];
|
||||
span { (c.label) }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"switch" => {
|
||||
let on = matches!(v, Some(Value::Bool(true)));
|
||||
html! {
|
||||
span class="bf-switch" {
|
||||
input type="checkbox" name=(path) value="true" checked[on] disabled[off]
|
||||
aria-description=[description] aria-invalid=[invalid.then_some("true")];
|
||||
span aria-hidden="true" { (if on { "On" } else { "Off" }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
"slider" => html! {
|
||||
input class="bf-input" type="range" name=(path) value=(cur)
|
||||
min=(lo) max=(hi) step=(step) disabled[off]
|
||||
aria-description=[description] aria-invalid=[invalid.then_some("true")];
|
||||
},
|
||||
"stepper" | "number" => html! {
|
||||
input class="bf-input" type="number" name=(path) value=(cur)
|
||||
min=(lo) max=(hi) step=(step) disabled[off]
|
||||
aria-description=[description] aria-invalid=[invalid.then_some("true")];
|
||||
},
|
||||
"list" => html! {
|
||||
textarea class="bf-input" name=(path) rows="4" disabled[off]
|
||||
aria-description=[description] aria-invalid=[invalid.then_some("true")] { (list_text(v)) }
|
||||
},
|
||||
other => html! {
|
||||
p class="bf-field-help bf-text-body-sm" { "Unsupported display: " (other) }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Render one setting at the concrete `path` (equal to `s.path` unless the
|
||||
/// setting belongs to a map).
|
||||
pub fn field(s: &Setting, path: &str, view: &View<'_>) -> Markup {
|
||||
let v = current(s, view.rows, path);
|
||||
let off = !view.can_write || s.hidden == Some(true);
|
||||
let err = view.errors.get(path);
|
||||
let error_description = err.map(|error| match (s.help.is_empty(), error.is_empty()) {
|
||||
(true, _) => error.clone(),
|
||||
(_, true) => s.help.clone(),
|
||||
_ => format!("{} {error}", s.help),
|
||||
});
|
||||
let description = error_description.as_deref().unwrap_or(&s.help);
|
||||
let description = (!description.is_empty()).then_some(description);
|
||||
html! {
|
||||
div class="bf-field" data-path=(path) {
|
||||
@if matches!(s.display.t.as_str(), "text" | "secret" | "dropdown" | "switch" | "slider" | "stepper" | "number" | "list") {
|
||||
// Implicit labels also work when another form repeats the field.
|
||||
label {
|
||||
span class="bf-field-label bf-text-label" { (s.label) }
|
||||
(control(s, path, v, view.eff, off, description, err.is_some()))
|
||||
}
|
||||
} @else {
|
||||
span class="bf-field-label bf-text-label" { (s.label) }
|
||||
(control(s, path, v, view.eff, off, description, err.is_some()))
|
||||
}
|
||||
@if !s.help.is_empty() { p class="bf-field-help bf-text-body-sm" { (s.help) } }
|
||||
@if let Some(e) = err { p class="bf-field-error bf-text-body-sm" role="alert" { (e) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_surface(s: &Setting, surface: Surface) -> bool {
|
||||
s.surfaces.as_ref().is_none_or(|l| l.contains(&surface))
|
||||
}
|
||||
|
||||
/// Render every visible setting of `section`, ordered by `order` then path.
|
||||
pub fn card(title: &str, section: &str, view: &View<'_>) -> Markup {
|
||||
let mut list: Vec<&Setting> = view
|
||||
.eff
|
||||
.doc
|
||||
.settings
|
||||
.iter()
|
||||
.filter(|s| s.section == section && s.hidden != Some(true) && !s.path.contains('*'))
|
||||
.filter(|s| on_surface(s, view.surface))
|
||||
.collect();
|
||||
list.sort_by(|a, b| a.order.cmp(&b.order).then_with(|| a.path.cmp(&b.path)));
|
||||
crate::components::card(
|
||||
title,
|
||||
html! { @for s in list { (field(s, &s.path, view)) } },
|
||||
)
|
||||
}
|
||||
|
||||
/// Validate a submitted batch. Returns the failure message per path; an empty
|
||||
/// map means the batch is acceptable.
|
||||
pub fn validate_form(
|
||||
eff: &Effective,
|
||||
ops: &[Op],
|
||||
rows: &Rows,
|
||||
origin: Origin,
|
||||
perms: Option<&[String]>,
|
||||
) -> BTreeMap<String, String> {
|
||||
let ctx = Ctx {
|
||||
origin,
|
||||
perms,
|
||||
rows,
|
||||
usable_wifi_credentials: None,
|
||||
tls_state: None,
|
||||
};
|
||||
validate_batch(eff, ops, &ctx)
|
||||
.into_iter()
|
||||
.map(|f| (f.path, f.msg))
|
||||
.collect()
|
||||
}
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
//! Request path resolution: path in, route or redirect out.
|
||||
//!
|
||||
//! The resolver knows the nav grammar only (d04 4.2, 4.3). Infrastructure
|
||||
//! routes (reserved words), and FLARE pages outside `/sites`, belong to
|
||||
//! their own handlers; the resolver reports them so the caller can dispatch.
|
||||
|
||||
use wschema::lint::RESERVED_ROUTE_WORDS;
|
||||
|
||||
use crate::nav::VisibleNav;
|
||||
use crate::url::Routes;
|
||||
|
||||
/// Which device a page belongs to.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Scope {
|
||||
/// Warden console at the root.
|
||||
Console,
|
||||
/// A Warden under a FLARE site.
|
||||
Warden { site: u64, warden: String },
|
||||
/// The hub's backend device.
|
||||
Backend { site: u64 },
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
pub fn routes(&self) -> Routes {
|
||||
match self {
|
||||
Scope::Console => Routes::console(),
|
||||
Scope::Warden { site, warden } => Routes::flare_warden(*site, warden),
|
||||
Scope::Backend { site } => Routes::flare_backend(*site),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What follows `/{section}/{tab}`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Tail {
|
||||
Page,
|
||||
Action(String),
|
||||
ActionStatus(String),
|
||||
ActionConfirm(String),
|
||||
Entries(String),
|
||||
Events,
|
||||
Edit,
|
||||
ItemEdit(String),
|
||||
}
|
||||
|
||||
/// A resolved nav route.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Target {
|
||||
pub scope: Scope,
|
||||
pub section: String,
|
||||
pub tab: String,
|
||||
pub tail: Tail,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Resolved {
|
||||
/// Serve this route.
|
||||
Route(Target),
|
||||
/// 302 (first visible tab can change) or 308 (canonical form).
|
||||
Redirect {
|
||||
status: u16,
|
||||
location: String,
|
||||
},
|
||||
/// A site-level page FLARE owns: `Site`, `SiteSettings` or the d05 words.
|
||||
Site {
|
||||
site: u64,
|
||||
page: SitePage,
|
||||
},
|
||||
/// First segment is a reserved word: another handler owns it.
|
||||
Infrastructure(String),
|
||||
/// Not under `/sites`: a global FLARE page, routed by FLARE itself.
|
||||
Outside,
|
||||
NotFound,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum SitePage {
|
||||
Home,
|
||||
Settings,
|
||||
/// `wifi`: owned by d05; listed so the word stays reserved.
|
||||
Wifi,
|
||||
}
|
||||
|
||||
/// Supplies the visible nav of a scope and canonical warden segments.
|
||||
pub trait NavSource {
|
||||
/// Visible nav for the scope; `None` when the scope does not exist.
|
||||
fn nav(&self, scope: &Scope) -> Option<VisibleNav>;
|
||||
/// Canonical `{warden}` segment for the one given (hostname or UUID),
|
||||
/// `None` when unknown.
|
||||
fn canonical_warden(&self, site: u64, segment: &str) -> Option<String>;
|
||||
}
|
||||
|
||||
/// A fixed nav for the console (single device).
|
||||
pub struct ConsoleNav(pub VisibleNav);
|
||||
|
||||
impl NavSource for ConsoleNav {
|
||||
fn nav(&self, scope: &Scope) -> Option<VisibleNav> {
|
||||
matches!(scope, Scope::Console).then(|| self.0.clone())
|
||||
}
|
||||
|
||||
fn canonical_warden(&self, _site: u64, _segment: &str) -> Option<String> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `word` may not be a section slug.
|
||||
pub fn is_reserved(word: &str) -> bool {
|
||||
RESERVED_ROUTE_WORDS.contains(&word)
|
||||
}
|
||||
|
||||
/// The `#/` bookmark rule: `#/{section}[/{tab}]` becomes the path, anything
|
||||
/// else is left alone. Mirrors the five-line rule of `shell.js`.
|
||||
pub fn hash_redirect(hash: &str) -> Option<String> {
|
||||
let rest = hash.strip_prefix("#/")?;
|
||||
let ok = |seg: &str| {
|
||||
!seg.is_empty()
|
||||
&& seg
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
|
||||
};
|
||||
let mut parts = rest.split('/');
|
||||
let first = parts.next()?;
|
||||
let second = parts.next();
|
||||
if parts.next().is_some() || !ok(first) || second.is_some_and(|s| !ok(s)) {
|
||||
return None;
|
||||
}
|
||||
Some(format!("/{rest}"))
|
||||
}
|
||||
|
||||
fn redirect(status: u16, location: String) -> Resolved {
|
||||
Resolved::Redirect { status, location }
|
||||
}
|
||||
|
||||
/// Splits a path into non-empty segments; the flag says whether the path was
|
||||
/// not already in canonical shape (trailing or doubled slash).
|
||||
fn segments(path: &str) -> (Vec<&str>, bool) {
|
||||
let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
|
||||
let canonical = path == "/" || path == format!("/{}", segs.join("/"));
|
||||
(segs, !canonical)
|
||||
}
|
||||
|
||||
/// Resolves `path` (no query string) for the surface the source serves.
|
||||
/// `flare` selects the FLARE grammar (`/sites/...`); false is the console.
|
||||
pub fn resolve(path: &str, flare: bool, src: &dyn NavSource) -> Resolved {
|
||||
if !path.starts_with('/') {
|
||||
return Resolved::NotFound;
|
||||
}
|
||||
let (segs, uncanonical) = segments(path);
|
||||
if flare {
|
||||
resolve_flare(&segs, uncanonical, src)
|
||||
} else {
|
||||
resolve_nav(&Scope::Console, &segs, uncanonical, src)
|
||||
}
|
||||
}
|
||||
|
||||
fn join(prefix: &str, segs: &[String]) -> String {
|
||||
let tail = segs.join("/");
|
||||
if tail.is_empty() {
|
||||
if prefix.is_empty() {
|
||||
"/".to_string()
|
||||
} else {
|
||||
prefix.to_string()
|
||||
}
|
||||
} else {
|
||||
format!("{prefix}/{tail}")
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_flare(segs: &[&str], uncanonical: bool, src: &dyn NavSource) -> Resolved {
|
||||
if segs.first() != Some(&"sites") {
|
||||
return Resolved::Outside;
|
||||
}
|
||||
let Some(site) = segs.get(1).and_then(|s| parse_site(s)) else {
|
||||
return Resolved::NotFound;
|
||||
};
|
||||
let canon_site = format!("/sites/{site}");
|
||||
// A non-canonical site number ("007") redirects too.
|
||||
let site_changed = segs[1] != site.to_string();
|
||||
let redirect_to = |rest: &[String]| redirect(308, join(&canon_site, rest));
|
||||
match segs.get(2).copied() {
|
||||
None => {
|
||||
if uncanonical || site_changed {
|
||||
redirect_to(&[])
|
||||
} else {
|
||||
Resolved::Site {
|
||||
site,
|
||||
page: SitePage::Home,
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("settings") if segs.len() == 3 => {
|
||||
if uncanonical || site_changed {
|
||||
redirect_to(&["settings".to_string()])
|
||||
} else {
|
||||
Resolved::Site {
|
||||
site,
|
||||
page: SitePage::Settings,
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("wifi") if segs.len() == 3 => Resolved::Site {
|
||||
site,
|
||||
page: SitePage::Wifi,
|
||||
},
|
||||
Some("backend") => {
|
||||
let scope = Scope::Backend { site };
|
||||
let prefix = format!("{canon_site}/backend");
|
||||
resolve_nav_under(
|
||||
&scope,
|
||||
&prefix,
|
||||
&segs[3..],
|
||||
uncanonical || site_changed,
|
||||
src,
|
||||
)
|
||||
}
|
||||
Some("wardens") => {
|
||||
let Some(raw) = segs.get(3) else {
|
||||
return Resolved::NotFound;
|
||||
};
|
||||
let Some(canon) = src.canonical_warden(site, raw) else {
|
||||
return Resolved::NotFound;
|
||||
};
|
||||
let warden_changed = canon != *raw;
|
||||
let scope = Scope::Warden {
|
||||
site,
|
||||
warden: canon.clone(),
|
||||
};
|
||||
let prefix = scope.routes().prefix().to_string();
|
||||
resolve_nav_under(
|
||||
&scope,
|
||||
&prefix,
|
||||
&segs[4..],
|
||||
uncanonical || site_changed || warden_changed,
|
||||
src,
|
||||
)
|
||||
}
|
||||
// /sites/{site}/{section}: dropped, a Warden page is never here.
|
||||
Some(_) => Resolved::NotFound,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_site(s: &str) -> Option<u64> {
|
||||
(!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()))
|
||||
.then(|| s.parse().ok())
|
||||
.flatten()
|
||||
}
|
||||
|
||||
fn resolve_nav(scope: &Scope, segs: &[&str], uncanonical: bool, src: &dyn NavSource) -> Resolved {
|
||||
if let Some(first) = segs.first() {
|
||||
let lower = first.to_ascii_lowercase();
|
||||
if is_reserved(&lower) {
|
||||
return Resolved::Infrastructure(lower);
|
||||
}
|
||||
}
|
||||
resolve_nav_under(scope, "", segs, uncanonical, src)
|
||||
}
|
||||
|
||||
/// Resolves the segments after the scope prefix. `changed` carries any
|
||||
/// canonicalisation already needed above this point.
|
||||
fn resolve_nav_under(
|
||||
scope: &Scope,
|
||||
prefix: &str,
|
||||
segs: &[&str],
|
||||
changed: bool,
|
||||
src: &dyn NavSource,
|
||||
) -> Resolved {
|
||||
let Some(nav) = src.nav(scope) else {
|
||||
return Resolved::NotFound;
|
||||
};
|
||||
if segs.is_empty() {
|
||||
// Scope home: first visible tab.
|
||||
return match nav.first_tab() {
|
||||
Some((s, t)) => redirect(302, scope.routes().page(s, t)),
|
||||
None => Resolved::NotFound,
|
||||
};
|
||||
}
|
||||
// Section and tab slugs are lower case; fold them, the rest keeps case.
|
||||
let mut canon: Vec<String> = Vec::with_capacity(segs.len());
|
||||
let mut fold = changed;
|
||||
for (i, s) in segs.iter().enumerate() {
|
||||
if i < 2 && *s != s.to_ascii_lowercase() {
|
||||
fold = true;
|
||||
canon.push(s.to_ascii_lowercase());
|
||||
} else {
|
||||
canon.push(s.to_string());
|
||||
}
|
||||
}
|
||||
let section_slug = &canon[0];
|
||||
let Some(section) = nav.section(section_slug) else {
|
||||
return Resolved::NotFound;
|
||||
};
|
||||
let Some(tab_slug) = canon.get(1) else {
|
||||
// /{section}: 302 to the first visible tab; a canonicalisation
|
||||
// redirect would only add a hop.
|
||||
return match section.tabs.first() {
|
||||
Some(t) => redirect(302, scope.routes().page(§ion.slug, &t.slug)),
|
||||
None => Resolved::NotFound,
|
||||
};
|
||||
};
|
||||
if !section.tabs.iter().any(|t| &t.slug == tab_slug) {
|
||||
return Resolved::NotFound;
|
||||
}
|
||||
let tail = match parse_tail(&canon[2..]) {
|
||||
Some(t) => t,
|
||||
None => return Resolved::NotFound,
|
||||
};
|
||||
if fold {
|
||||
return redirect(308, join(prefix, &canon));
|
||||
}
|
||||
Resolved::Route(Target {
|
||||
scope: scope.clone(),
|
||||
section: section_slug.clone(),
|
||||
tab: tab_slug.clone(),
|
||||
tail,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_tail(rest: &[String]) -> Option<Tail> {
|
||||
let r: Vec<&str> = rest.iter().map(String::as_str).collect();
|
||||
Some(match r.as_slice() {
|
||||
[] => Tail::Page,
|
||||
["events"] => Tail::Events,
|
||||
["edit"] => Tail::Edit,
|
||||
["actions", name] => Tail::Action((*name).to_string()),
|
||||
["actions", name, "status"] => Tail::ActionStatus((*name).to_string()),
|
||||
["actions", name, "confirm"] => Tail::ActionConfirm((*name).to_string()),
|
||||
["entries", map] => Tail::Entries((*map).to_string()),
|
||||
[id, "edit"] => Tail::ItemEdit((*id).to_string()),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
//! Page shell (UI-4): sidebar of visible sections, tab strip, main area.
|
||||
//!
|
||||
//! The shell renders a [`VisibleNav`] already filtered for the viewer; it does
|
||||
//! no permission logic of its own. Active section and tab are marked with
|
||||
//! `aria-current="page"` and the `bf-nav-active` class.
|
||||
|
||||
use maud::{html, Markup, DOCTYPE};
|
||||
|
||||
use crate::assets::PageAssets;
|
||||
use crate::nav::VisibleNav;
|
||||
|
||||
/// The section and tab being shown, by slug.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Active<'a> {
|
||||
pub section: &'a str,
|
||||
pub tab: &'a str,
|
||||
}
|
||||
|
||||
fn link_class(active: bool) -> &'static str {
|
||||
if active {
|
||||
"bf-nav-link bf-text-body bf-nav-active"
|
||||
} else {
|
||||
"bf-nav-link bf-text-body"
|
||||
}
|
||||
}
|
||||
|
||||
/// The sidebar: one block per visible section, linking its first tab.
|
||||
pub fn sidebar(nav: &VisibleNav, active: Active) -> Markup {
|
||||
html! {
|
||||
nav class="bf-sidebar" aria-label="Sections" {
|
||||
@for s in &nav.sections {
|
||||
@let here = s.slug == active.section;
|
||||
@if let Some(first) = s.tabs.first() {
|
||||
div class="bf-nav-section" {
|
||||
a class=(link_class(here)) href=(first.href)
|
||||
aria-current=[here.then_some("page")] { (s.title) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The tab strip of the active section; empty markup when it has one tab or
|
||||
/// the section is not visible.
|
||||
pub fn tab_strip(nav: &VisibleNav, active: Active) -> Markup {
|
||||
let Some(sec) = nav.section(active.section) else {
|
||||
return html! {};
|
||||
};
|
||||
if sec.tabs.len() < 2 {
|
||||
return html! {};
|
||||
}
|
||||
html! {
|
||||
div class="bf-tabs" role="navigation" aria-label="Tabs" {
|
||||
@for t in &sec.tabs {
|
||||
@let here = t.slug == active.tab;
|
||||
a class=(link_class(here)) href=(t.href)
|
||||
aria-current=[here.then_some("page")] { (t.title) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A full HTML document around `body`.
|
||||
pub fn page(
|
||||
title: &str,
|
||||
assets: &PageAssets,
|
||||
nav: &VisibleNav,
|
||||
active: Active,
|
||||
body: Markup,
|
||||
) -> Markup {
|
||||
html! {
|
||||
(DOCTYPE)
|
||||
html lang="en" {
|
||||
head {
|
||||
meta charset="utf-8";
|
||||
meta name="viewport" content="width=device-width, initial-scale=1";
|
||||
title { (title) }
|
||||
(assets.head())
|
||||
}
|
||||
body {
|
||||
div class="bf-shell" {
|
||||
(sidebar(nav, active))
|
||||
main class="bf-main" {
|
||||
(tab_strip(nav, active))
|
||||
(body)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::nav::{VisibleSection, VisibleTab};
|
||||
use crate::tokens::class_allowed;
|
||||
|
||||
fn tab(slug: &str) -> VisibleTab {
|
||||
VisibleTab {
|
||||
slug: slug.into(),
|
||||
title: slug.to_uppercase(),
|
||||
page: "p".into(),
|
||||
href: format!("/s/{slug}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn nav() -> VisibleNav {
|
||||
VisibleNav {
|
||||
sections: vec![
|
||||
VisibleSection {
|
||||
slug: "a".into(),
|
||||
title: "Alpha <x>".into(),
|
||||
icon: "i".into(),
|
||||
tabs: vec![tab("t1"), tab("t2")],
|
||||
},
|
||||
VisibleSection {
|
||||
slug: "b".into(),
|
||||
title: "Beta".into(),
|
||||
icon: "i".into(),
|
||||
tabs: vec![tab("t3")],
|
||||
},
|
||||
VisibleSection {
|
||||
slug: "empty".into(),
|
||||
title: "Empty".into(),
|
||||
icon: "i".into(),
|
||||
tabs: vec![],
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
fn classes(html: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut rest = html;
|
||||
while let Some(i) = rest.find("class=\"") {
|
||||
rest = &rest[i + 7..];
|
||||
let end = rest.find('"').unwrap();
|
||||
out.extend(rest[..end].split_whitespace().map(String::from));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_active_and_escapes() {
|
||||
let s = sidebar(
|
||||
&nav(),
|
||||
Active {
|
||||
section: "a",
|
||||
tab: "t1",
|
||||
},
|
||||
)
|
||||
.into_string();
|
||||
assert!(s.contains("aria-current=\"page\""));
|
||||
assert_eq!(s.matches("aria-current").count(), 1);
|
||||
assert!(s.contains("Alpha <x>"));
|
||||
assert!(!s.contains("Empty"), "sections without tabs are skipped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_strip_only_for_multi_tab_sections() {
|
||||
let a = Active {
|
||||
section: "a",
|
||||
tab: "t2",
|
||||
};
|
||||
let s = tab_strip(&nav(), a).into_string();
|
||||
assert!(s.contains("href=\"/s/t1\"") && s.contains("href=\"/s/t2\""));
|
||||
assert_eq!(s.matches("aria-current").count(), 1);
|
||||
assert_eq!(
|
||||
tab_strip(
|
||||
&nav(),
|
||||
Active {
|
||||
section: "b",
|
||||
tab: "t3"
|
||||
}
|
||||
)
|
||||
.into_string(),
|
||||
""
|
||||
);
|
||||
assert_eq!(
|
||||
tab_strip(
|
||||
&nav(),
|
||||
Active {
|
||||
section: "zz",
|
||||
tab: "t"
|
||||
}
|
||||
)
|
||||
.into_string(),
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_is_complete_and_classes_allowed() {
|
||||
let assets = PageAssets {
|
||||
styles: vec!["/s.css".into()],
|
||||
scripts: vec!["/live.js".into()],
|
||||
streams: vec![],
|
||||
};
|
||||
let s = page(
|
||||
"T",
|
||||
&assets,
|
||||
&nav(),
|
||||
Active {
|
||||
section: "a",
|
||||
tab: "t1",
|
||||
},
|
||||
html! { p { "hi" } },
|
||||
)
|
||||
.into_string();
|
||||
assert!(s.starts_with("<!DOCTYPE html>"));
|
||||
assert!(s.contains("<title>T</title>") && s.contains("href=\"/s.css\""));
|
||||
assert!(s.contains("<p>hi</p>"));
|
||||
for c in classes(&s) {
|
||||
assert!(class_allowed(&c), "class {c} not allowed");
|
||||
}
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
//! Dash studio assets (LD-07, flare-ui side).
|
||||
//!
|
||||
//! The dashboard editor lives under `dash-editor/editor/`. This module embeds
|
||||
//! its files so a consumer serves them from one table instead of vendoring a
|
||||
//! copy: [`asset`] maps a request name to a content type and body, and
|
||||
//! [`STUDIO_FRAGMENT`] is the page body the studio script mounts into.
|
||||
|
||||
/// The studio page fragment (no `<html>` wrapper; the shell supplies it).
|
||||
pub const STUDIO_FRAGMENT: &str = include_str!("../../../dash-editor/editor/dashboard_studio.html");
|
||||
|
||||
/// One embedded studio file.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StudioAsset {
|
||||
/// File name under the studio mount, with no directory part.
|
||||
pub name: &'static str,
|
||||
/// Media type to serve it with.
|
||||
pub content_type: &'static str,
|
||||
/// File body, byte for byte.
|
||||
pub body: &'static str,
|
||||
}
|
||||
|
||||
macro_rules! js {
|
||||
($n:literal) => {
|
||||
StudioAsset {
|
||||
name: $n,
|
||||
content_type: "text/javascript; charset=utf-8",
|
||||
body: include_str!(concat!("../../../dash-editor/editor/", $n)),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Every studio file served to the browser, in load order.
|
||||
pub const ASSETS: &[StudioAsset] = &[
|
||||
js!("dashboard-json.js"),
|
||||
js!("dashboard-doc.js"),
|
||||
js!("dashboard-file.js"),
|
||||
js!("dashboard-sources.js"),
|
||||
js!("dashboard-raw.js"),
|
||||
js!("dashboard-list.js"),
|
||||
js!("dashboard-drag.js"),
|
||||
js!("dashboard-editor.js"),
|
||||
js!("dashboard-inspector.js"),
|
||||
StudioAsset {
|
||||
name: "studio.css",
|
||||
content_type: "text/css; charset=utf-8",
|
||||
body: include_str!("../../../dash-editor/editor/studio.css"),
|
||||
},
|
||||
];
|
||||
|
||||
/// Look up a studio file by request name. Names with a path separator or a
|
||||
/// dot-dot never match.
|
||||
pub fn asset(name: &str) -> Option<&'static StudioAsset> {
|
||||
if name.contains('/') || name.contains('\\') || name.contains("..") {
|
||||
return None;
|
||||
}
|
||||
ASSETS.iter().find(|a| a.name == name)
|
||||
}
|
||||
|
||||
/// Script names in load order, for [`crate::assets::PageAssets::scripts`].
|
||||
pub fn script_names() -> impl Iterator<Item = &'static str> {
|
||||
ASSETS
|
||||
.iter()
|
||||
.filter(|a| a.name.ends_with(".js"))
|
||||
.map(|a| a.name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn every_editor_file_is_embedded() {
|
||||
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../dash-editor/editor");
|
||||
for e in std::fs::read_dir(dir).unwrap() {
|
||||
let name = e.unwrap().file_name().into_string().unwrap();
|
||||
if name == "dashboard_studio.html" {
|
||||
continue;
|
||||
}
|
||||
assert!(asset(&name).is_some(), "{name} not embedded");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bodies_are_ascii_and_nonempty() {
|
||||
for a in ASSETS {
|
||||
assert!(a.body.is_ascii() && !a.body.is_empty(), "{}", a.name);
|
||||
}
|
||||
assert!(STUDIO_FRAGMENT.is_ascii());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_rejects_traversal() {
|
||||
assert!(asset("studio.css").is_some());
|
||||
assert!(asset("../studio.css").is_none());
|
||||
assert!(asset("a/studio.css").is_none());
|
||||
assert!(asset("missing.js").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_types_match_extension() {
|
||||
for a in ASSETS {
|
||||
let js = a.name.ends_with(".js");
|
||||
assert_eq!(
|
||||
a.content_type.starts_with("text/javascript"),
|
||||
js,
|
||||
"{}",
|
||||
a.name
|
||||
);
|
||||
}
|
||||
assert_eq!(script_names().count(), ASSETS.len() - 1);
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
//! Design tokens and the CSS class allowlist (UI-4).
|
||||
//!
|
||||
//! `assets/tokens.css` is the single source of design tokens for FLARE and
|
||||
//! the Warden console. [`TOKENS_CSS`] embeds it; [`token_names`] and
|
||||
//! [`class_names`] list what it defines; [`class_allowed`] is the allowlist
|
||||
//! the renderer checks every emitted `class` against.
|
||||
|
||||
/// The token stylesheet, byte for byte.
|
||||
pub const TOKENS_CSS: &str = include_str!("../assets/tokens.css");
|
||||
|
||||
/// The component stylesheet, byte for byte. Uses only tokens from [`TOKENS_CSS`].
|
||||
pub const COMPONENTS_CSS: &str = include_str!("../assets/components.css");
|
||||
|
||||
/// The shared app theme (`--app-*` aliases, dark default, light variants), byte for byte.
|
||||
pub const THEME_CSS: &str = include_str!("../assets/theme.css");
|
||||
|
||||
/// Maps the legacy Warden console property names onto the shared theme.
|
||||
pub const WARDEN_COMPAT_CSS: &str = include_str!("../assets/warden-compat.css");
|
||||
|
||||
/// Prefix every token and shared class carries.
|
||||
pub const PREFIX: &str = "bf-";
|
||||
|
||||
/// Custom property names defined in `:root` (for example `--bf-space-4`), sorted.
|
||||
pub fn token_names() -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for line in TOKENS_CSS.lines() {
|
||||
let t = line.trim_start();
|
||||
if let Some(rest) = t.strip_prefix("--") {
|
||||
if let Some((name, _)) = rest.split_once(':') {
|
||||
out.push(format!("--{}", name.trim()));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// Class names defined by the stylesheet (without the dot), sorted.
|
||||
pub fn class_names() -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for line in TOKENS_CSS.lines().chain(COMPONENTS_CSS.lines()) {
|
||||
let Some(rest) = line.strip_prefix('.') else {
|
||||
continue;
|
||||
};
|
||||
let end = rest
|
||||
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '-' || c == '_'))
|
||||
.unwrap_or(rest.len());
|
||||
if end > 0 {
|
||||
out.push(rest[..end].to_string());
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// True when `class` may appear in rendered output: a single token with only
|
||||
/// `[a-z0-9_-]` that the stylesheet defines.
|
||||
pub fn class_allowed(class: &str) -> bool {
|
||||
class_names().iter().any(|c| c == class)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tokens_are_ascii_and_prefixed() {
|
||||
assert!(TOKENS_CSS.is_ascii());
|
||||
let names = token_names();
|
||||
assert!(names.len() > 100);
|
||||
assert!(names.iter().all(|n| n.starts_with("--bf-")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_var_reference_resolves() {
|
||||
let names = token_names();
|
||||
let all = format!("{TOKENS_CSS}\n{COMPONENTS_CSS}");
|
||||
let mut rest = all.as_str();
|
||||
while let Some(i) = rest.find("var(") {
|
||||
rest = &rest[i + 4..];
|
||||
let end = rest.find(')').unwrap();
|
||||
let name = rest[..end].trim();
|
||||
assert!(names.iter().any(|n| n == name), "unresolved {name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allowlist_matches_stylesheet() {
|
||||
assert!(class_allowed("bf-text-body"));
|
||||
assert!(!class_allowed("bf-text-bodyx"));
|
||||
assert!(!class_allowed("evil"));
|
||||
assert!(!class_allowed(""));
|
||||
assert!(class_names().iter().all(|c| c.starts_with(PREFIX)));
|
||||
}
|
||||
|
||||
fn defined(css: &str) -> Vec<String> {
|
||||
css.lines()
|
||||
.flat_map(|l| l.split(';'))
|
||||
.filter_map(|d| {
|
||||
let d = d.trim_start().trim_start_matches('{').trim_start();
|
||||
let rest = d.strip_prefix("--")?;
|
||||
let (name, _) = rest.split_once(':')?;
|
||||
Some(format!("--{}", name.trim()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn used(css: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut rest = css;
|
||||
while let Some(i) = rest.find("var(") {
|
||||
rest = &rest[i + 4..];
|
||||
let end = rest.find(')').unwrap();
|
||||
out.push(rest[..end].trim().to_string());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_references_resolve() {
|
||||
let mut known = defined(TOKENS_CSS);
|
||||
known.extend(defined(THEME_CSS));
|
||||
known.extend(defined(WARDEN_COMPAT_CSS));
|
||||
for css in [THEME_CSS, WARDEN_COMPAT_CSS] {
|
||||
assert!(css.is_ascii());
|
||||
for name in used(css) {
|
||||
assert!(known.contains(&name), "unresolved {name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_variants_define_the_same_names() {
|
||||
// Dark root block, light data-theme block and the system-preference block.
|
||||
let sets: Vec<Vec<String>> = THEME_CSS
|
||||
.split('}')
|
||||
.map(|b| {
|
||||
let mut d: Vec<String> = defined(b)
|
||||
.into_iter()
|
||||
.filter(|n| n.starts_with("--app-"))
|
||||
.collect();
|
||||
d.sort();
|
||||
d.dedup();
|
||||
d
|
||||
})
|
||||
.filter(|d| !d.is_empty())
|
||||
.collect();
|
||||
assert_eq!(sets.len(), 3, "dark, light, system light");
|
||||
assert_eq!(sets[0], sets[1]);
|
||||
assert_eq!(sets[0], sets[2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warden_names_are_all_mapped() {
|
||||
// Custom properties the console stylesheet reads (checked against app.css).
|
||||
let legacy = [
|
||||
"--radius",
|
||||
"--sp-1",
|
||||
"--sp-2",
|
||||
"--sp-3",
|
||||
"--sp-4",
|
||||
"--sp-6",
|
||||
"--sp-8",
|
||||
"--hair",
|
||||
"--font-display",
|
||||
"--font-body",
|
||||
"--bg",
|
||||
"--surface",
|
||||
"--surface-alt",
|
||||
"--border",
|
||||
"--text",
|
||||
"--text-muted",
|
||||
"--accent",
|
||||
"--accent-ink",
|
||||
"--accent-soft",
|
||||
"--flame",
|
||||
"--ok",
|
||||
"--warn",
|
||||
"--crit",
|
||||
"--dot-ok",
|
||||
"--dot-warn",
|
||||
"--dot-crit",
|
||||
"--dot-new",
|
||||
"--dot-off",
|
||||
"--focus",
|
||||
"--scrim",
|
||||
"--chip-dark",
|
||||
"--rail-w",
|
||||
"--rail-narrow",
|
||||
"--sidebar-w",
|
||||
];
|
||||
let got = defined(WARDEN_COMPAT_CSS);
|
||||
for n in legacy {
|
||||
assert!(got.iter().any(|g| g == n), "unmapped {n}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
//! URL builders. Every URL derives from the nav model (d04 4.1): one canonical
|
||||
//! form per page, `/{section}/{tab}`, under a prefix that is empty on the
|
||||
//! Warden console and a device path in FLARE.
|
||||
|
||||
/// Query parameters every page shares (names.md 18).
|
||||
pub const QUERY_KEYS: &[&str] = &[
|
||||
"sort", "dir", "page", "per", "q", "tier", "src", "range", "app",
|
||||
];
|
||||
/// Stream resume position on `.../events`.
|
||||
pub const KEY_SEQ: &str = "seq";
|
||||
/// `mode=poll`, the one-batch fallback of `.../events`.
|
||||
pub const KEY_MODE: &str = "mode";
|
||||
/// Terminal ticket on `/term`.
|
||||
pub const KEY_TICKET: &str = "t";
|
||||
|
||||
/// Percent-encodes one path segment or query component (RFC 3986 unreserved
|
||||
/// characters pass through).
|
||||
pub fn encode(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for b in s.bytes() {
|
||||
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
|
||||
out.push(b as char);
|
||||
} else {
|
||||
out.push_str(&format!("%{b:02X}"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Route prefix of one surface scope.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Routes {
|
||||
prefix: String,
|
||||
}
|
||||
|
||||
impl Routes {
|
||||
/// The Warden console: routes at the root.
|
||||
pub fn console() -> Self {
|
||||
Routes {
|
||||
prefix: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A Warden under a FLARE site: `/sites/{site}/wardens/{warden}`.
|
||||
pub fn flare_warden(site: u64, warden: &str) -> Self {
|
||||
Routes {
|
||||
prefix: format!("/sites/{site}/wardens/{}", encode(warden)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The hub's backend device: `/sites/{site}/backend`.
|
||||
pub fn flare_backend(site: u64) -> Self {
|
||||
Routes {
|
||||
prefix: format!("/sites/{site}/backend"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn prefix(&self) -> &str {
|
||||
&self.prefix
|
||||
}
|
||||
|
||||
/// Home of the scope: the root or the Warden path (redirects to the first
|
||||
/// visible tab).
|
||||
pub fn home(&self) -> String {
|
||||
if self.prefix.is_empty() {
|
||||
"/".to_string()
|
||||
} else {
|
||||
self.prefix.clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn section(&self, section: &str) -> String {
|
||||
format!("{}/{}", self.prefix, encode(section))
|
||||
}
|
||||
|
||||
/// The canonical page URL.
|
||||
pub fn page(&self, section: &str, tab: &str) -> String {
|
||||
format!("{}/{}", self.section(section), encode(tab))
|
||||
}
|
||||
|
||||
pub fn action(&self, section: &str, tab: &str, name: &str) -> String {
|
||||
format!("{}/actions/{}", self.page(section, tab), encode(name))
|
||||
}
|
||||
|
||||
pub fn action_status(&self, section: &str, tab: &str, name: &str) -> String {
|
||||
format!("{}/status", self.action(section, tab, name))
|
||||
}
|
||||
|
||||
pub fn action_confirm(&self, section: &str, tab: &str, name: &str) -> String {
|
||||
format!("{}/confirm", self.action(section, tab, name))
|
||||
}
|
||||
|
||||
pub fn entries(&self, section: &str, tab: &str, map: &str) -> String {
|
||||
format!("{}/entries/{}", self.page(section, tab), encode(map))
|
||||
}
|
||||
|
||||
pub fn events(&self, section: &str, tab: &str) -> String {
|
||||
format!("{}/events", self.page(section, tab))
|
||||
}
|
||||
|
||||
/// The page's own island editor.
|
||||
pub fn edit(&self, section: &str, tab: &str) -> String {
|
||||
format!("{}/edit", self.page(section, tab))
|
||||
}
|
||||
|
||||
/// An item editor such as the later flow builder.
|
||||
pub fn item_edit(&self, section: &str, tab: &str, id: &str) -> String {
|
||||
format!("{}/{}/edit", self.page(section, tab), encode(id))
|
||||
}
|
||||
}
|
||||
|
||||
/// FLARE site home.
|
||||
pub fn flare_site(site: u64) -> String {
|
||||
format!("/sites/{site}")
|
||||
}
|
||||
|
||||
/// FLARE site settings (FLARE-owned).
|
||||
pub fn flare_site_settings(site: u64) -> String {
|
||||
format!("/sites/{site}/settings")
|
||||
}
|
||||
|
||||
/// Appends a query string built from `pairs` to `path`. Only the closed
|
||||
/// parameter set of [`QUERY_KEYS`] and the `extra` keys the route allows pass;
|
||||
/// unknown keys are dropped, as are values outside their domain (`dir` other
|
||||
/// than asc or desc, `tier` other than min, hour or day, `per` outside
|
||||
/// 10 to 200, `mode` other than poll). Order follows `pairs`.
|
||||
pub fn with_query<'a, I>(path: &str, pairs: I, extra: &[&str]) -> String
|
||||
where
|
||||
I: IntoIterator<Item = (&'a str, &'a str)>,
|
||||
{
|
||||
let kept: Vec<String> = pairs
|
||||
.into_iter()
|
||||
.filter(|(k, _)| QUERY_KEYS.contains(k) || extra.contains(k))
|
||||
.filter(|(k, v)| value_ok(k, v))
|
||||
.map(|(k, v)| format!("{}={}", encode(k), encode(v)))
|
||||
.collect();
|
||||
if kept.is_empty() {
|
||||
path.to_string()
|
||||
} else {
|
||||
format!("{path}?{}", kept.join("&"))
|
||||
}
|
||||
}
|
||||
|
||||
fn value_ok(key: &str, value: &str) -> bool {
|
||||
match key {
|
||||
"dir" => matches!(value, "asc" | "desc"),
|
||||
"tier" => matches!(value, "min" | "hour" | "day"),
|
||||
"per" => value.parse::<u32>().is_ok_and(|n| (10..=200).contains(&n)),
|
||||
"page" | KEY_SEQ => value.parse::<u64>().is_ok(),
|
||||
KEY_MODE => value == "poll",
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
//! Action and approval tests: target safety, escaping, allowlist, goldens.
|
||||
//! Refresh goldens with `UPDATE_GOLDEN=1 cargo test -p flare-ui --test actions`.
|
||||
|
||||
use flare_ui::actions::*;
|
||||
use flare_ui::tokens::class_allowed;
|
||||
|
||||
fn ap(id: &str) -> Approval {
|
||||
Approval {
|
||||
id: id.into(),
|
||||
summary: "Open <valve> 3".into(),
|
||||
requested_by: "ann".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn cases() -> Vec<(&'static str, String)> {
|
||||
vec![
|
||||
(
|
||||
"button",
|
||||
action_button("/a/b", "Run", Tone::Primary, "tok", None)
|
||||
.unwrap()
|
||||
.into_string(),
|
||||
),
|
||||
(
|
||||
"button_confirm",
|
||||
action_button("/a/b", "Stop", Tone::Danger, "tok", Some("Sure?"))
|
||||
.unwrap()
|
||||
.into_string(),
|
||||
),
|
||||
(
|
||||
"approvals",
|
||||
approvals("/approvals", &[ap("a1")], "tok").into_string(),
|
||||
),
|
||||
(
|
||||
"approvals_empty",
|
||||
approvals("/approvals", &[], "tok").into_string(),
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn golden_per_block() {
|
||||
for (name, got) in cases() {
|
||||
let p = format!(
|
||||
"{}/tests/golden/actions/{name}.html",
|
||||
env!("CARGO_MANIFEST_DIR")
|
||||
);
|
||||
if std::env::var("UPDATE_GOLDEN").is_ok() {
|
||||
std::fs::create_dir_all(std::path::Path::new(&p).parent().unwrap()).unwrap();
|
||||
std::fs::write(&p, format!("{got}\n")).unwrap();
|
||||
continue;
|
||||
}
|
||||
let want = std::fs::read_to_string(&p).unwrap_or_else(|_| panic!("missing golden {p}"));
|
||||
assert_eq!(want.trim_end(), got, "golden {name} differs");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsafe_targets_render_nothing() {
|
||||
for t in [
|
||||
"//evil.example/x",
|
||||
"https://evil.example",
|
||||
"x",
|
||||
"",
|
||||
"/a b",
|
||||
"/a\\b",
|
||||
"/a\nb",
|
||||
] {
|
||||
assert!(
|
||||
action_button(t, "Go", Tone::Normal, "t", None).is_none(),
|
||||
"{t:?}"
|
||||
);
|
||||
assert!(!safe_target(t), "{t:?}");
|
||||
}
|
||||
assert!(safe_target("/ok/path?x=1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_ids_and_base_are_dropped() {
|
||||
let s = approvals("/approvals", &[ap("../x"), ap(""), ap("a/b")], "t").into_string();
|
||||
assert!(s.contains("No approvals pending"), "{s}");
|
||||
let s = approvals("//evil", &[ap("ok")], "t").into_string();
|
||||
assert!(
|
||||
s.contains("No approvals pending") && !s.contains("evil"),
|
||||
"{s}"
|
||||
);
|
||||
let s = approvals("/approvals/", &[ap("ok")], "t").into_string();
|
||||
assert!(s.contains("action=\"/approvals/ok/approve\""), "{s}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_is_escaped_and_csrf_present() {
|
||||
let s = approvals("/approvals", &[ap("a1")], "t\"k").into_string();
|
||||
assert!(s.contains("<valve>") && !s.contains("<valve>"));
|
||||
assert!(s.contains("name=\"csrf\"") && s.contains("t"k"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_class_is_allowed() {
|
||||
let mut n = 0;
|
||||
for (name, html) in cases() {
|
||||
let mut rest = html.as_str();
|
||||
while let Some(i) = rest.find("class=\"") {
|
||||
rest = &rest[i + 7..];
|
||||
let end = rest.find('"').unwrap();
|
||||
for cl in rest[..end].split_whitespace() {
|
||||
assert!(class_allowed(cl), "{name}: class {cl} not allowed");
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(n > 5);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
mod common;
|
||||
|
||||
use std::process::Command;
|
||||
use wschema::model::{DocKind, Document};
|
||||
|
||||
#[test]
|
||||
fn nav_json_binary_prints_the_document() {
|
||||
let mut doc = Document::new(DocKind::Base, "t");
|
||||
doc.menus = common::menus();
|
||||
let dir = std::env::temp_dir().join(format!("nav-json-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("schema.json");
|
||||
std::fs::write(&file, doc.to_value().to_string()).unwrap();
|
||||
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_nav-json"))
|
||||
.arg(&file)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
|
||||
assert_eq!(v, flare_ui::nav::nav_json(&common::menus()));
|
||||
|
||||
let bad = Command::new(env!("CARGO_BIN_EXE_nav-json"))
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(bad.status.code(), Some(2));
|
||||
let missing = Command::new(env!("CARGO_BIN_EXE_nav-json"))
|
||||
.arg(dir.join("none"))
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(missing.status.code(), Some(2));
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//! Runs the Node unit tests for `assets/js/boot.js`. Skipped (with a note)
|
||||
//! when `node` is not installed.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn boot_js_unit_tests() {
|
||||
let dir = env!("CARGO_MANIFEST_DIR");
|
||||
let out = match Command::new("node")
|
||||
.args(["--test", "tests/js/boot.test.js"])
|
||||
.current_dir(dir)
|
||||
.output()
|
||||
{
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
eprintln!("skipping boot.js tests: node unavailable ({e})");
|
||||
return;
|
||||
}
|
||||
};
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"node tests failed:\n{}\n{}",
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
# Chart benchmarks
|
||||
|
||||
Use the pinned Playwright installation described in README.md. Run these
|
||||
workloads on an isolated test worker with headless Chromium and Firefox.
|
||||
|
||||
```sh
|
||||
node benchmark.cjs --verify
|
||||
node benchmark.cjs --runs=3 --samples=20 --warmup=5
|
||||
node visually-hidden.cjs
|
||||
```
|
||||
|
||||
`--verify` checks the workloads without reporting timing estimates. It
|
||||
uses one browser launch per engine, two warmup batches and three measured
|
||||
batches per case. Profiling defaults to three independent browser launches,
|
||||
five warmup batches and 20 measured batches. `--browser=chromium` or
|
||||
`--browser=firefox` limits either mode to one engine.
|
||||
|
||||
## Workloads
|
||||
|
||||
Each case runs with normal and reduced motion, 60 seeded points per series,
|
||||
the real live/chart scripts, all shared stylesheets and a plain-HTTP SSE
|
||||
server. The stream retains its existing 64-series and 600-point limits.
|
||||
|
||||
| Case | Charts and series | Ring points | Update batch |
|
||||
|---|---|---:|---:|
|
||||
| two-seeded | One chart, two series | 60 | 1 |
|
||||
| two-full-ring | One chart, two series | 600 | 1 |
|
||||
| series-cap | One chart, 64 series | 600 | 1 |
|
||||
| four-charts | Four charts, 16 series each | 600 | 1 |
|
||||
| burst | Four charts, 16 series each | 600 | 16 |
|
||||
| unrelated | One chart, two series; events target another id | 600 | 1 |
|
||||
| extremes | One chart, two series; opposite finite maxima | 600 | 1 |
|
||||
| subnormal | One chart, two series; smallest positive values | 600 | 1 |
|
||||
|
||||
Setup fills real Live rings through ingestSeries before mounting charts.
|
||||
This avoids charging thousands of setup redraws to a steady-state sample.
|
||||
Every timed update arrives through EventSource as a named `series` event
|
||||
and runs the actual chart binding. Charts occupy two equal columns in a
|
||||
1280px viewport, using the normal canvas height from components.css.
|
||||
|
||||
## Measurements
|
||||
|
||||
Output consists of JSON records prefixed with BENCH_PROVENANCE and
|
||||
BENCH_RESULT. Provenance includes the revision, asset hashes and sizes,
|
||||
benchmark hash, Node version, CPU model and browser version. Dirty source
|
||||
is identified by its hashes; a revision alone does not identify it.
|
||||
|
||||
| Field | Measurement |
|
||||
|---|---|
|
||||
| coldMountMs | First bindCharts call on a fresh page after ring setup |
|
||||
| handlerMs | ingestSeries duration, including synchronous chart/readings updates |
|
||||
| deliveryBatchMs | Browser request through the local server to completion of the SSE batch |
|
||||
| parsePropsMs | Parsing all chart props on the page |
|
||||
| chartDataMs | Merging all chart props with their live rings |
|
||||
|
||||
Warmup batches are excluded. Hot-path distributions report count, p50,
|
||||
p95 and maximum milliseconds per independent run. Two animation frames
|
||||
consume the drawn output after each batch; that wait is outside delivery
|
||||
timing. Timings include normal browser allocation and garbage collection.
|
||||
No CPU-frequency or scheduler isolation is claimed. Treat ungated runs
|
||||
as relative diagnostics, not device or CI performance acceptance.
|
||||
|
||||
Every run also checks that SSE updates reached the real ring and latest
|
||||
value table, frame geometry is finite, point counts are bounded, and stream
|
||||
caps remain unchanged. Animation does not rebuild geometry between updates.
|
||||
The existing 24 KiB chart asset cap stays unchanged. There is no new timing
|
||||
budget or automatic baseline update.
|
||||
|
||||
## Hidden table regression
|
||||
|
||||
`visually-hidden.cjs` colors only the caption red and counts painted red
|
||||
pixels in real screenshots. A visible-caption control proves the detector
|
||||
works. The hidden table and row header must remain accessible in both
|
||||
browsers with JavaScript enabled and disabled.
|
||||
|
||||
`--css=/absolute/path/components.css` tests a candidate stylesheet without
|
||||
editing assets. Its exact hash is recorded. Set FLARE_UI_SCREENSHOTS to
|
||||
an output directory to retain screenshots. The PNG reader comes from the
|
||||
pinned Playwright package; no additional dependency is required.
|
||||
|
||||
## Workspace coverage
|
||||
|
||||
The Rust workspace has three benchmark targets:
|
||||
|
||||
```sh
|
||||
cargo bench --locked -p flare-ui --bench chart
|
||||
cargo bench --locked -p wschema --bench canon_hash
|
||||
cargo bench --locked -p warden-sync --bench sync
|
||||
```
|
||||
|
||||
They cover chart props/render, schema parse/canonicalization/hash/lint/
|
||||
tables/corpus, and sync digest/planning/HLC. They do not measure package
|
||||
validation, sealing, OpenAPI generation or editor operations. Keep those
|
||||
coverage gaps explicit when reporting whole-workspace performance.
|
||||
@@ -0,0 +1,21 @@
|
||||
# UI browser checks
|
||||
|
||||
Run from this directory:
|
||||
|
||||
```sh
|
||||
npm ci --ignore-scripts
|
||||
npx playwright install --with-deps chromium firefox
|
||||
npm test
|
||||
```
|
||||
|
||||
The fixtures serve real assets and SSE samples. Their local HTTP proxy gives
|
||||
pages an insecure origin without DNS or hosts-file changes. Both browsers run:
|
||||
|
||||
- Chart geometry, cached animation, reduced motion, cleanup and CSP checks.
|
||||
- Island binding, settings control names and visually hidden caption checks.
|
||||
- Theme, flow parameter form and swapped live-state checks.
|
||||
- Chart benchmark correctness workloads; timing profiles are separate.
|
||||
|
||||
`node chart.cjs --baseline=<commit>` replaces the chart and live assets with
|
||||
that commit's files. The boot asset stays current so the earlier renderer can
|
||||
be tested separately from bootstrap failures.
|
||||
@@ -0,0 +1,250 @@
|
||||
"use strict";
|
||||
const assert = require("node:assert/strict");
|
||||
const crypto = require("node:crypto");
|
||||
const { execFileSync } = require("node:child_process");
|
||||
const fs = require("node:fs");
|
||||
const http = require("node:http");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const { chromium, firefox } = require("playwright");
|
||||
|
||||
const verify = process.argv.includes("--verify");
|
||||
function option(name, fallback, min, max) {
|
||||
const arg = process.argv.find(value => value.startsWith("--" + name + "="));
|
||||
const value = arg ? Number(arg.slice(name.length + 3)) : fallback;
|
||||
assert(Number.isInteger(value) && value >= min && value <= max, "invalid " + name);
|
||||
return value;
|
||||
}
|
||||
const samples = option("samples", verify ? 3 : 20, 2, 1000);
|
||||
const warmup = option("warmup", verify ? 2 : 5, 1, 100);
|
||||
const runs = option("runs", verify ? 1 : 3, 1, 10);
|
||||
const browserArg = process.argv.find(arg => arg.startsWith("--browser="))?.slice(10) || "both";
|
||||
assert(["chromium", "firefox", "both"].includes(browserArg), "invalid browser");
|
||||
const types = [chromium, firefox].filter(type => browserArg === "both" || type.name() === browserArg);
|
||||
const assets = path.resolve(__dirname, "../../assets");
|
||||
const root = path.resolve(__dirname, "../../../..");
|
||||
const origin = "http://flare-ui.test";
|
||||
const sha256 = data => crypto.createHash("sha256").update(data).digest("hex");
|
||||
const assetNames = ["js/live.js", "js/chart.js", "components.css", "tokens.css", "theme.css", "warden-compat.css"];
|
||||
const sources = new Map(assetNames.map(name => ["/" + name, fs.readFileSync(path.join(assets, name))]));
|
||||
assert(sources.get("/js/chart.js").length <= 24576, "the existing chart asset cap must hold");
|
||||
const cases = [
|
||||
{ name: "two-seeded", charts: 1, series: 2, history: 60, burst: 1, range: "normal" },
|
||||
{ name: "two-full-ring", charts: 1, series: 2, history: 600, burst: 1, range: "normal" },
|
||||
{ name: "series-cap", charts: 1, series: 64, history: 600, burst: 1, range: "normal" },
|
||||
{ name: "four-charts", charts: 4, series: 16, history: 600, burst: 1, range: "normal" },
|
||||
{ name: "burst", charts: 4, series: 16, history: 600, burst: 16, range: "normal" },
|
||||
{ name: "unrelated", charts: 1, series: 2, history: 600, burst: 1, range: "normal", unrelated: true },
|
||||
{ name: "extremes", charts: 1, series: 2, history: 600, burst: 1, range: "extreme" },
|
||||
{ name: "subnormal", charts: 1, series: 2, history: 600, burst: 1, range: "subnormal" }
|
||||
];
|
||||
|
||||
function value(index, series, range) {
|
||||
if (range === "extreme") return index % 2 ? Number.MAX_VALUE : -Number.MAX_VALUE;
|
||||
if (range === "subnormal") return Number.MIN_VALUE * (index % 2 + 1);
|
||||
return (index * 13 + series * 7) % 97 + Math.sin(index / 8);
|
||||
}
|
||||
function propsFor(config, chart) {
|
||||
const series = Array.from({ length: config.series }, (_, s) => ({ key: "s" + s,
|
||||
label: "Series " + s, unit: "kW", color: ["#3776BE", "#F26522", "#1E8E4E", "#7046B8"][s % 4] }));
|
||||
return { id: "chart" + chart, series, tier: "min",
|
||||
tiers: { min: { n: 60, step_s: 60 }, hour: { n: 60, step_s: 3600 }, day: { n: 60, step_s: 86400 } },
|
||||
points: Object.fromEntries(series.map((s, n) => [s.key, Array.from({ length: 60 }, (_, i) => [1700000000000 + i * 60000, value(i, n, config.range)])])) };
|
||||
}
|
||||
function attribute(text) {
|
||||
return text.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<").replaceAll(">", ">");
|
||||
}
|
||||
function figure(config, index) {
|
||||
const props = propsFor(config, index);
|
||||
return '<figure class="bf-chart" data-live data-island="chart" data-chart="' + attribute(JSON.stringify(props)) + '">' +
|
||||
'<figcaption>Chart ' + index + '</figcaption><canvas class="bf-chart-canvas" role="img" aria-label="Chart ' + index + '"></canvas>' +
|
||||
'<table class="bf-vh"><caption>Chart ' + index + ' latest values</caption><tbody>' +
|
||||
props.series.map(s => '<tr><th scope="row">' + s.label + '</th><td data-chart-value="' + s.key + '">-- kW</td></tr>').join("") + '</tbody></table></figure>';
|
||||
}
|
||||
|
||||
// This runs in the browser after the unchanged live and chart assets load.
|
||||
function driver(config, readingValue) {
|
||||
const live = new FlareLive.Live("/events?case=" + config.name);
|
||||
const figures = [...document.querySelectorAll("figure")];
|
||||
const raw = figures.map(figure => figure.getAttribute("data-chart"));
|
||||
const props = raw.map(FlareChart.chartProps);
|
||||
if (props.some(p => !p)) throw new Error("invalid benchmark props");
|
||||
// Fill actual bounded rings before binding, avoiding 38400 unmeasured redraws.
|
||||
for (const p of props) for (let s = 0; s < p.series.length; s++) {
|
||||
for (let i = 0; i < config.history; i++) live.ingestSeries(JSON.stringify({ id: p.id, key: "s" + s,
|
||||
p: [1700000000000 + i * 60000, readingValue(i, s, config.range)] }));
|
||||
}
|
||||
const bench = window.benchmark = { ready: false, durations: [], last: null, waiter: null, live };
|
||||
const ingest = live.ingestSeries.bind(live);
|
||||
live.ingestSeries = data => {
|
||||
const start = performance.now();
|
||||
ingest(data);
|
||||
bench.durations.push(performance.now() - start);
|
||||
bench.last = JSON.parse(data);
|
||||
if (bench.waiter && bench.durations.length >= bench.waiter.target) {
|
||||
const resolve = bench.waiter.resolve;
|
||||
bench.waiter = null;
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
const mount = performance.now();
|
||||
const stop = FlareChart.bindCharts(live, document);
|
||||
bench.mountMs = performance.now() - mount;
|
||||
live.start();
|
||||
live.es.addEventListener("open", () => { bench.ready = true; });
|
||||
bench.sample = async count => {
|
||||
const offset = bench.durations.length;
|
||||
let timer;
|
||||
const done = new Promise((resolve, reject) => {
|
||||
bench.waiter = { target: offset + count, resolve };
|
||||
timer = setTimeout(() => reject(new Error("SSE batch timed out")), 30000);
|
||||
});
|
||||
const start = performance.now();
|
||||
try {
|
||||
const response = fetch("/emit?case=" + config.name + "&count=" + count).then(response => {
|
||||
if (!response.ok) throw new Error("emit failed: " + response.status);
|
||||
});
|
||||
await Promise.all([done, response]);
|
||||
const deliveryMs = performance.now() - start;
|
||||
const frames = figures.map(figure => figure.querySelector("canvas").__cframe);
|
||||
// Two frames consume the painted result; this wait is outside delivery timing.
|
||||
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
if (figures.some((figure, i) => figure.querySelector("canvas").__cframe !== frames[i])) {
|
||||
throw new Error("animation rebuilt geometry between events");
|
||||
}
|
||||
return { deliveryMs, handlerMs: bench.durations.slice(offset) };
|
||||
} finally { clearTimeout(timer); bench.waiter = null; }
|
||||
};
|
||||
bench.inspect = () => {
|
||||
const last = bench.last;
|
||||
const ring = live.chartSamples(last.id, last.key);
|
||||
if (ring.at(-1).t !== last.p[0] || ring.at(-1).v !== last.p[1]) throw new Error("SSE output was not consumed");
|
||||
if (!config.unrelated) {
|
||||
const index = Number(last.id.slice(5));
|
||||
const cell = figures[index].querySelector('[data-chart-value="' + last.key + '"]');
|
||||
if (cell.textContent !== FlareChart.formatValue(last.p[1]) + " kW") throw new Error("latest table value drifted");
|
||||
}
|
||||
const frames = figures.map(figure => figure.querySelector("canvas").__cframe);
|
||||
for (const frame of frames) {
|
||||
if (!frame || !Number.isFinite(frame.yMax - frame.yMin) || frame.yMax <= frame.yMin) throw new Error("invalid frame range");
|
||||
if (frame.series.length !== config.series) throw new Error("series lost");
|
||||
const limit = 71 * Math.max(12, Math.ceil(frame.dx / 2)) + 1;
|
||||
for (const s of frame.series) {
|
||||
if (s.pts.length > limit || s.pts.some(p => !Number.isFinite(p.x) || !Number.isFinite(p.y))) throw new Error("unbounded or nonfinite geometry");
|
||||
}
|
||||
}
|
||||
if (live.seriesCount > 64 || ring.length > 600 || live.dropped) throw new Error("stream capacity changed");
|
||||
return { events: bench.durations.length, series: live.seriesCount, lastRing: ring.length,
|
||||
frames: frames.length, points: frames.reduce((total, f) => total + f.series.reduce((n, s) => n + s.pts.length, 0), 0) };
|
||||
};
|
||||
bench.micro = count => {
|
||||
const parse = [], merge = [];
|
||||
let checksum = 0;
|
||||
for (let i = 0; i < count; i++) {
|
||||
let start = performance.now();
|
||||
for (const text of raw) checksum += FlareChart.chartProps(text).series.length;
|
||||
parse.push(performance.now() - start);
|
||||
start = performance.now();
|
||||
for (const p of props) checksum += FlareChart.chartData(p, live).series.reduce((n, s) => n + s.data.length, 0);
|
||||
merge.push(performance.now() - start);
|
||||
}
|
||||
return { parse, merge, checksum };
|
||||
};
|
||||
bench.stop = () => { stop(); live.close(); };
|
||||
}
|
||||
|
||||
const clients = new Map();
|
||||
const server = http.createServer((request, response) => {
|
||||
const url = new URL(request.url, origin);
|
||||
const config = cases.find(item => item.name === url.searchParams.get("case"));
|
||||
if (url.origin !== origin) { response.writeHead(404); response.end(); return; }
|
||||
if (sources.has(url.pathname)) {
|
||||
response.writeHead(200, { "content-type": url.pathname.endsWith(".css") ? "text/css" : "text/javascript" });
|
||||
response.end(sources.get(url.pathname));
|
||||
} else if (url.pathname === "/bench.css") {
|
||||
response.writeHead(200, { "content-type": "text/css" });
|
||||
response.end("main {display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px} .bf-chart {min-width:0}");
|
||||
} else if (url.pathname === "/driver.js" && config) {
|
||||
response.writeHead(200, { "content-type": "text/javascript" });
|
||||
response.end("(" + driver.toString() + ")(" + JSON.stringify(config) + "," + value.toString() + ");");
|
||||
} else if (url.pathname === "/events" && config) {
|
||||
response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store" });
|
||||
response.write(": ready\n\n");
|
||||
const client = { response, sequence: config.history };
|
||||
clients.set(config.name, client);
|
||||
response.on("close", () => { if (clients.get(config.name) === client) clients.delete(config.name); });
|
||||
} else if (url.pathname === "/emit" && config && clients.has(config.name)) {
|
||||
const count = Number(url.searchParams.get("count"));
|
||||
if (!Number.isInteger(count) || count < 1 || count > 64) { response.writeHead(400); response.end(); return; }
|
||||
const client = clients.get(config.name);
|
||||
let packet = "";
|
||||
for (let i = 0; i < count; i++) {
|
||||
const seq = client.sequence++, series = seq % (config.charts * config.series);
|
||||
const point = { id: config.unrelated ? "unmounted" : "chart" + Math.floor(series / config.series),
|
||||
key: config.unrelated ? "outside" : "s" + series % config.series,
|
||||
p: [1700000000000 + seq * 60000, value(seq, series % config.series, config.range)] };
|
||||
packet += "event: series\ndata: " + JSON.stringify(point) + "\n\n";
|
||||
}
|
||||
client.response.write(packet);
|
||||
response.writeHead(200); response.end("ok");
|
||||
} else if (url.pathname === "/" && config) {
|
||||
response.writeHead(200, { "content-type": "text/html",
|
||||
"content-security-policy": "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; base-uri 'none'; object-src 'none'" });
|
||||
response.end('<!doctype html><html lang="en"><head><meta name="viewport" content="width=device-width, initial-scale=1">' +
|
||||
assetNames.filter(name => name.endsWith(".css")).map(name => '<link rel="stylesheet" href="/' + name + '">').join("") +
|
||||
'<link rel="stylesheet" href="/bench.css"><script src="/js/live.js" defer></script><script src="/js/chart.js" defer></script>' +
|
||||
'<script src="/driver.js?case=' + config.name + '" defer></script></head><body><main>' +
|
||||
Array.from({ length: config.charts }, (_, i) => figure(config, i)).join("") + '</main></body></html>');
|
||||
} else if (url.pathname === "/favicon.ico") { response.writeHead(204); response.end(); }
|
||||
else { response.writeHead(404); response.end(); }
|
||||
});
|
||||
server.on("connect", (_, socket) => socket.end("HTTP/1.1 403 Forbidden\r\n\r\n"));
|
||||
|
||||
function distribution(values) {
|
||||
assert(values.length && values.every(Number.isFinite), "measurements must be finite");
|
||||
const sorted = [...values].sort((a, b) => a - b);
|
||||
const at = p => Number(sorted[Math.ceil(p * sorted.length) - 1].toFixed(3));
|
||||
return { n: sorted.length, p50: at(.5), p95: at(.95), max: at(1) };
|
||||
}
|
||||
|
||||
(async () => {
|
||||
console.log("BENCH_PROVENANCE", JSON.stringify({ mode: verify ? "verification" : "ungated-profile", samples, warmup, runs,
|
||||
revision: execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8" }).trim(),
|
||||
node: process.version, platform: os.platform(), arch: os.arch(), cpu: os.cpus()[0]?.model,
|
||||
source: Object.fromEntries([...sources].map(([name, body]) => [name, { bytes: body.length, sha256: sha256(body) }])),
|
||||
benchmarkSha256: sha256(fs.readFileSync(__filename)) }));
|
||||
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
|
||||
try {
|
||||
for (const type of types) for (let run = 0; run < runs; run++) {
|
||||
const browser = await type.launch({ headless: true,
|
||||
proxy: { server: "http://127.0.0.1:" + server.address().port } });
|
||||
try {
|
||||
for (const config of cases) for (const reduced of [false, true]) {
|
||||
const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, reducedMotion: reduced ? "reduce" : "no-preference" });
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
try {
|
||||
await page.goto(origin + "/?case=" + config.name);
|
||||
await page.waitForFunction(() => window.benchmark?.ready, null, { timeout: 30000 });
|
||||
const coldMountMs = await page.evaluate(() => benchmark.mountMs);
|
||||
for (let i = 0; i < warmup; i++) await page.evaluate(count => benchmark.sample(count), config.burst);
|
||||
const measurements = [];
|
||||
for (let i = 0; i < samples; i++) measurements.push(await page.evaluate(count => benchmark.sample(count), config.burst));
|
||||
const state = await page.evaluate(() => benchmark.inspect());
|
||||
const micro = await page.evaluate(count => benchmark.micro(count), samples + warmup);
|
||||
assert.equal(state.events, (samples + warmup) * config.burst);
|
||||
assert(micro.checksum > 0);
|
||||
assert.deepEqual(errors, []);
|
||||
const result = { browser: type.name(), version: browser.version(), run, case: config.name, reduced, state };
|
||||
if (!verify) Object.assign(result, { coldMountMs, handlerMs: distribution(measurements.flatMap(m => m.handlerMs)),
|
||||
deliveryBatchMs: distribution(measurements.map(m => m.deliveryMs)),
|
||||
parsePropsMs: distribution(micro.parse.slice(warmup)), chartDataMs: distribution(micro.merge.slice(warmup)) });
|
||||
console.log("BENCH_RESULT", JSON.stringify(result));
|
||||
await page.evaluate(() => benchmark.stop());
|
||||
} finally { await page.close(); }
|
||||
}
|
||||
} finally { await browser.close(); }
|
||||
}
|
||||
} finally { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
|
||||
console.log("PASS chart benchmark workloads");
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1,297 @@
|
||||
"use strict";
|
||||
const assert = require("node:assert/strict");
|
||||
const { execFileSync } = require("node:child_process");
|
||||
const fs = require("node:fs");
|
||||
const http = require("node:http");
|
||||
const path = require("node:path");
|
||||
const { chromium, firefox } = require("playwright");
|
||||
|
||||
const origin = "http://flare-ui.test";
|
||||
const assets = path.resolve(__dirname, "../../assets/js");
|
||||
const baseline = process.argv.find(arg => arg.startsWith("--baseline="))?.split("=")[1];
|
||||
if (baseline && !/^[0-9a-f]{40}$/.test(baseline)) throw new Error("baseline must be a full commit id");
|
||||
const sources = new Map(["live.js", "islands.js", "chart.js", "boot.js"].map(name => {
|
||||
const source = baseline && (name === "chart.js" || name === "live.js")
|
||||
? execFileSync("git", ["show", baseline + ":crates/flare-ui/assets/js/" + name])
|
||||
: fs.readFileSync(path.join(assets, name));
|
||||
return ["/" + name, source];
|
||||
}));
|
||||
const css = fs.readFileSync(path.resolve(assets, "../components.css"));
|
||||
const timeout = Math.min(30000, Math.max(1000, Number(process.env.FLARE_UI_BROWSER_TIMEOUT_MS) || 10000));
|
||||
const seriesClients = new Set();
|
||||
|
||||
// The fixture is also the browser's HTTP proxy. The test origin stays outside
|
||||
// localhost's secure-context exception without a DNS or hosts-file change.
|
||||
const server = http.createServer((request, response) => {
|
||||
const url = new URL(request.url, origin);
|
||||
if (url.origin !== origin) { response.writeHead(404); response.end(); return; }
|
||||
if (url.pathname === "/series") {
|
||||
response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store" });
|
||||
response.write(": ready\n\n");
|
||||
seriesClients.add(response);
|
||||
response.on("close", () => seriesClients.delete(response));
|
||||
} else if (url.pathname === "/emit") {
|
||||
const payload = url.searchParams.has("invalid") ? '{"id":"traffic","key":"rx","p":[1e400,999]}' :
|
||||
JSON.stringify({ id: url.searchParams.get("id") || "traffic", key: url.searchParams.get("key") || "rx", p: [3000, 4] });
|
||||
const boundaries = { flat: [1e20, 1e20], maximum: [Number.MAX_VALUE, Number.MAX_VALUE],
|
||||
opposite: [-Number.MAX_VALUE, Number.MAX_VALUE], subnormal: [Number.MIN_VALUE, Number.MIN_VALUE * 2] };
|
||||
const boundary = url.searchParams.get("boundary");
|
||||
const values = Object.hasOwn(boundaries, boundary) ? boundaries[boundary] : null;
|
||||
const packets = values ? values.map((v, i) => JSON.stringify({ id: "traffic", key: "rx", p: [(i + 1) * 1000, v] })) : [payload];
|
||||
for (const client of seriesClients) for (const packet of packets) client.write("event: series\ndata: " + packet + "\n\n");
|
||||
response.writeHead(200); response.end("ok");
|
||||
} else if (url.pathname === "/network/traffic") {
|
||||
const tier = ["min", "hour", "day"].includes(url.searchParams.get("tier")) ? url.searchParams.get("tier") : "hour";
|
||||
let figure = fs.readFileSync(path.join(__dirname, "../golden/chart-" + tier + ".html"), "utf8");
|
||||
const count = Number(url.searchParams.get("seed"));
|
||||
if ([1, 2, 3].includes(count)) {
|
||||
const attribute = /data-chart="([^"]*)"/.exec(figure)[1];
|
||||
const props = JSON.parse(attribute.replaceAll(""", '"').replaceAll("&", "&"));
|
||||
props.points = { rx: Array.from({ length: count }, (_, i) => [(i + 1) * 1000, i + 1]) };
|
||||
figure = figure.replace(attribute, JSON.stringify(props).replaceAll("&", "&").replaceAll('"', """))
|
||||
.replace('data-chart-value="rx">2 B/s', 'data-chart-value="rx">' + count + ' B/s');
|
||||
}
|
||||
const control = Number(url.searchParams.get("bad"));
|
||||
const stream = [9, 10, 13].includes(control) ? "/&#" + control + ";/outside.example/stream" : "/series";
|
||||
response.writeHead(200, { "content-type": "text/html",
|
||||
"content-security-policy": "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self'; img-src 'self'; base-uri 'none'; object-src 'none'" });
|
||||
response.end('<!doctype html><html><head><meta name="bf-stream" content="' + stream + '">' +
|
||||
'<link rel="stylesheet" href="/components.css">' + [...sources.keys()].map(name => '<script src="' + name + '" defer></script>').join("") +
|
||||
'</head><body>' + figure + figure.replaceAll("traffic", "other") + '</body></html>');
|
||||
} else if (url.pathname === "/events") {
|
||||
const points = Array.from({ length: 60 }, (_, i) => ({ k: "pressure", t: i * 1000, v: 25 + 10 * Math.sin(i / 5) }));
|
||||
points[59].v = 42.5;
|
||||
let data = JSON.stringify(points);
|
||||
if (url.searchParams.has("invalid")) data = data.slice(0, -1) + ',{"k":"pressure","v":999,"t":1e400}]';
|
||||
response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store" });
|
||||
response.write("data: " + data + "\n\n");
|
||||
} else if (url.pathname === "/") {
|
||||
const defer = url.searchParams.get("mode") === "defer" ? " defer" : "";
|
||||
const stream = url.searchParams.has("invalid") ? "/events?invalid=1" : "/events";
|
||||
response.writeHead(200, {
|
||||
"content-type": "text/html",
|
||||
"content-security-policy": "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self'; img-src 'self'; base-uri 'none'; object-src 'none'"
|
||||
});
|
||||
response.end('<!doctype html><html><head><meta name="bf-stream" content="' + stream + '">' +
|
||||
[...sources.keys()].map(name => '<script src="' + name + '"' + defer + '></script>').join("") +
|
||||
'</head><body><div data-live data-key="pressure"><span class="bf-kv-value">1 psi</span></div>' +
|
||||
'<figure data-live data-island="chart" data-key="pressure"><canvas width="240" height="120" aria-label="Pressure"></canvas></figure></body></html>');
|
||||
} else if (url.pathname === "/components.css") {
|
||||
response.writeHead(200, { "content-type": "text/css" }); response.end(css);
|
||||
} else if (sources.has(url.pathname)) {
|
||||
response.writeHead(200, { "content-type": "text/javascript" }); response.end(sources.get(url.pathname));
|
||||
} else if (url.pathname === "/favicon.ico") {
|
||||
response.writeHead(204); response.end();
|
||||
} else { response.writeHead(404); response.end(); }
|
||||
});
|
||||
server.on("connect", (_, socket) => socket.end("HTTP/1.1 403 Forbidden\r\n\r\n"));
|
||||
|
||||
async function check(browser, mode, reduced, tier, invalid) {
|
||||
const page = await browser.newPage({ reducedMotion: reduced ? "reduce" : "no-preference" });
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
const trace = window.chartTrace = { blits: 0, lines: 0, requests: 0, csp: [] };
|
||||
const prototype = CanvasRenderingContext2D.prototype;
|
||||
for (const [method, key] of [["drawImage", "blits"], ["lineTo", "lines"]]) {
|
||||
const original = prototype[method];
|
||||
prototype[method] = function (...args) { trace[key]++; return original.apply(this, args); };
|
||||
}
|
||||
const request = window.requestAnimationFrame.bind(window);
|
||||
window.requestAnimationFrame = callback => { trace.requests++; return request(callback); };
|
||||
document.addEventListener("securitypolicyviolation", event => trace.csp.push(event.violatedDirective));
|
||||
});
|
||||
try {
|
||||
await page.goto(origin + "/?mode=" + mode + "&tier=" + tier + (invalid ? "&invalid=1" : ""));
|
||||
await page.waitForFunction(() => document.querySelector(".bf-kv-value").textContent === "42.5 psi", null, { timeout });
|
||||
await page.waitForFunction(() => !!document.querySelector("canvas").__cframe, null, { timeout });
|
||||
assert.equal(await page.evaluate(() => isSecureContext), false);
|
||||
const frame = await page.evaluate(() => {
|
||||
const canvas = document.querySelector("canvas"), frame = canvas.__cframe;
|
||||
return { points: frame.series[0].pts.length, vel: frame.vel, top: frame.yMax,
|
||||
pixels: canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height).data.some(value => value !== 0),
|
||||
trace: { ...chartTrace } };
|
||||
});
|
||||
assert(frame.points > 60, "the live binding must use spline geometry");
|
||||
assert(frame.top < 100, "invalid timestamps must not enter the chart");
|
||||
assert(frame.pixels, "the chart must paint real pixels");
|
||||
if (!reduced && tier === "min") {
|
||||
await page.waitForFunction(count => chartTrace.blits > count, frame.trace.blits, { timeout });
|
||||
} else await page.waitForTimeout(120);
|
||||
const later = await page.evaluate(() => ({ ...chartTrace }));
|
||||
assert.equal(later.lines, frame.trace.lines, "animation must not rebuild geometry");
|
||||
if (reduced || tier !== "min") {
|
||||
assert.equal(frame.vel, 0);
|
||||
assert.equal(later.requests, 0, "static charts must not start an animation loop");
|
||||
} else {
|
||||
assert(frame.vel > 0);
|
||||
assert(later.blits > frame.trace.blits);
|
||||
await page.emulateMedia({ reducedMotion: "reduce" });
|
||||
await page.waitForFunction(() => document.querySelector("canvas").__cframe.vel === 0, null, { timeout });
|
||||
}
|
||||
await page.evaluate(() => {
|
||||
const figure = document.querySelector("figure");
|
||||
document.dispatchEvent(new CustomEvent("htmx:beforeCleanupElement", { detail: { elt: figure } }));
|
||||
figure.remove();
|
||||
});
|
||||
const afterCleanup = await page.evaluate(() => chartTrace.requests);
|
||||
await page.waitForTimeout(80);
|
||||
assert.equal(await page.evaluate(() => chartTrace.requests), afterCleanup);
|
||||
assert.deepEqual(await page.evaluate(() => chartTrace.csp), []);
|
||||
assert.deepEqual(errors, []);
|
||||
} catch (error) {
|
||||
error.message += " " + JSON.stringify({ mode, reduced, tier, invalid, errors,
|
||||
state: await page.evaluate(() => ({ reading: document.querySelector(".bf-kv-value")?.textContent,
|
||||
frame: !!document.querySelector("canvas")?.__cframe, csp: window.chartTrace?.csp })).catch(() => null) });
|
||||
throw error;
|
||||
} finally { await page.close(); }
|
||||
}
|
||||
|
||||
async function contract(browser) {
|
||||
const nojs = await browser.newPage({ javaScriptEnabled: false });
|
||||
try {
|
||||
await nojs.goto(origin + "/network/traffic?tier=hour");
|
||||
assert.equal(await nojs.locator('#traffic [data-chart-value="rx"]').textContent(), "2 B/s");
|
||||
assert.equal(await nojs.locator('#traffic [data-chart-value="constructor"]').textContent(), "-- B/s");
|
||||
assert.equal(await nojs.locator('#traffic a[aria-current="page"]').getAttribute("href"), "/network/traffic?tier=hour");
|
||||
await nojs.locator('#traffic a[href$="tier=day"]').click();
|
||||
assert.equal(new URL(nojs.url()).searchParams.get("tier"), "day");
|
||||
assert.equal(await nojs.locator('#traffic a[aria-current="page"]').textContent(), "day");
|
||||
} finally { await nojs.close(); }
|
||||
for (const reduced of [false, true]) {
|
||||
const page = await browser.newPage({ reducedMotion: reduced ? "reduce" : "no-preference" });
|
||||
const errors = [], csp = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.violations = [];
|
||||
document.addEventListener("securitypolicyviolation", event => violations.push(event.violatedDirective));
|
||||
});
|
||||
try {
|
||||
const ready = page.waitForResponse(response => response.url() === origin + "/series");
|
||||
await page.goto(origin + "/network/traffic?tier=min");
|
||||
await ready;
|
||||
await page.waitForFunction(() => !!document.querySelector("#traffic canvas").__cframe, null, { timeout });
|
||||
const initial = await page.locator("#traffic canvas").evaluate(cv => ({
|
||||
count: cv.__cframe.series.length, pts: cv.__cframe.series[0].pts.length,
|
||||
colors: cv.__cframe.series.map(s => s.color), vel: cv.__cframe.vel
|
||||
}));
|
||||
assert.equal(initial.count, 2); assert(initial.pts > 2);
|
||||
assert.deepEqual(initial.colors, ["#3776BE", "#F26522"]);
|
||||
assert.equal(initial.vel, 0, "short seeded histories are visible before the feed");
|
||||
await page.evaluate(() => fetch("/emit"));
|
||||
await page.waitForFunction(() => document.querySelector('#traffic [data-chart-value="rx"]').textContent === "4 B/s", null, { timeout });
|
||||
assert.equal(await page.locator('#other [data-chart-value="rx"]').textContent(), "2 B/s");
|
||||
await page.evaluate(() => fetch("/emit?id=traffic&key=constructor"));
|
||||
await page.waitForFunction(() => document.querySelector('#traffic [data-chart-value="constructor"]').textContent === "4 B/s", null, { timeout });
|
||||
await page.evaluate(() => fetch("/emit?invalid=1"));
|
||||
await page.waitForTimeout(60);
|
||||
assert.equal(await page.locator('#traffic [data-chart-value="rx"]').textContent(), "4 B/s");
|
||||
await page.emulateMedia({ reducedMotion: "reduce" });
|
||||
await page.waitForFunction(() => document.querySelector("#traffic canvas").__cframe.vel === 0, null, { timeout });
|
||||
csp.push(...await page.evaluate(() => violations));
|
||||
assert.deepEqual(csp, []); assert.deepEqual(errors, []);
|
||||
} finally { await page.close(); }
|
||||
}
|
||||
}
|
||||
|
||||
async function boundaries(browser) {
|
||||
for (const name of ["flat", "maximum", "opposite", "subnormal"]) {
|
||||
const page = await browser.newPage({ reducedMotion: "reduce" }), errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
try {
|
||||
const ready = page.waitForResponse(response => response.url() === origin + "/series");
|
||||
await page.goto(origin + "/network/traffic?tier=min"); await ready;
|
||||
await page.evaluate(name => fetch("/emit?boundary=" + name), name);
|
||||
const expected = name === "flat" ? "100000000000000000000 B/s" :
|
||||
name === "subnormal" ? "0 B/s" : "1.7976931348623157e+308 B/s";
|
||||
await page.waitForFunction(expected => document.querySelector('#traffic [data-chart-value="rx"]').textContent === expected, expected, { timeout });
|
||||
const frame = await page.locator("#traffic canvas").evaluate(cv => {
|
||||
const f = cv.__cframe;
|
||||
return { span: f.yMax - f.yMin,
|
||||
finite: f.series.every(s => s.pts.every(p => Number.isFinite(p.x) && Number.isFinite(p.y)) &&
|
||||
(!s.endpoint || (Number.isFinite(s.endpoint.x) && Number.isFinite(s.endpoint.y)))),
|
||||
pixels: cv.getContext("2d").getImageData(0, 0, cv.width, cv.height).data.some(v => v !== 0) };
|
||||
});
|
||||
assert(Number.isFinite(frame.span) && frame.span > 0); assert(frame.finite); assert(frame.pixels);
|
||||
for (const color of [{ toString: 0 }, ["#abc"]]) {
|
||||
assert.equal(await page.evaluate(color => {
|
||||
const figure = document.querySelector("#traffic"), p = JSON.parse(figure.getAttribute("data-chart"));
|
||||
p.series[0].color = color; figure.setAttribute("data-chart", JSON.stringify(p));
|
||||
document.dispatchEvent(new CustomEvent("htmx:afterSwap"));
|
||||
return FlareChart.chartProps(figure.getAttribute("data-chart"));
|
||||
}, color), null);
|
||||
}
|
||||
await page.evaluate(() => fetch("/emit?id=other"));
|
||||
await page.waitForFunction(() => document.querySelector('#other [data-chart-value="rx"]').textContent === "4 B/s", null, { timeout });
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS chart numeric boundary", browser.browserType().name(), name);
|
||||
} finally { await page.close(); }
|
||||
}
|
||||
}
|
||||
|
||||
async function firstPaint(browser) {
|
||||
for (const count of [1, 2, 3]) {
|
||||
const page = await browser.newPage({ reducedMotion: "no-preference" });
|
||||
try {
|
||||
await page.goto(origin + "/network/traffic?tier=min&seed=" + count);
|
||||
await page.waitForFunction(() => !!document.querySelector("#traffic canvas").__cframe, null, { timeout });
|
||||
const observed = await page.locator("#traffic canvas").evaluate(cv => {
|
||||
const pixels = cv.getContext("2d").getImageData(0, 0, cv.width, cv.height).data;
|
||||
let blue = 0;
|
||||
for (let i = 0; i < pixels.length; i += 4) {
|
||||
if (pixels[i] < 100 && pixels[i + 1] > 70 && pixels[i + 1] < 180 && pixels[i + 2] > 150 && pixels[i + 3]) blue++;
|
||||
}
|
||||
return { blue, velocity: cv.__cframe.vel };
|
||||
});
|
||||
assert(observed.blue > 0, "seeded series must paint its own pixels");
|
||||
assert.equal(observed.velocity, 0);
|
||||
assert(await page.locator("#traffic").evaluate(el => el.classList.contains("bf-stale")));
|
||||
await page.evaluate(() => fetch("/emit"));
|
||||
await page.waitForFunction(() => !document.querySelector("#traffic").classList.contains("bf-stale"), null, { timeout });
|
||||
console.log("PASS seeded first paint", browser.browserType().name(), count, observed.blue);
|
||||
} finally { await page.close(); }
|
||||
}
|
||||
for (const code of [9, 10, 13]) {
|
||||
const page = await browser.newPage();
|
||||
try {
|
||||
await page.addInitScript(() => {
|
||||
const Original = window.EventSource;
|
||||
window.streamAttempts = [];
|
||||
window.EventSource = class extends Original {
|
||||
constructor(url, options) { window.streamAttempts.push(String(url)); super(url, options); }
|
||||
};
|
||||
});
|
||||
await page.goto(origin + "/network/traffic?bad=" + code);
|
||||
assert.deepEqual(await page.evaluate(() => window.streamAttempts), []);
|
||||
console.log("PASS stream origin refusal", browser.browserType().name(), code);
|
||||
} finally { await page.close(); }
|
||||
}
|
||||
}
|
||||
|
||||
(async () => {
|
||||
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
|
||||
try {
|
||||
for (const type of [chromium, firefox]) {
|
||||
const browser = await type.launch({ headless: true,
|
||||
proxy: { server: "http://127.0.0.1:" + server.address().port } });
|
||||
try {
|
||||
for (const [mode, reduced, tier, invalid] of [
|
||||
["loading", false, "min", false], ["defer", false, "min", true],
|
||||
["defer", true, "min", false], ["defer", false, "hour", false]
|
||||
]) {
|
||||
await check(browser, mode, reduced, tier, invalid);
|
||||
console.log("PASS chart browser", type.name(), mode, reduced ? "reduced" : tier, invalid ? "invalid timestamp" : "valid data");
|
||||
}
|
||||
if (!baseline) {
|
||||
await contract(browser);
|
||||
console.log("PASS chart contract", type.name(), "SSR/no-JS/tier navigation/seeded/multi-series/named SSE/id isolation/reduced motion");
|
||||
await boundaries(browser);
|
||||
await firstPaint(browser);
|
||||
}
|
||||
} finally { await browser.close(); }
|
||||
}
|
||||
} finally {
|
||||
server.closeAllConnections();
|
||||
await new Promise(resolve => server.close(resolve));
|
||||
}
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1,67 @@
|
||||
"use strict";
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const http = require("node:http");
|
||||
const path = require("node:path");
|
||||
const { chromium, firefox } = require("playwright");
|
||||
|
||||
const source = fs.readFileSync(path.join(__dirname, "../../assets/js/islands.js"));
|
||||
const server = http.createServer((request, response) => {
|
||||
const url = new URL(request.url, "http://127.0.0.1");
|
||||
if (url.pathname === "/islands.js") {
|
||||
response.writeHead(200, { "content-type": "text/javascript" }); response.end(source);
|
||||
} else if (url.pathname === "/bind.js") {
|
||||
response.writeHead(200, { "content-type": "text/javascript" });
|
||||
response.end("FlareIslands.bindTableSort(document, location);");
|
||||
} else {
|
||||
response.writeHead(200, { "content-type": "text/html" });
|
||||
response.end('<!doctype html><html><head><script src="/islands.js" defer></script>' +
|
||||
'<script src="/bind.js" defer></script></head><body><table><thead><tr>' +
|
||||
'<th data-sort="name">Name</th><th data-sort="date"><a href="/table?native=kept">Date</a></th>' +
|
||||
'</tr></thead><tbody><tr><td>A</td><td>Today</td></tr></tbody></table>' +
|
||||
'<a href="#after" id="after">After table</a></body></html>');
|
||||
}
|
||||
});
|
||||
|
||||
(async () => {
|
||||
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
|
||||
const origin = "http://127.0.0.1:" + server.address().port;
|
||||
try {
|
||||
for (const type of [chromium, firefox]) {
|
||||
const browser = await type.launch({ headless: true });
|
||||
const page = await browser.newPage(), errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
try {
|
||||
for (const query of ["?q=%", "?sort=%E0%A4%A", "?dir=asc&q=%GG"]) {
|
||||
await page.goto(origin + "/table" + query);
|
||||
assert.equal(await page.getByRole("button", { name: "Name", exact: true }).count(), 1);
|
||||
await page.keyboard.press("Tab");
|
||||
assert.equal(await page.evaluate(() => document.activeElement.tagName), "BUTTON");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.waitForURL(url => url.searchParams.get("sort") === "name");
|
||||
assert.equal(new URL(page.url()).searchParams.get("dir"), "asc");
|
||||
if (query === "?q=%") assert.equal(new URL(page.url()).searchParams.get("q"), "%");
|
||||
}
|
||||
await page.goto(origin + "/table?sort=name&dir=asc");
|
||||
await page.evaluate(() => {
|
||||
FlareIslands.bindTableSort(document, location);
|
||||
FlareIslands.bindTableSort(document, location);
|
||||
});
|
||||
assert.equal(await page.getByRole("button", { name: "Name", exact: true }).count(), 1);
|
||||
assert.equal(await page.getByRole("columnheader").count(), 2);
|
||||
assert.equal(await page.getByRole("button", { name: "Date", exact: true }).count(), 0);
|
||||
await page.keyboard.press("Tab");
|
||||
await page.keyboard.press("Space");
|
||||
await page.waitForURL(url => url.searchParams.get("dir") === "desc");
|
||||
await page.goto(origin + "/table");
|
||||
await page.keyboard.press("Tab");
|
||||
await page.keyboard.press("Tab");
|
||||
assert.equal(await page.evaluate(() => document.activeElement.textContent), "Date");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.waitForURL(url => url.searchParams.get("native") === "kept");
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS table keyboard and malformed queries", type.name());
|
||||
} finally { await browser.close(); }
|
||||
}
|
||||
} finally { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"name": "flare-ui-browser-tests",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "flare-ui-browser-tests",
|
||||
"devDependencies": {
|
||||
"playwright": "1.62.1"
|
||||
}
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.62.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz",
|
||||
"integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.62.1"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.62.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz",
|
||||
"integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "flare-ui-browser-tests",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"test": "node chart.cjs && node islands.cjs && node render.cjs && node visually-hidden.cjs && node theme-form.cjs && node benchmark.cjs --verify"
|
||||
},
|
||||
"devDependencies": {
|
||||
"playwright": "1.62.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
"use strict";
|
||||
const assert = require("node:assert/strict");
|
||||
const { execFileSync } = require("node:child_process");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { chromium, firefox } = require("playwright");
|
||||
const { expect } = require("playwright/test");
|
||||
|
||||
const baseline = process.argv.find(arg => arg.startsWith("--baseline="))?.split("=")[1];
|
||||
if (baseline && !/^[0-9a-f]{40}$/.test(baseline)) throw new Error("baseline must be a full commit id");
|
||||
const fixtures = path.resolve(__dirname, "../golden/render");
|
||||
const assets = path.resolve(__dirname, "../../assets");
|
||||
const css = ["tokens.css", "components.css"].map(name => fs.readFileSync(path.join(assets, name), "utf8")).join("\n");
|
||||
const artifacts = process.env.FLARE_UI_RENDER_ARTIFACTS;
|
||||
if (artifacts) fs.mkdirSync(artifacts, { recursive: true });
|
||||
const cases = [
|
||||
["text", "textbox"], ["secret", "textbox"], ["dropdown", "combobox"],
|
||||
["segmented", "radiogroup"], ["swatch", "radiogroup"], ["switch", "checkbox"],
|
||||
["slider", "slider"], ["stepper", "spinbutton"], ["number", "spinbutton"],
|
||||
["list", "textbox"], ["intset", "combobox"],
|
||||
];
|
||||
const values = { "t.text": "hi <b>", "t.secret": "", "t.dropdown": "b", "t.segmented": "a",
|
||||
"t.swatch": "c", "t.switch": "true", "t.slider": "5", "t.stepper": "3", "t.number": "7",
|
||||
"t.list": "x\ny", "t.intset": "2" };
|
||||
const label = key => baseline ? "Label" : `Setting t.${key} <&> "quoted"`;
|
||||
const help = key => baseline ? "Some help" : `Help for t.${key} <&> "quoted"`;
|
||||
const error = key => `Invalid t.${key} <&> "quoted"`;
|
||||
const failures = [];
|
||||
let checks = 0;
|
||||
|
||||
function fixture(mode) {
|
||||
if (baseline) {
|
||||
return cases.map(([key]) => execFileSync("git", ["show",
|
||||
`${baseline}:crates/flare-ui/tests/golden/render/${key}.html`], { encoding: "utf8" })).join("");
|
||||
}
|
||||
return fs.readFileSync(path.join(fixtures, mode + ".html"), "utf8");
|
||||
}
|
||||
|
||||
async function check(name, action) {
|
||||
checks++;
|
||||
try { await action(); } catch (failure) {
|
||||
failures.push(name + ": " + failure.message.split("\n").find(line => line.trim()));
|
||||
}
|
||||
}
|
||||
|
||||
function form(body, name) {
|
||||
return `<form data-form="${name}"><input type="hidden" name="_csrf" value="csrf-fixture">${body}</form>`;
|
||||
}
|
||||
|
||||
async function fieldCheck(scope, mode, key, role) {
|
||||
const field = scope.locator(`[data-path="t.${key}"]`);
|
||||
const control = role === "radiogroup" ? field.getByRole(role) : field.locator("input,select,textarea").first();
|
||||
await expect(control).toHaveAccessibleName(label(key), { timeout: 250 });
|
||||
await expect(control).toHaveAccessibleDescription(help(key) + (mode === "form_errors" ? " " + error(key) : ""), { timeout: 250 });
|
||||
if (role !== "radiogroup") {
|
||||
const association = await control.evaluate(element => ({
|
||||
count: element.labels.length,
|
||||
text: element.labels[0]?.querySelector(".bf-field-label")?.textContent,
|
||||
}));
|
||||
assert.deepEqual(association, { count: 1, text: label(key) }, key + " native label association");
|
||||
}
|
||||
assert.equal(await control.getAttribute("aria-invalid"), mode === "form_errors" ? "true" : null);
|
||||
if (mode === "form_errors") await expect(field.getByRole("alert")).toHaveText(error(key));
|
||||
for (const input of await field.locator("input,select,textarea").all()) {
|
||||
assert.equal(await input.isDisabled(), mode === "form_readonly", key + " disabled state");
|
||||
}
|
||||
if (role === "radiogroup") {
|
||||
for (const choice of ["Alpha", "Beta", "Gamma"]) {
|
||||
assert.equal(await field.getByRole("radio", { name: choice, exact: true }).count(), 1);
|
||||
}
|
||||
assert.equal(await field.locator("input:checked").inputValue(), values["t." + key]);
|
||||
}
|
||||
if (key === "switch") await expect(control).toBeChecked();
|
||||
}
|
||||
|
||||
async function fields(scope, mode) {
|
||||
for (const [key, role] of cases) await fieldCheck(scope, mode, key, role);
|
||||
}
|
||||
|
||||
async function browserCheck(type) {
|
||||
const executablePath = process.env[type === chromium ? "FLARE_UI_CHROMIUM" : "FLARE_UI_FIREFOX"];
|
||||
const browser = await type.launch({ headless: true, ...(executablePath ? { executablePath } : {}) });
|
||||
const start = checks;
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 1024, height: 1200 } });
|
||||
for (const mode of baseline ? ["form"] : ["form", "form_errors", "form_readonly"]) {
|
||||
const body = fixture(mode);
|
||||
assert(!body.includes("must-not-render-secret"));
|
||||
await page.setContent(`<!doctype html><html lang="en"><head><style>${css}</style></head><body>${form(body, "first")}</body></html>`);
|
||||
const scope = page.locator('form[data-form="first"]');
|
||||
for (const [key, role] of cases) {
|
||||
await check(`${type.name()} ${mode} ${key}`, () => fieldCheck(scope, mode, key, role));
|
||||
}
|
||||
if (!baseline) await check(`${type.name()} ${mode} states and submission`, async () => {
|
||||
const data = await scope.evaluate(element => Object.fromEntries(new FormData(element)));
|
||||
assert.deepEqual(data, mode === "form_readonly" ? { _csrf: "csrf-fixture" } : { _csrf: "csrf-fixture", ...values });
|
||||
assert.equal(await scope.locator("label label").count(), 0);
|
||||
assert.equal(await scope.locator("script,button").count(), 0);
|
||||
if (mode === "form") {
|
||||
const text = scope.locator('[data-path="t.text"]');
|
||||
await text.locator(".bf-field-label").click();
|
||||
await expect(text.locator("input")).toBeFocused();
|
||||
const toggle = scope.locator('[data-path="t.switch"]');
|
||||
await toggle.locator(".bf-field-label").click();
|
||||
await expect(toggle.locator("input")).not.toBeChecked();
|
||||
await expect(toggle.locator("input")).toHaveAccessibleName(label("switch"));
|
||||
await toggle.locator(".bf-field-label").click();
|
||||
await expect(toggle.locator("input")).toBeChecked();
|
||||
}
|
||||
});
|
||||
if (type === chromium && !baseline) await check(`chromium ${mode} native accessibility tree`, async () => {
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
const nodes = (await cdp.send("Accessibility.getFullAXTree")).nodes;
|
||||
const observed = [];
|
||||
for (const [key, role] of cases) {
|
||||
const found = nodes.filter(node => node.role?.value === role && node.name?.value === label(key));
|
||||
assert.equal(found.length, 1, key + " native AX name");
|
||||
assert.equal(found[0].description?.value, help(key) + (mode === "form_errors" ? " " + error(key) : ""));
|
||||
const invalid = found[0].properties.find(property => property.name === "invalid")?.value.value;
|
||||
if (mode === "form_errors") assert.equal(invalid, "true");
|
||||
else assert([undefined, "false"].includes(invalid), key + " native AX invalid state");
|
||||
observed.push({ path: "t." + key, role, name: found[0].name.value, description: found[0].description.value, invalid });
|
||||
}
|
||||
if (artifacts) fs.writeFileSync(path.join(artifacts, type.name() + "-" + mode + ".json"), JSON.stringify(observed, null, 2) + "\n");
|
||||
await cdp.detach();
|
||||
});
|
||||
if (artifacts && !baseline) await page.screenshot({ path: path.join(artifacts, type.name() + "-" + mode + ".png"), fullPage: true });
|
||||
}
|
||||
if (!baseline) await check(`${type.name()} repeated fields`, async () => {
|
||||
const body = fixture("form");
|
||||
await page.setContent(`<!doctype html><html><body>${form(body, "first")}${form(body, "second")}</body></html>`);
|
||||
for (const scope of await page.locator("form").all()) await fields(scope, "form");
|
||||
const ids = await page.locator("[id]").evaluateAll(elements => elements.map(element => element.id));
|
||||
assert.equal(ids.length, new Set(ids).size, "duplicate DOM ids after repeating a field");
|
||||
});
|
||||
console.log(JSON.stringify({ browser: type.name(), version: browser.version(), checks: checks - start,
|
||||
field_types: cases.length, modes: baseline ? ["baseline"] : ["normal", "error", "disabled", "repeated"] }));
|
||||
} finally { await browser.close(); }
|
||||
}
|
||||
|
||||
(async () => {
|
||||
for (const type of [chromium, firefox]) await browserCheck(type);
|
||||
if (failures.length) throw new Error(failures.length + " renderer accessibility failures\n" + failures.join("\n"));
|
||||
console.log("Renderer browser accessibility: PASS (" + checks + " checks)");
|
||||
})().catch(error => { console.error(error.message); process.exitCode = 1; });
|
||||
@@ -0,0 +1,93 @@
|
||||
"use strict";
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { chromium, firefox } = require("playwright");
|
||||
const sourceArg = process.argv.find(arg => arg.startsWith("--source-root="));
|
||||
const groupArg = process.argv.find(arg => arg.startsWith("--group="));
|
||||
const root = sourceArg ? path.resolve(sourceArg.slice(14)) : path.resolve(__dirname, "../../../..");
|
||||
const group = groupArg ? groupArg.slice(8) : "all";
|
||||
assert(["all", "theme", "form", "live"].includes(group));
|
||||
const assets = path.join(root, "crates/flare-ui/assets");
|
||||
const css = ["tokens.css", "theme.css", "warden-compat.css"].map(name => fs.readFileSync(path.join(assets, name), "utf8"));
|
||||
const artifacts = process.env.FLARE_UI_THEME_ARTIFACTS;
|
||||
if (artifacts) fs.mkdirSync(artifacts, { recursive: true });
|
||||
|
||||
(async () => {
|
||||
for (const type of [chromium, firefox]) {
|
||||
const browser = await type.launch({ headless: true });
|
||||
try {
|
||||
if (group === "all" || group === "theme") {
|
||||
for (const system of ["dark", "light"]) for (const theme of [null, "dark", "light"]) {
|
||||
const page = await browser.newPage({ colorScheme: system, viewport: { width: 600, height: 360 } });
|
||||
try {
|
||||
await page.setContent('<!doctype html><html lang="en"' + (theme ? ' data-theme="' + theme + '"' : "") +
|
||||
'><head><style>' + css.join("\n") + '\n#sentinel{color:rgb(1,2,3)}' +
|
||||
'body{background:var(--app-bg);color:var(--app-text);font:18px sans-serif;padding:24px}' +
|
||||
'</style></head><body><h1>Theme</h1><p>Network traffic</p><p id="sentinel">After theme</p></body></html>');
|
||||
const observed = await page.evaluate(() => {
|
||||
const style = getComputedStyle(document.documentElement);
|
||||
return { bg: getComputedStyle(document.body).backgroundColor,
|
||||
text: getComputedStyle(document.body).color,
|
||||
legacy: style.getPropertyValue("--bg").trim(), scheme: style.colorScheme,
|
||||
sentinel: getComputedStyle(document.querySelector("#sentinel")).color };
|
||||
});
|
||||
const light = theme === "light" || (theme === null && system === "light");
|
||||
assert.equal(observed.bg, light ? "rgb(255, 255, 255)" : "rgb(7, 13, 29)");
|
||||
assert.equal(observed.scheme, light ? "light" : "dark");
|
||||
assert.notEqual(observed.legacy, "");
|
||||
assert.notEqual(observed.text, observed.bg);
|
||||
assert.equal(observed.sentinel, "rgb(1, 2, 3)");
|
||||
if (artifacts) await page.screenshot({ path: path.join(artifacts, type.name() + "-" + system + "-" + (theme || "default") + ".png") });
|
||||
} finally { await page.close(); }
|
||||
}
|
||||
}
|
||||
const page = await browser.newPage();
|
||||
try {
|
||||
await page.setContent('<!doctype html><html><body><div id="host"></div></body></html>');
|
||||
if (group === "all" || group === "form") {
|
||||
for (const name of ["flow-doc.js", "flow-form.js"]) {
|
||||
await page.addScriptTag({ content: fs.readFileSync(path.join(root, "flow-builder/editor", name), "utf8") });
|
||||
}
|
||||
const result = await page.evaluate(() => {
|
||||
const host = document.querySelector("#host"), context = { target: "warden", version: 2 };
|
||||
const malformed = [
|
||||
{ op: "command", device: { toString: 0 }, type: "run_stop_cmd", value: "run" },
|
||||
{ op: "command", device: "rs485:1", type: { toString: 0 }, value: "run" },
|
||||
{ op: "wait", seconds: { toString: 0 } },
|
||||
{ op: "script", lang: "rhai", source: { toString: 0 } }
|
||||
];
|
||||
for (const step of malformed) FlareFlowForm.render(host, step, context, () => {});
|
||||
const step = JSON.parse('{"op":"wait","seconds":1,"__proto__":{"inherited":"value"},"constructor":"ordinary"}');
|
||||
let next;
|
||||
FlareFlowForm.render(host, step, context, value => { next = value; });
|
||||
const input = host.querySelector("input");
|
||||
input.value = "2"; input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
return { own: Object.prototype.hasOwnProperty.call(next, "__proto__"),
|
||||
normal: Object.getPrototypeOf(next) === Object.prototype,
|
||||
inherited: Object.prototype.hasOwnProperty.call(next, "inherited"),
|
||||
value: next.__proto__.inherited, constructor: next.constructor, seconds: next.seconds };
|
||||
});
|
||||
assert.deepEqual(result, { own: true, normal: true, inherited: false, value: "value", constructor: "ordinary", seconds: 2 });
|
||||
}
|
||||
if (group === "all" || group === "live") {
|
||||
await page.addScriptTag({ content: fs.readFileSync(path.join(assets, "js/live.js"), "utf8") });
|
||||
const result = await page.evaluate(() => {
|
||||
const live = new FlareLive.Live("/events"), stop = FlareLive.bindStaleMarker(live, document);
|
||||
const node = document.createElement("span"); node.dataset.live = ""; document.body.appendChild(node);
|
||||
node.dispatchEvent(new Event("htmx:afterSwap", { bubbles: true }));
|
||||
const stale = node.classList.contains("bf-stale");
|
||||
live.ingest('{"k":"sample","v":1}');
|
||||
const fresh = !node.classList.contains("bf-stale");
|
||||
stop(); live._setStale(true);
|
||||
node.dispatchEvent(new Event("htmx:afterSwap", { bubbles: true }));
|
||||
const detached = !node.classList.contains("bf-stale"); live.close();
|
||||
return { stale, fresh, detached };
|
||||
});
|
||||
assert.deepEqual(result, { stale: true, fresh: true, detached: true });
|
||||
}
|
||||
console.log("PASS theme/form/live", type.name(), group);
|
||||
} finally { await page.close(); }
|
||||
} finally { await browser.close(); }
|
||||
}
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1,81 @@
|
||||
"use strict";
|
||||
const assert = require("node:assert/strict");
|
||||
const crypto = require("node:crypto");
|
||||
const fs = require("node:fs");
|
||||
const http = require("node:http");
|
||||
const path = require("node:path");
|
||||
const { chromium, firefox } = require("playwright");
|
||||
// Playwright's pinned PNG reader avoids another browser-test dependency.
|
||||
const { PNG } = require(path.join(path.dirname(require.resolve("playwright-core/package.json")), "lib/utilsBundle.js"));
|
||||
|
||||
const cssArg = process.argv.find(arg => arg.startsWith("--css="));
|
||||
const cssPath = cssArg ? path.resolve(cssArg.slice(6)) : path.resolve(__dirname, "../../assets/components.css");
|
||||
const css = fs.readFileSync(cssPath);
|
||||
const fixturePath = path.resolve(__dirname, "../golden/chart-hour.html");
|
||||
const fixture = fs.readFileSync(fixturePath, "utf8");
|
||||
const origin = "http://flare-ui.test";
|
||||
const sha256 = value => crypto.createHash("sha256").update(value).digest("hex");
|
||||
const provenance = { css: { path: cssPath, sha256: sha256(css) },
|
||||
fixture: { path: fixturePath, sha256: sha256(fixture) } };
|
||||
|
||||
const server = http.createServer((request, response) => {
|
||||
const url = new URL(request.url, origin);
|
||||
if (url.origin !== origin) { response.writeHead(404); response.end(); return; }
|
||||
if (url.pathname === "/components.css") {
|
||||
response.writeHead(200, { "content-type": "text/css" });
|
||||
// No other element uses red, so the screenshot detects caption paint.
|
||||
response.end(Buffer.concat([css, Buffer.from("\ncaption { color: #ed0000; }\n")]));
|
||||
} else if (url.pathname === "/") {
|
||||
const visible = url.searchParams.has("visible");
|
||||
const body = visible ? fixture.replace('class="bf-vh"', 'class=""') : fixture;
|
||||
response.writeHead(200, { "content-type": "text/html",
|
||||
"content-security-policy": "default-src 'none'; style-src 'self'; img-src 'self'; base-uri 'none'; object-src 'none'" });
|
||||
response.end('<!doctype html><html lang="en"><head><meta name="viewport" content="width=device-width, initial-scale=1">' +
|
||||
'<link rel="stylesheet" href="/components.css"></head><body>' + body + '</body></html>');
|
||||
} else { response.writeHead(204); response.end(); }
|
||||
});
|
||||
server.on("connect", (_, socket) => socket.end("HTTP/1.1 403 Forbidden\r\n\r\n"));
|
||||
|
||||
function redPixels(buffer) {
|
||||
const png = PNG.sync.read(buffer);
|
||||
let count = 0;
|
||||
for (let i = 0; i < png.data.length; i += 4) {
|
||||
if (png.data[i] > 180 && png.data[i + 1] < 60 && png.data[i + 2] < 60 && png.data[i + 3] > 0) count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const failures = [];
|
||||
console.log("HIDDEN_PROVENANCE", JSON.stringify(provenance));
|
||||
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
|
||||
try {
|
||||
for (const type of [chromium, firefox]) {
|
||||
const browser = await type.launch({ headless: true,
|
||||
proxy: { server: "http://127.0.0.1:" + server.address().port } });
|
||||
try {
|
||||
for (const js of [true, false]) {
|
||||
const page = await browser.newPage({ javaScriptEnabled: js, viewport: { width: 375, height: 720 } });
|
||||
try {
|
||||
await page.goto(origin + "/?visible=1");
|
||||
const control = redPixels(await page.screenshot({ fullPage: true }));
|
||||
assert(control > 20, "the visible caption must prove the pixel probe can detect its text");
|
||||
await page.goto(origin + "/");
|
||||
assert.equal(await page.getByRole("table", { name: "Network <traffic> latest values", exact: true }).count(), 1);
|
||||
assert.equal(await page.getByRole("rowheader", { name: "Receive", exact: true }).count(), 1);
|
||||
const screenshot = await page.screenshot({ fullPage: true });
|
||||
const painted = redPixels(screenshot);
|
||||
if (process.env.FLARE_UI_SCREENSHOTS) {
|
||||
fs.mkdirSync(process.env.FLARE_UI_SCREENSHOTS, { recursive: true });
|
||||
fs.writeFileSync(path.join(process.env.FLARE_UI_SCREENSHOTS, type.name() + "-" + (js ? "js" : "nojs") + ".png"), screenshot);
|
||||
}
|
||||
console.log("HIDDEN_CAPTION", JSON.stringify({ browser: type.name(), js, visiblePixels: control, hiddenPixels: painted }));
|
||||
if (painted !== 0) failures.push(type.name() + " " + (js ? "JS" : "no-JS") + ": " + painted + " caption pixels");
|
||||
} finally { await page.close(); }
|
||||
}
|
||||
} finally { await browser.close(); }
|
||||
}
|
||||
} finally { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
|
||||
assert.deepEqual(failures, [], "visually hidden captions must not paint");
|
||||
console.log("PASS hidden chart captions");
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use flare_ui::chart::{Chart, Error, Series, Tier, TierSpec};
|
||||
|
||||
fn chart() -> Chart {
|
||||
Chart {
|
||||
id: "traffic".into(),
|
||||
label: "Network <traffic>".into(),
|
||||
series: vec![
|
||||
Series {
|
||||
key: "rx".into(),
|
||||
label: "Receive".into(),
|
||||
unit: "B/s".into(),
|
||||
color: "#3776BE".into(),
|
||||
},
|
||||
Series {
|
||||
key: "constructor".into(),
|
||||
label: "Transmit".into(),
|
||||
unit: "B/s".into(),
|
||||
color: "#F26522".into(),
|
||||
},
|
||||
],
|
||||
tiers: [
|
||||
TierSpec { n: 60, step_s: 60 },
|
||||
TierSpec {
|
||||
n: 60,
|
||||
step_s: 3600,
|
||||
},
|
||||
TierSpec {
|
||||
n: 60,
|
||||
step_s: 86400,
|
||||
},
|
||||
],
|
||||
tier: Tier::Hour,
|
||||
points: BTreeMap::from([("rx".into(), vec![(1000.0, 1.0), (2000.0, 2.0)])]),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn props_preserve_series_tiers_and_points() {
|
||||
let props = chart().props().unwrap();
|
||||
assert_eq!(props["id"], "traffic");
|
||||
assert_eq!(props["series"][1]["key"], "constructor");
|
||||
assert_eq!(props["tiers"]["day"]["step_s"], 86400);
|
||||
assert_eq!(props["tier"], "hour");
|
||||
assert_eq!(props["points"]["rx"][1][1], 2.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_fixtures_match_server_rendering() {
|
||||
for tier in Tier::ALL {
|
||||
let mut c = chart();
|
||||
c.tier = tier;
|
||||
let html = c.render("/network/traffic").unwrap().into_string();
|
||||
let file = format!(
|
||||
"{}/tests/golden/chart-{}.html",
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
tier.as_str()
|
||||
);
|
||||
if std::env::var_os("UPDATE_GOLDEN").is_some() {
|
||||
std::fs::write(file, format!("{html}\n")).unwrap();
|
||||
} else {
|
||||
assert_eq!(std::fs::read_to_string(file).unwrap().trim_end(), html);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chart_asset_stays_within_d63_budget() {
|
||||
assert!(flare_ui::assets::CHART_JS.len() <= 24 * 1024);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_links_and_latest_values_work_without_javascript() {
|
||||
let html = chart().render("/network/traffic").unwrap().into_string();
|
||||
for tier in ["min", "hour", "day"] {
|
||||
assert!(
|
||||
html.contains(&format!("href=\"/network/traffic?tier={tier}\"")),
|
||||
"{html}"
|
||||
);
|
||||
}
|
||||
assert_eq!(html.matches("aria-current=\"page\"").count(), 1);
|
||||
assert!(html.contains("<table class=\"bf-vh\">"));
|
||||
assert!(html.contains("data-chart-value=\"rx\">2 B/s</td>"));
|
||||
assert!(html.contains("data-chart-value=\"constructor\">-- B/s</td>"));
|
||||
assert!(!html.contains("<script"));
|
||||
assert!(html.contains("Network <traffic>"));
|
||||
for class in ["bf-chart", "bf-chart-canvas", "bf-vh", "bf-text-label"] {
|
||||
assert!(flare_ui::tokens::class_allowed(class));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn props_and_labels_are_escaped_as_attribute_text() {
|
||||
let mut c = chart();
|
||||
c.id = "\"><script>alert(1)</script>".into();
|
||||
c.series[0].label = "<img onerror=bad>".into();
|
||||
let html = c.render("/network/traffic").unwrap().into_string();
|
||||
assert!(!html.contains("<script"));
|
||||
assert!(!html.contains("<img"));
|
||||
assert!(html.contains("<img"));
|
||||
assert!(html.contains(""id""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_contracts_are_refused() {
|
||||
let mut c = chart();
|
||||
c.id.clear();
|
||||
assert_eq!(c.validate(), Err(Error::Identity));
|
||||
let mut c = chart();
|
||||
c.series.push(c.series[0].clone());
|
||||
assert_eq!(c.validate(), Err(Error::Series));
|
||||
let mut c = chart();
|
||||
c.series[0].color = "url(evil)".into();
|
||||
assert_eq!(c.validate(), Err(Error::Series));
|
||||
let mut c = chart();
|
||||
c.tiers[0].n = 61;
|
||||
assert_eq!(c.validate(), Err(Error::Tiers));
|
||||
let mut c = chart();
|
||||
c.tiers[1].step_s = 0;
|
||||
assert_eq!(c.validate(), Err(Error::Tiers));
|
||||
for points in [
|
||||
vec![(0.0, f64::NAN)],
|
||||
vec![(f64::INFINITY, 1.0)],
|
||||
vec![(2.0, 1.0), (1.0, 1.0)],
|
||||
vec![(1.0, 1.0); 61],
|
||||
] {
|
||||
let mut c = chart();
|
||||
c.points.insert("rx".into(), points);
|
||||
assert_eq!(c.validate(), Err(Error::Points));
|
||||
}
|
||||
let mut c = chart();
|
||||
c.points.insert("unknown".into(), vec![]);
|
||||
assert_eq!(c.validate(), Err(Error::Points));
|
||||
for path in [
|
||||
"https://evil/",
|
||||
"//evil/",
|
||||
"/a\\b",
|
||||
"/a?x=1",
|
||||
"/a#b",
|
||||
"/a\nb",
|
||||
] {
|
||||
assert!(matches!(chart().render(path), Err(Error::Path)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//! Runs the Node unit tests for `assets/js/chart.js`. Skipped (with a note)
|
||||
//! when `node` is not installed.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn chart_js_unit_tests() {
|
||||
let dir = env!("CARGO_MANIFEST_DIR");
|
||||
let out = match Command::new("node")
|
||||
.args(["--test", "tests/js/chart.test.js"])
|
||||
.current_dir(dir)
|
||||
.output()
|
||||
{
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
eprintln!("skipping chart.js tests: node unavailable ({e})");
|
||||
return;
|
||||
}
|
||||
};
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"node tests failed:\n{}\n{}",
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Shared fixtures: a small effective menu set.
|
||||
#![allow(dead_code)]
|
||||
|
||||
use wschema::model::{Menu, MenuRequires, Surface};
|
||||
|
||||
pub fn node(id: &str, slug: &str, title: &str) -> Menu {
|
||||
Menu {
|
||||
id: id.into(),
|
||||
slug: slug.into(),
|
||||
title: title.into(),
|
||||
short: None,
|
||||
icon: None,
|
||||
band: None,
|
||||
order: None,
|
||||
surfaces: None,
|
||||
requires: None,
|
||||
consumes: vec![],
|
||||
page: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn section(slug: &str, title: &str, band: i64, order: i64) -> Menu {
|
||||
let mut m = node(slug, slug, title);
|
||||
m.band = Some(band);
|
||||
m.order = Some(order);
|
||||
m.icon = Some(format!("i-{slug}"));
|
||||
m
|
||||
}
|
||||
|
||||
pub fn tab(sec: &str, slug: &str, title: &str, order: i64) -> Menu {
|
||||
let mut m = node(&format!("{sec}/{slug}"), slug, title);
|
||||
m.order = Some(order);
|
||||
m.page = Some(format!("{sec}.{slug}"));
|
||||
m
|
||||
}
|
||||
|
||||
pub fn menus() -> Vec<Menu> {
|
||||
let mut v = vec![
|
||||
section("settings", "Settings", 3, 10),
|
||||
section("dashboard", "Dashboard", 0, 10),
|
||||
section("network", "Network", 1, 10),
|
||||
section("rs485", "RS485", 1, 20),
|
||||
section("starlink", "Starlink", 2, 0),
|
||||
section("bess", "BESS", 2, 0),
|
||||
];
|
||||
for (s, t) in [
|
||||
("dashboard", "overview"),
|
||||
("dashboard", "metrics"),
|
||||
("network", "overview"),
|
||||
("network", "devices"),
|
||||
("rs485", "overview"),
|
||||
("starlink", "overview"),
|
||||
("bess", "overview"),
|
||||
("settings", "system"),
|
||||
("settings", "terminal"),
|
||||
] {
|
||||
let title = format!("{}{}", t[..1].to_ascii_uppercase(), &t[1..]);
|
||||
let order = if t == "overview" { 0 } else { 10 };
|
||||
v.push(tab(s, t, &title, order));
|
||||
}
|
||||
// rs485 needs the bus capability; starlink needs its app; terminal is
|
||||
// web only.
|
||||
v[3].requires = Some(MenuRequires {
|
||||
capabilities: vec!["rs485-bus".into()],
|
||||
any: vec![],
|
||||
});
|
||||
v[4].requires = Some(MenuRequires {
|
||||
capabilities: vec![],
|
||||
any: vec!["starlink".into(), "starlink-lite".into()],
|
||||
});
|
||||
let n = v.len();
|
||||
v[n - 1].surfaces = Some(vec![Surface::Web]);
|
||||
v
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use flare_ui::display_types::display_types_json;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn committed() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../docs/display-types.json")
|
||||
}
|
||||
|
||||
fn rendered() -> String {
|
||||
let mut s = serde_json::to_string_pretty(&display_types_json()).unwrap();
|
||||
s.push('\n');
|
||||
s
|
||||
}
|
||||
|
||||
/// `UPDATE_DISPLAY_TYPES=1 cargo test -p flare-ui --test display_types`
|
||||
/// rewrites the committed file after a registry change.
|
||||
#[test]
|
||||
fn committed_file_equals_the_registry() {
|
||||
if std::env::var_os("UPDATE_DISPLAY_TYPES").is_some() {
|
||||
std::fs::write(committed(), rendered()).unwrap();
|
||||
}
|
||||
let on_disk = std::fs::read_to_string(committed()).expect("docs/display-types.json");
|
||||
assert_eq!(
|
||||
on_disk,
|
||||
rendered(),
|
||||
"run with UPDATE_DISPLAY_TYPES=1 to refresh"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_are_unique_and_every_type_binds_something() {
|
||||
let v = display_types_json();
|
||||
let types = v["types"].as_array().unwrap();
|
||||
let mut ids: Vec<&str> = types.iter().map(|t| t["id"].as_str().unwrap()).collect();
|
||||
let n = ids.len();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
assert_eq!(ids.len(), n);
|
||||
assert!(n > 20);
|
||||
assert!(types
|
||||
.iter()
|
||||
.all(|t| !t["binds"].as_array().unwrap().is_empty()));
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<ul class="bf-approvals"><li class="bf-approval"><span class="bf-text-body">Open <valve> 3</span><span class="bf-text-label">Requested by ann</span><form class="bf-action" method="post" action="/approvals/a1/approve" hx-post="/approvals/a1/approve" hx-swap="outerHTML"><input type="hidden" name="csrf" value="tok"><button type="submit" class="bf-btn bf-btn-primary bf-text-button">Approve</button></form><form class="bf-action" method="post" action="/approvals/a1/deny" hx-post="/approvals/a1/deny" hx-swap="outerHTML"><input type="hidden" name="csrf" value="tok"><p class="bf-action-confirm bf-text-body">Deny this request?</p><button type="submit" class="bf-btn bf-btn-danger bf-text-button">Deny</button></form></li></ul>
|
||||
+1
@@ -0,0 +1 @@
|
||||
<p class="bf-note bf-text-body">No approvals pending.</p>
|
||||
@@ -0,0 +1 @@
|
||||
<form class="bf-action" method="post" action="/a/b" hx-post="/a/b" hx-swap="outerHTML"><input type="hidden" name="csrf" value="tok"><button type="submit" class="bf-btn bf-btn-primary bf-text-button">Run</button></form>
|
||||
@@ -0,0 +1 @@
|
||||
<form class="bf-action" method="post" action="/a/b" hx-post="/a/b" hx-swap="outerHTML"><input type="hidden" name="csrf" value="tok"><p class="bf-action-confirm bf-text-body">Sure?</p><button type="submit" class="bf-btn bf-btn-danger bf-text-button">Stop</button></form>
|
||||
@@ -0,0 +1 @@
|
||||
<figure id="traffic" class="bf-chart" data-live data-island="chart" data-chart="{"id":"traffic","points":{"rx":[[1000.0,1.0],[2000.0,2.0]]},"series":[{"color":"#3776BE","key":"rx","label":"Receive","unit":"B/s"},{"color":"#F26522","key":"constructor","label":"Transmit","unit":"B/s"}],"tier":"day","tiers":{"day":{"n":60,"step_s":86400},"hour":{"n":60,"step_s":3600},"min":{"n":60,"step_s":60}}}"><figcaption class="bf-text-label">Network <traffic></figcaption><nav aria-label="Chart tier"><a href="/network/traffic?tier=min">min</a><a href="/network/traffic?tier=hour">hour</a><a href="/network/traffic?tier=day" aria-current="page">day</a></nav><canvas class="bf-chart-canvas" role="img" aria-label="Network <traffic>"></canvas><table class="bf-vh"><caption>Network <traffic> latest values</caption><thead><tr><th scope="col">Series</th><th scope="col">Value</th></tr></thead><tbody><tr><th scope="row">Receive</th><td data-chart-value="rx">2 B/s</td></tr><tr><th scope="row">Transmit</th><td data-chart-value="constructor">-- B/s</td></tr></tbody></table></figure>
|
||||
@@ -0,0 +1 @@
|
||||
<figure id="traffic" class="bf-chart" data-live data-island="chart" data-chart="{"id":"traffic","points":{"rx":[[1000.0,1.0],[2000.0,2.0]]},"series":[{"color":"#3776BE","key":"rx","label":"Receive","unit":"B/s"},{"color":"#F26522","key":"constructor","label":"Transmit","unit":"B/s"}],"tier":"hour","tiers":{"day":{"n":60,"step_s":86400},"hour":{"n":60,"step_s":3600},"min":{"n":60,"step_s":60}}}"><figcaption class="bf-text-label">Network <traffic></figcaption><nav aria-label="Chart tier"><a href="/network/traffic?tier=min">min</a><a href="/network/traffic?tier=hour" aria-current="page">hour</a><a href="/network/traffic?tier=day">day</a></nav><canvas class="bf-chart-canvas" role="img" aria-label="Network <traffic>"></canvas><table class="bf-vh"><caption>Network <traffic> latest values</caption><thead><tr><th scope="col">Series</th><th scope="col">Value</th></tr></thead><tbody><tr><th scope="row">Receive</th><td data-chart-value="rx">2 B/s</td></tr><tr><th scope="row">Transmit</th><td data-chart-value="constructor">-- B/s</td></tr></tbody></table></figure>
|
||||
@@ -0,0 +1 @@
|
||||
<figure id="traffic" class="bf-chart" data-live data-island="chart" data-chart="{"id":"traffic","points":{"rx":[[1000.0,1.0],[2000.0,2.0]]},"series":[{"color":"#3776BE","key":"rx","label":"Receive","unit":"B/s"},{"color":"#F26522","key":"constructor","label":"Transmit","unit":"B/s"}],"tier":"min","tiers":{"day":{"n":60,"step_s":86400},"hour":{"n":60,"step_s":3600},"min":{"n":60,"step_s":60}}}"><figcaption class="bf-text-label">Network <traffic></figcaption><nav aria-label="Chart tier"><a href="/network/traffic?tier=min" aria-current="page">min</a><a href="/network/traffic?tier=hour">hour</a><a href="/network/traffic?tier=day">day</a></nav><canvas class="bf-chart-canvas" role="img" aria-label="Network <traffic>"></canvas><table class="bf-vh"><caption>Network <traffic> latest values</caption><thead><tr><th scope="col">Series</th><th scope="col">Value</th></tr></thead><tbody><tr><th scope="row">Receive</th><td data-chart-value="rx">2 B/s</td></tr><tr><th scope="row">Transmit</th><td data-chart-value="constructor">-- B/s</td></tr></tbody></table></figure>
|
||||
@@ -0,0 +1 @@
|
||||
<figure class="bf-chart" data-live data-island="chart" data-key="tank.level"><canvas class="bf-chart-canvas" role="img" aria-label="Level"></canvas><figcaption class="bf-text-label">Level</figcaption></figure>
|
||||
@@ -0,0 +1 @@
|
||||
<div class="bf-gauge" data-live data-key="tank.level"><span class="bf-kv-label bf-text-label">Level <1></span><meter class="bf-gauge-bar" min="0" max="10" value="5" aria-label="Level <1>">50%</meter><span class="bf-kv-value bf-text-body">5.00 m</span></div>
|
||||
@@ -0,0 +1 @@
|
||||
<div class="bf-hero" data-live data-key="tank.level"><span class="bf-hero-value">42.00</span><span class="bf-hero-units bf-text-body">m</span><span class="bf-kv-label bf-text-label">Level <1></span></div>
|
||||
@@ -0,0 +1 @@
|
||||
<div class="bf-kv" data-live data-key="tank.level"><span class="bf-kv-label bf-text-label">Level <1></span><span class="bf-kv-value bf-text-body">1.23 m</span></div>
|
||||
@@ -0,0 +1 @@
|
||||
<div class="bf-kv" data-live data-key="tank.level"><span class="bf-kv-label bf-text-label">Level <1></span><span class="bf-kv-value bf-text-body">-- m</span></div>
|
||||
@@ -0,0 +1 @@
|
||||
<ol class="bf-log" data-live><li class="bf-text-body-sm">one</li><li class="bf-text-body-sm">two</li></ol>
|
||||
@@ -0,0 +1 @@
|
||||
<p class="bf-note bf-text-body">Be careful</p>
|
||||
@@ -0,0 +1 @@
|
||||
<dl class="bf-plate"><dt class="bf-text-label">Model</dt><dd class="bf-text-body">X1</dd></dl>
|
||||
@@ -0,0 +1 @@
|
||||
<div class="bf-kv" data-live data-key="tank.level"><span class="bf-kv-label bf-text-label">Level <1></span><span class="bf-badge bf-badge-warn">Degraded</span></div>
|
||||
@@ -0,0 +1 @@
|
||||
<table class="bf-table"><thead><tr><th>K</th><th>V</th></tr></thead><tbody><tr><td>a</td><td><b></td></tr></tbody></table>
|
||||
@@ -0,0 +1 @@
|
||||
<div class="bf-field" data-path="t.dropdown"><label><span class="bf-field-label bf-text-label">Label</span><select class="bf-input" name="t.dropdown" aria-description="Some help"><option value="a">Alpha</option><option value="b" selected>Beta</option><option value="c">Gamma</option></select></label><p class="bf-field-help bf-text-body-sm">Some help</p></div>
|
||||
@@ -0,0 +1,2 @@
|
||||
<section class="bf-card"><h3 class="bf-card-title bf-text-h3">Settings</h3><div class="bf-field" data-path="t.text"><label><span class="bf-field-label bf-text-label">Setting t.text <&> "quoted"</span><input class="bf-input" type="text" name="t.text" value="hi <b>" aria-description="Help for t.text <&> "quoted""></label><p class="bf-field-help bf-text-body-sm">Help for t.text <&> "quoted"</p></div><div class="bf-field" data-path="t.secret"><label><span class="bf-field-label bf-text-label">Setting t.secret <&> "quoted"</span><input class="bf-input" type="password" name="t.secret" value="" placeholder="unchanged" autocomplete="new-password" aria-description="Help for t.secret <&> "quoted""></label><p class="bf-field-help bf-text-body-sm">Help for t.secret <&> "quoted"</p></div><div class="bf-field" data-path="t.dropdown"><label><span class="bf-field-label bf-text-label">Setting t.dropdown <&> "quoted"</span><select class="bf-input" name="t.dropdown" aria-description="Help for t.dropdown <&> "quoted""><option value="a">Alpha</option><option value="b" selected>Beta</option><option value="c">Gamma</option></select></label><p class="bf-field-help bf-text-body-sm">Help for t.dropdown <&> "quoted"</p></div><div class="bf-field" data-path="t.segmented"><span class="bf-field-label bf-text-label">Setting t.segmented <&> "quoted"</span><div class="bf-segmented" role="radiogroup" aria-label="Setting t.segmented <&> "quoted"" aria-description="Help for t.segmented <&> "quoted""><label class="bf-segment"><input type="radio" name="t.segmented" value="a" checked><span>Alpha</span></label><label class="bf-segment"><input type="radio" name="t.segmented" value="b"><span>Beta</span></label><label class="bf-segment"><input type="radio" name="t.segmented" value="c"><span>Gamma</span></label></div><p class="bf-field-help bf-text-body-sm">Help for t.segmented <&> "quoted"</p></div><div class="bf-field" data-path="t.swatch"><span class="bf-field-label bf-text-label">Setting t.swatch <&> "quoted"</span><div class="bf-segmented" role="radiogroup" aria-label="Setting t.swatch <&> "quoted"" aria-description="Help for t.swatch <&> "quoted""><label class="bf-segment"><input type="radio" name="t.swatch" value="a"><span>Alpha</span></label><label class="bf-segment"><input type="radio" name="t.swatch" value="b"><span>Beta</span></label><label class="bf-segment"><input type="radio" name="t.swatch" value="c" checked><span>Gamma</span></label></div><p class="bf-field-help bf-text-body-sm">Help for t.swatch <&> "quoted"</p></div><div class="bf-field" data-path="t.switch"><label><span class="bf-field-label bf-text-label">Setting t.switch <&> "quoted"</span><span class="bf-switch"><input type="checkbox" name="t.switch" value="true" checked aria-description="Help for t.switch <&> "quoted""><span aria-hidden="true">On</span></span></label><p class="bf-field-help bf-text-body-sm">Help for t.switch <&> "quoted"</p></div><div class="bf-field" data-path="t.slider"><label><span class="bf-field-label bf-text-label">Setting t.slider <&> "quoted"</span><input class="bf-input" type="range" name="t.slider" value="5" min="1" max="10" step="1" aria-description="Help for t.slider <&> "quoted""></label><p class="bf-field-help bf-text-body-sm">Help for t.slider <&> "quoted"</p></div><div class="bf-field" data-path="t.stepper"><label><span class="bf-field-label bf-text-label">Setting t.stepper <&> "quoted"</span><input class="bf-input" type="number" name="t.stepper" value="3" min="1" max="10" step="1" aria-description="Help for t.stepper <&> "quoted""></label><p class="bf-field-help bf-text-body-sm">Help for t.stepper <&> "quoted"</p></div><div class="bf-field" data-path="t.number"><label><span class="bf-field-label bf-text-label">Setting t.number <&> "quoted"</span><input class="bf-input" type="number" name="t.number" value="7" min="1" max="10" step="1" aria-description="Help for t.number <&> "quoted""></label><p class="bf-field-help bf-text-body-sm">Help for t.number <&> "quoted"</p></div><div class="bf-field" data-path="t.list"><label><span class="bf-field-label bf-text-label">Setting t.list <&> "quoted"</span><textarea class="bf-input" name="t.list" rows="4" aria-description="Help for t.list <&> "quoted"">x
|
||||
y</textarea></label><p class="bf-field-help bf-text-body-sm">Help for t.list <&> "quoted"</p></div><div class="bf-field" data-path="t.intset"><label><span class="bf-field-label bf-text-label">Setting t.intset <&> "quoted"</span><select class="bf-input" name="t.intset" aria-description="Help for t.intset <&> "quoted""><option value="1">One</option><option value="2" selected>2</option></select></label><p class="bf-field-help bf-text-body-sm">Help for t.intset <&> "quoted"</p></div></section>
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
|
||||
<section class="bf-card"><h3 class="bf-card-title bf-text-h3">Settings</h3><div class="bf-field" data-path="t.text"><label><span class="bf-field-label bf-text-label">Setting t.text <&> "quoted"</span><input class="bf-input" type="text" name="t.text" value="hi <b>" disabled aria-description="Help for t.text <&> "quoted""></label><p class="bf-field-help bf-text-body-sm">Help for t.text <&> "quoted"</p></div><div class="bf-field" data-path="t.secret"><label><span class="bf-field-label bf-text-label">Setting t.secret <&> "quoted"</span><input class="bf-input" type="password" name="t.secret" value="" placeholder="unchanged" autocomplete="new-password" disabled aria-description="Help for t.secret <&> "quoted""></label><p class="bf-field-help bf-text-body-sm">Help for t.secret <&> "quoted"</p></div><div class="bf-field" data-path="t.dropdown"><label><span class="bf-field-label bf-text-label">Setting t.dropdown <&> "quoted"</span><select class="bf-input" name="t.dropdown" disabled aria-description="Help for t.dropdown <&> "quoted""><option value="a">Alpha</option><option value="b" selected>Beta</option><option value="c">Gamma</option></select></label><p class="bf-field-help bf-text-body-sm">Help for t.dropdown <&> "quoted"</p></div><div class="bf-field" data-path="t.segmented"><span class="bf-field-label bf-text-label">Setting t.segmented <&> "quoted"</span><div class="bf-segmented" role="radiogroup" aria-label="Setting t.segmented <&> "quoted"" aria-description="Help for t.segmented <&> "quoted""><label class="bf-segment"><input type="radio" name="t.segmented" value="a" checked disabled><span>Alpha</span></label><label class="bf-segment"><input type="radio" name="t.segmented" value="b" disabled><span>Beta</span></label><label class="bf-segment"><input type="radio" name="t.segmented" value="c" disabled><span>Gamma</span></label></div><p class="bf-field-help bf-text-body-sm">Help for t.segmented <&> "quoted"</p></div><div class="bf-field" data-path="t.swatch"><span class="bf-field-label bf-text-label">Setting t.swatch <&> "quoted"</span><div class="bf-segmented" role="radiogroup" aria-label="Setting t.swatch <&> "quoted"" aria-description="Help for t.swatch <&> "quoted""><label class="bf-segment"><input type="radio" name="t.swatch" value="a" disabled><span>Alpha</span></label><label class="bf-segment"><input type="radio" name="t.swatch" value="b" disabled><span>Beta</span></label><label class="bf-segment"><input type="radio" name="t.swatch" value="c" checked disabled><span>Gamma</span></label></div><p class="bf-field-help bf-text-body-sm">Help for t.swatch <&> "quoted"</p></div><div class="bf-field" data-path="t.switch"><label><span class="bf-field-label bf-text-label">Setting t.switch <&> "quoted"</span><span class="bf-switch"><input type="checkbox" name="t.switch" value="true" checked disabled aria-description="Help for t.switch <&> "quoted""><span aria-hidden="true">On</span></span></label><p class="bf-field-help bf-text-body-sm">Help for t.switch <&> "quoted"</p></div><div class="bf-field" data-path="t.slider"><label><span class="bf-field-label bf-text-label">Setting t.slider <&> "quoted"</span><input class="bf-input" type="range" name="t.slider" value="5" min="1" max="10" step="1" disabled aria-description="Help for t.slider <&> "quoted""></label><p class="bf-field-help bf-text-body-sm">Help for t.slider <&> "quoted"</p></div><div class="bf-field" data-path="t.stepper"><label><span class="bf-field-label bf-text-label">Setting t.stepper <&> "quoted"</span><input class="bf-input" type="number" name="t.stepper" value="3" min="1" max="10" step="1" disabled aria-description="Help for t.stepper <&> "quoted""></label><p class="bf-field-help bf-text-body-sm">Help for t.stepper <&> "quoted"</p></div><div class="bf-field" data-path="t.number"><label><span class="bf-field-label bf-text-label">Setting t.number <&> "quoted"</span><input class="bf-input" type="number" name="t.number" value="7" min="1" max="10" step="1" disabled aria-description="Help for t.number <&> "quoted""></label><p class="bf-field-help bf-text-body-sm">Help for t.number <&> "quoted"</p></div><div class="bf-field" data-path="t.list"><label><span class="bf-field-label bf-text-label">Setting t.list <&> "quoted"</span><textarea class="bf-input" name="t.list" rows="4" disabled aria-description="Help for t.list <&> "quoted"">x
|
||||
y</textarea></label><p class="bf-field-help bf-text-body-sm">Help for t.list <&> "quoted"</p></div><div class="bf-field" data-path="t.intset"><label><span class="bf-field-label bf-text-label">Setting t.intset <&> "quoted"</span><select class="bf-input" name="t.intset" disabled aria-description="Help for t.intset <&> "quoted""><option value="1">One</option><option value="2" selected>2</option></select></label><p class="bf-field-help bf-text-body-sm">Help for t.intset <&> "quoted"</p></div></section>
|
||||
@@ -0,0 +1 @@
|
||||
<div class="bf-field" data-path="t.intset"><label><span class="bf-field-label bf-text-label">Label</span><select class="bf-input" name="t.intset" aria-description="Some help"><option value="1">One</option><option value="2" selected>2</option></select></label><p class="bf-field-help bf-text-body-sm">Some help</p></div>
|
||||
@@ -0,0 +1,2 @@
|
||||
<div class="bf-field" data-path="t.list"><label><span class="bf-field-label bf-text-label">Label</span><textarea class="bf-input" name="t.list" rows="4" aria-description="Some help">x
|
||||
y</textarea></label><p class="bf-field-help bf-text-body-sm">Some help</p></div>
|
||||
@@ -0,0 +1 @@
|
||||
<div class="bf-field" data-path="t.number"><label><span class="bf-field-label bf-text-label">Label</span><input class="bf-input" type="number" name="t.number" value="7" min="1" max="10" step="1" aria-description="Some help"></label><p class="bf-field-help bf-text-body-sm">Some help</p></div>
|
||||
@@ -0,0 +1 @@
|
||||
<div class="bf-field" data-path="t.secret"><label><span class="bf-field-label bf-text-label">Label</span><input class="bf-input" type="password" name="t.secret" value="" placeholder="unchanged" autocomplete="new-password" aria-description="Some help"></label><p class="bf-field-help bf-text-body-sm">Some help</p></div>
|
||||
@@ -0,0 +1 @@
|
||||
<div class="bf-field" data-path="t.segmented"><span class="bf-field-label bf-text-label">Label</span><div class="bf-segmented" role="radiogroup" aria-label="Label" aria-description="Some help"><label class="bf-segment"><input type="radio" name="t.segmented" value="a" checked><span>Alpha</span></label><label class="bf-segment"><input type="radio" name="t.segmented" value="b"><span>Beta</span></label><label class="bf-segment"><input type="radio" name="t.segmented" value="c"><span>Gamma</span></label></div><p class="bf-field-help bf-text-body-sm">Some help</p></div>
|
||||
@@ -0,0 +1 @@
|
||||
<div class="bf-field" data-path="t.slider"><label><span class="bf-field-label bf-text-label">Label</span><input class="bf-input" type="range" name="t.slider" value="5" min="1" max="10" step="1" aria-description="Some help"></label><p class="bf-field-help bf-text-body-sm">Some help</p></div>
|
||||
@@ -0,0 +1 @@
|
||||
<div class="bf-field" data-path="t.stepper"><label><span class="bf-field-label bf-text-label">Label</span><input class="bf-input" type="number" name="t.stepper" value="3" min="1" max="10" step="1" aria-description="Some help"></label><p class="bf-field-help bf-text-body-sm">Some help</p></div>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user