diff --git a/packages/widgets-rs/.gitignore b/packages/widgets-rs/.gitignore new file mode 100644 index 00000000000..b83d22266ac --- /dev/null +++ b/packages/widgets-rs/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/packages/widgets-rs/Cargo.lock b/packages/widgets-rs/Cargo.lock new file mode 100644 index 00000000000..fcd36af4a92 --- /dev/null +++ b/packages/widgets-rs/Cargo.lock @@ -0,0 +1,1372 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytecount" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" + +[[package]] +name = "calendrical_calculations" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5abbd6eeda6885048d357edc66748eea6e0268e3dd11f326fff5bd248d779c26" +dependencies = [ + "core_maths", + "displaydoc", +] + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "compact_str" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79fcda08c33bb58b97008b2cdada6622500e949e060f5913361763121abd2416" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "static_assertions", + "zmij", +] + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[package]] +name = "cow-utils" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417bef24afe1460300965a25ff4a24b8b45ad011948302ec221e8a0a81eb2c79" + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fixed_decimal" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2214fb00f669ee96bee5bb29dfb1ddabe058b2bc426817efc79afa03c9bc55ae" +dependencies = [ + "displaydoc", + "smallvec", + "writeable", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +dependencies = [ + "allocator-api2", +] + +[[package]] +name = "icu_calendar" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a68ffb801cc7acb8dcae62da7c692c47934698d2dd4f479ddee1eb442763dea1" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_calendar_data", + "icu_locale_core", + "icu_locale_fallback", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_calendar_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "514da54e79efa36b5976232d5b3d1d8ee1b47b19ab658f1b1ebe39221696c2d8" + +[[package]] +name = "icu_collator" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24cb0205c419b2036da3f9082964905d6849b3f2130dd4a517940c45899a544b" +dependencies = [ + "icu_collator_data", + "icu_collections", + "icu_locale_core", + "icu_locale_fallback", + "icu_normalizer", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "zerovec", +] + +[[package]] +name = "icu_collator_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "183f47e821a327661c1ebe152f61d5b6c2000010d228cadbbf226e0e2b8c2634" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_datetime" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c338aa7ebff734470e216a4196fa84b123a366cc786c445741b6f5647412c3c" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_calendar", + "icu_datetime_data", + "icu_decimal", + "icu_locale_core", + "icu_locale_fallback", + "icu_pattern", + "icu_plurals", + "icu_provider", + "icu_time", + "potential_utf", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_datetime_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bddb757c2df1635453c4e8cb2d4ba7ad026e904893f29699315826c0951bbd9" + +[[package]] +name = "icu_decimal" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1150ad5e272740670464934ee76facda43ef2e11f85c27b7ba76ccb33edf2d05" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_decimal_data", + "icu_locale_core", + "icu_locale_fallback", + "icu_plurals", + "icu_provider", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_decimal_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5595ab78370d48abd24a062f3db115d5108dd0b65634352036cae532aebb0df8" + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "write16", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_pattern" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc43ce0e76ee8cb0482dc6e2dbb9b76278e8038f45daabf2a2877577e2ceb18f" +dependencies = [ + "displaydoc", + "either", + "serde", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_plurals" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef046647b445acf95ce0f8083fa292467d3df649959fa9a20f3f8abfd957c5d" +dependencies = [ + "fixed_decimal", + "icu_locale_fallback", + "icu_plurals_data", + "icu_provider", + "zerovec", +] + +[[package]] +name = "icu_plurals_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43ff7df2c1a1d41588a6ddcba354d513d4a3e10eec22c06fe56d13c12a848ea" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" +dependencies = [ + "icu_collections", + "icu_locale_fallback", + "icu_provider", + "icu_segmenter_data", + "potential_utf", + "smallvec", + "utf8_iter", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" + +[[package]] +name = "icu_time" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17d45ee651f21433b1c6352311f2ad9b5253c26be0e25d9a0869cb8247b8cfde" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_calendar", + "icu_locale_core", + "icu_provider", + "icu_time_data", + "serde", + "writeable", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_time_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6d7d711f44237fa9300406ab6e521148594056862343370b5df265a0d15c088" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "279259b0ac81c89d11c290495fdcfa96ea3643b7df311c138b6fe8ca5237f0f8" +dependencies = [ + "idna_mapping", + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "idna_mapping" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11c13906586a4b339310541a274dd927aff6fcbb5b8e3af90634c4b31681c792" +dependencies = [ + "unicode-joining-type", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "nonmax" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "610a5acd306ec67f907abe5567859a3c693fb9886eb1f012ab8f2a47bef3db51" + +[[package]] +name = "num-bigint" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "oxc_allocator" +version = "0.159.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf8c5fa53291fec5f52e179974cc58cd002e45eab0defdbdfb6b36a1809c9ef" +dependencies = [ + "allocator-api2", + "hashbrown", + "oxc_data_structures", + "rustc-hash", +] + +[[package]] +name = "oxc_ast" +version = "0.159.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc5ac049e885e553878688ca583184cc2b8de02177914328f59616e59ffc224f" +dependencies = [ + "bitflags", + "oxc_allocator", + "oxc_ast_macros", + "oxc_data_structures", + "oxc_diagnostics", + "oxc_estree", + "oxc_regular_expression", + "oxc_span", + "oxc_str", + "oxc_syntax", +] + +[[package]] +name = "oxc_ast_macros" +version = "0.159.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb36e1df5e540ebd898865ed79ffd8d8f9e06310521dc0d8e5b9cc4567fc6739" +dependencies = [ + "phf", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "oxc_ast_visit" +version = "0.159.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a019293646229f79954cf7c5d022a13324c84e1b874e8ce030c8e7c0a56e5b0f" +dependencies = [ + "oxc_allocator", + "oxc_ast", + "oxc_span", + "oxc_syntax", +] + +[[package]] +name = "oxc_data_structures" +version = "0.159.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8932e4c5ad3c6973548bf2f7750b778315012ecd7086617721d23f17b43e5a55" + +[[package]] +name = "oxc_diagnostics" +version = "0.159.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901588f26a8f1e7a0a8f7ebab60bf311bc9a1d22935e740a1b545c33b020f29f" +dependencies = [ + "bytecount", + "cow-utils", + "itoa", + "memchr", + "oxc_span", + "percent-encoding", + "smallvec", + "textwrap", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "oxc_ecmascript" +version = "0.159.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4127c1685ec3e85c34bcbe9b4055b1ce34bc0e2614c4bf5cf56c52a5424c7fc5" +dependencies = [ + "itoa", + "memchr", + "num-bigint", + "num-traits", + "oxc_ast", + "oxc_data_structures", + "oxc_span", + "oxc_str", + "oxc_syntax", + "zmij_ecma", +] + +[[package]] +name = "oxc_estree" +version = "0.159.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00c806bed591dc97e36678eeaaccb6e85ecc21766eaf6f8a77e7a261a4457a2c" + +[[package]] +name = "oxc_index" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c448ca664753487e107221c172cb54ac55b500d6a8d7d126507a837f626c1f26" +dependencies = [ + "nonmax", + "serde", +] + +[[package]] +name = "oxc_parser" +version = "0.159.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fd93cb9811da8634acfd28a864889d1bf68bce2c546a52372205afabd4a63e7" +dependencies = [ + "bitflags", + "cow-utils", + "memchr", + "num-bigint", + "num-traits", + "oxc_allocator", + "oxc_ast", + "oxc_data_structures", + "oxc_diagnostics", + "oxc_ecmascript", + "oxc_span", + "oxc_str", + "oxc_syntax", + "rustc-hash", + "seq-macro", +] + +[[package]] +name = "oxc_regular_expression" +version = "0.159.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c85fe16e0f852ba1b1085f08efec7b9d611ecaba1851ca6fecb7f91b09631714" +dependencies = [ + "bitflags", + "oxc_allocator", + "oxc_ast_macros", + "oxc_data_structures", + "oxc_diagnostics", + "oxc_span", + "oxc_str", + "phf", + "rustc-hash", + "unicode-id-start", +] + +[[package]] +name = "oxc_semantic" +version = "0.159.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61b34d4fb57e1f91ed099708e09b7450960d34d3a706ee84be55f821da27021" +dependencies = [ + "itertools", + "memchr", + "oxc_allocator", + "oxc_ast", + "oxc_ast_visit", + "oxc_data_structures", + "oxc_diagnostics", + "oxc_ecmascript", + "oxc_index", + "oxc_span", + "oxc_str", + "oxc_syntax", + "rustc-hash", + "self_cell", + "smallvec", +] + +[[package]] +name = "oxc_span" +version = "0.159.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0bb9aed024358d262b9daab20b7aa7ae89b42946e549b52ff92ddfef033d0e1" +dependencies = [ + "oxc_allocator", + "oxc_ast_macros", + "oxc_estree", +] + +[[package]] +name = "oxc_str" +version = "0.159.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b51303dd938569998ad07110fff48d76da59cfe47748a39833c4652424babb4" +dependencies = [ + "compact_str", + "hashbrown", + "memchr", + "oxc_allocator", + "oxc_estree", + "oxc_span", +] + +[[package]] +name = "oxc_syntax" +version = "0.159.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f832591474dac1e451b6619d9e9d6187f08445d9d73c47b331dedc34439eb81" +dependencies = [ + "bitflags", + "cow-utils", + "nonmax", + "oxc_allocator", + "oxc_ast_macros", + "oxc_estree", + "oxc_index", + "oxc_span", + "oxc_str", + "phf", + "unicode-id-start", + "zmij_ecma", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "serde_core", + "writeable", + "zerovec", +] + +[[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 = "psychoscript" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "659e5b08541fc7be1a8e52cf7045ed1f3fc5f87fb234f90580b3c1e399d91cd4" +dependencies = [ + "fixed_decimal", + "icu_calendar", + "icu_collator", + "icu_datetime", + "icu_decimal", + "icu_locale_core", + "icu_time", + "idna_adapter", + "libc", + "num-bigint", + "num-traits", + "oxc_allocator", + "oxc_ast", + "oxc_ast_visit", + "oxc_diagnostics", + "oxc_parser", + "oxc_semantic", + "oxc_span", + "oxc_str", + "oxc_syntax", + "regress", + "rustc-hash", + "serde_json", + "tz-rs", + "unicode-normalization", + "url", + "web-time", + "writeable", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regress" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32eef8b209c3c1c15dbad02c1f30f9539f00dc7253e0cbcdaae442a50a09d7c1" +dependencies = [ + "memchr", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu-js" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f232fd0249f55adbe7f15bee58bbbd3d40708000b84e6482066d2ba599e08a9" + +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + +[[package]] +name = "seq-macro" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" + +[[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.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" +dependencies = [ + "serde", +] + +[[package]] +name = "smawk" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[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.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "textwrap" +version = "0.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ecfad6c3abc80a577f2b91c1e412ee57e7a060d430b553c1b0c940974ebcd49" +dependencies = [ + "icu_segmenter", + "smawk", + "unicode-width", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tz-rs" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fc6c929ffa10fb34f4a3c7e9a73620a83ef2e85e47f9ec3381b8289e6762f42" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-id-start" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0825d2e09dcae814a4273c1e1435979d414ede25b2ee235b1545da6682483765" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-joining-type" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8d00a78170970967fdb83f9d49b92f959ab2bb829186b113e4f4604ad98e180" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf16_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c7de35d9d8757dbc1f5125dc8b51438c68b4430546a735c3a9b91aaaaf9a18a" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "widget-web" +version = "0.1.0" +dependencies = [ + "js-sys", + "psychoscript", + "ryu-js", + "serde", + "serde_json", + "url", + "wasm-bindgen", + "web-time", +] + +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +dependencies = [ + "either", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zmij_ecma" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "458b3e7a977f14499066b6bdb63d69da30ce337d6c160f077e6c575c82a44db9" diff --git a/packages/widgets-rs/Cargo.toml b/packages/widgets-rs/Cargo.toml new file mode 100644 index 00000000000..7cd3670bb01 --- /dev/null +++ b/packages/widgets-rs/Cargo.toml @@ -0,0 +1,12 @@ +[workspace] +resolver = "3" +members = ["crates/widget-web"] + +[workspace.package] +edition = "2024" +rust-version = "1.99.1" +license = "MIT" + +[profile.release] +lto = "thin" +codegen-units = 1 diff --git a/packages/widgets-rs/crates/widget-web/Cargo.toml b/packages/widgets-rs/crates/widget-web/Cargo.toml new file mode 100644 index 00000000000..b30c4cc65c7 --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "widget-web" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish = false +description = "PsychoScript in the browser: wasm-bindgen bindings that compile a program once and run it with a JSON input, or live with __host, single-threaded" + +[lib] +name = "widget_web" +crate-type = ["cdylib", "rlib"] + +[features] +default = ["language"] +# The language: `Program` and `LiveRun`. The web package builds it into `widget_web_bg.wasm`. +language = ["dep:psychoscript", "dep:serde", "dep:url", "dep:web-time", "dep:ryu-js"] + +[dependencies] +psychoscript = { version = "0.1", optional = true } +serde = { version = "1", optional = true } +serde_json = { version = "1", features = ["preserve_order"] } +url = { version = "2.5", optional = true } +# ECMAScript `Number::toString`, for keys and numbers in native view trees (`tree`). +ryu-js = { version = "1", optional = true } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wasm-bindgen = "0.2" +js-sys = "0.3" +web-time = { version = "1.1", optional = true } + +# The tree tests read numbers like 123456789012345680000 from the fixtures: they must parse exactly; the live tests +# read views 100 levels deep. +[dev-dependencies] +serde_json = { version = "1", features = ["preserve_order", "float_roundtrip", "unbounded_depth"] } diff --git a/packages/widgets-rs/crates/widget-web/README.md b/packages/widgets-rs/crates/widget-web/README.md new file mode 100644 index 00000000000..3d15d9043e4 --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/README.md @@ -0,0 +1,105 @@ +# widget-web + +PsychoScript in the browser: wasm-bindgen bindings over the `psychoscript` crate (crates.io, 0.1) for hosts that run on +one thread (a Web Worker) and hand programs JSON. The web counterpart of PsychoScript's `psychoscript-mobile`; the +widget host that uses it is `packages/widgets-rs/web`. + +## JavaScript API (`wasm-bindgen --target web`) + +```ts +class Program { + constructor(source: string, inputName?: string) // compile once; throws PsychoScriptError + run(inputJson: string, timeoutMs?: number, maxOutputBytes?: number): string // one run, its completion value as JSON + runStep(inputJson: string, timeoutMs?: number, maxOutputBytes?: number): string // a native widget step (below) + runDraw(inputJson: string, timeoutMs?: number, maxOutputBytes?: number): string // a native draw step's commands + startLive(inputJson: string, options?: { sliceBudgetMs?: number; maxPostsPerSecond?: number; httpsHosts?: string[]; + allowLocalNetwork?: boolean; native?: boolean }): LiveRun +} +class LiveRun { + pump(maxMs: number): number // -3 ended (see exit()), -2 still computing: pump again soon, + // -1 waiting with no timer, else ms until its next sleep ends + takeBytes(): Uint8Array // the GPU batches' bytes in that outbox, which they name by [offset, length] + takeOutbox(): string // JSON array: { type: "post", message } | { type: "warning", message } + // | { type: "fetch", id, url, method, headers, body?|body64?, timeoutMs, maxResponseBytes } + // | { type: "cancel", id } + deliver(messageJson: string): void + fetchDone(id: number, metaJson: string /* { status, url, headers } */, body: Uint8Array): void + fetchFailed(id: number, kind: "Network" | "Timeout" | "TooLarge", message: string): void + pause(): void; resume(): void; stop(): void; isPaused(): boolean; nowMs(): number + exit(): string | undefined // { type: "finished", result } | { type: "failed", error } | { type: "stopped" } +} +``` + +Errors are `Error`s named `PsychoScriptError` with `type` (`syntax`, `runtime`, `timeout`, `outputTooLarge`, +`invalidInput`, `sliceBudget`, `invalidState`, `view`), `kind` (the language's diagnostic kind), 1-based +`line`/`column`, and `phase: "view"` for a `view` error. + +Widgets run as a native host of widget protocol 2 (`specs/v2/widgets.md`, Native hosts): functions cross as +markers, and this crate builds the tree clients get (`src/tree.rs`). `runStep` runs a program ending in +`return __widget_native_step(__input())` with `__widget_emit(view, failure?)` as a second host global: the result is the +run's, its functions left out as JSON leaves them, with `view` (the emitted view's tree) added. `runDraw` runs a draw step +the same way and gives the commands the program emitted, as JSON reads them (`null` for none). A live run with +`native: true` builds each posted `render`'s tree (`post` returns whether it has handlers) and maps a `draw`'s `key` to +its canvas's id; its `render` and `draw` posts go out under the post rate (a bucket of 8 refilled at +`maxPostsPerSecond`, 240; waiting posts coalesce by render and by canvas key, and go out at the run's end unless it is +stopped); GPU batches (`{ type: "frame", gpu }`, `{ type: "gpu", ops, bytes }`, widgets-gpu.md) take no token but +never overtake a waiting post, and go as they are for the client's host checks: their ops as JSON reads them, with +their non-finite numbers (which JSON writes as `null`) listed by path in `nonFinite` for the client to put back, an +`ArrayBuffer`'s bytes (read in place) in the byte outbox (`takeBytes`), other bytes `null`; a render carries its GPU canvases' ids by +key (`gpu`). Every run has typed arrays (the language's). A +`draw` without a string `key`, over 2,000 commands or with an invalid command (type `draw`), ends the run. Draws, live posts and +`runDraw` alike, are checked and normalised by the spec's draw command checks (`src/draw.rs`; `tests/draw.rs` runs the +89 shared cases of `packages/widget/test/fixtures/draw.json`). A key that isn't a string, number or boolean, or a view over 100 levels, fails with type `view` (a step +once it has run; a live run at once); a function anywhere but a node's handler props, in any host call's argument, +throws the runtime's `TypeError` `Argument to contains a function, which cannot be passed to the host.`, +located at the call (`HostError::located`, sync and async calls alike), as the host's other errors are. `tests/tree.rs` runs the 58 conformance fixtures (`packages/widget/test/fixtures/wire`). The tests read the fixtures +and preludes in place from `packages/widget`. + +A live run has `__host.post/receive/sleep/now/fetch` as in `psychoscript-mobile` (and `widgets-live.md`), but nothing +runs by itself: the host calls `pump` after a delivery, a fetch answer, a resume, or when the returned timer is due, +and again while it returns `-2`. In the browser the language yields about every millisecond of compute (see below), +so `pump(8)` returns within ~8 ms and the worker's event loop stays responsive; a stretch of compute longer than the +slice budget (50 ms) with no wait on the host stops the run with `sliceBudget`. Pausing freezes `now()` and sleeps, +and holds deliveries and fetch answers; `resume` queues `{ type: "resumed", pausedMs }` first. + +`fetch` rules are checked here (`src/fetch.rs`): https only, the declared hosts (an entry may name a port), no URL +credentials, no local names or non-public literal addresses (unless `allowLocalNetwork`, dev mode: then those too, +over `http:` as well, when an entry other than `*` declares them), the six methods, no cookie headers, 256 KB out / 2 MB in, 4 in flight and 10 a +second; the browser carries the request and the final URL after redirects is checked again. Snapshots +(`suspend`/`toBytes`) aren't offered: `Suspender::suspend` blocks on a condition variable, which a single-threaded +host can't do while it is the thread that must reach the safe point. + +The native parts are plain Rust and tested natively: `cargo test -p widget-web` (from `packages/widgets-rs`). + +## The language in the browser + +`psychoscript` 0.1 supports `wasm32-unknown-unknown` itself; this crate relies on two things it does there: + +1. **Clocks:** `std::time` panics on `wasm32-unknown-unknown`, so the language reads its clocks through `web-time` + (`performance.now()`, `Date.now()`). +2. **Yielding instead of offloading:** a run driven as a future moves compute past 1 ms to a worker thread. A + browser can't start one, so on wasm32 the run instead wakes its own waker and returns `Pending` at that stop; the + executor polls it again to continue. This is what lets a single-threaded host bound and interleave stretches of + compute. + +Also: local time zone in a browser is UTC (there is no `TZ` or `/etc/localtime`); `crypto.getRandomValues` +falls back to the run's generator (there is no `/dev/urandom`); a program nested too deeply to compile on the +caller's stack fails with "nested too deeply" (no thread with a larger stack). + +## Size + +`packages/widgets-rs/web/scripts/build-wasm.sh` (release, thin LTO, `wasm-opt -O3`): + +| Module | Raw | gzip -9 | brotli -q 11 | +| --- | --- | --- | --- | +| `widget_web_bg.wasm` (language) | 9.54 MB | 3.19 MB | 2.21 MB | +| of which code | 3.84 MB | 1.36 MB | 0.93 MB | +| of which data | 5.69 MB | 1.83 MB | 1.24 MB | + +The data is mostly ICU4X's compiled data for every CLDR locale (date/time names and patterns for +`toLocale*String`/`Intl.DateTimeFormat`, collation for `localeCompare`). Data segments are copied into each +instance's linear memory, so they also set each worker's baseline memory (~7 MB). Trimming them to a few locales +(baked data from `icu4x-datagen` through `ICU4X_DATA_DIR`, no code change) would save most of the data row (an +estimated 4–5 MB raw, ~1.5 MB gzip, ~1 MB brotli, and as much memory per worker), at the cost of formatting and +collating other locales like their nearest kept one: a difference from the native build and the reference, so it +needs a decision first. `-Oz` instead of `-O3` in wasm-opt saves under 1%. diff --git a/packages/widgets-rs/crates/widget-web/examples/step.rs b/packages/widgets-rs/crates/widget-web/examples/step.rs new file mode 100644 index 00000000000..e8bdff6bd40 --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/examples/step.rs @@ -0,0 +1,30 @@ +//! Times compiling and running widget steps natively: `cargo run --release -p widget-web --example step -- +//! ` (the program is prelude + "\n" + source). + +use std::time::Instant; + +use widget_web::Program; + +fn main() { + let args: Vec = std::env::args().collect(); + let program = std::fs::read_to_string(&args[1]).expect("a program file"); + let data = std::fs::read_to_string(&args[2]).expect("a data file"); + let t = Instant::now(); + let p = Program::new(&(program + "\nreturn __widget_step(__input())"), None).expect("compiles"); + println!("compile {:.2} ms", t.elapsed().as_secs_f64() * 1000.0); + for i in 0..5 { + let t = Instant::now(); + let out = p + .run( + &format!(r#"{{"phase":"init","data":{data}}}"#), + Some(250), + None, + ) + .expect("runs"); + println!( + "init #{i} {:.2} ms, {} bytes", + t.elapsed().as_secs_f64() * 1000.0, + out.len() + ); + } +} diff --git a/packages/widgets-rs/crates/widget-web/src/draw.rs b/packages/widgets-rs/crates/widget-web/src/draw.rs new file mode 100644 index 00000000000..128acc82c36 --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/src/draw.rs @@ -0,0 +1,385 @@ +//! A draw's commands checked (widgets.md, Canvas, "Draw command checks"), the same in every host: from the values as +//! they crossed to the normalised commands clients get, as JSON, or the exact failure (a program error in phase +//! `draw`). Shared cases: `packages/widget/test/fixtures/draw.json`. + +use std::fmt::Write as _; + +use psychoscript::HostValue; + +/// The most commands a draw may have (widgets-live.md, "Lifecycle and budgets"). +pub(crate) const MAX_COMMANDS: usize = 2000; + +const TOKENS: [&str; 9] = [ + "text", "muted", "accent", "bg", "surface", "border", "success", "warning", "error", +]; + +type Item = Option; +type Checked = Result<(), String>; + +/// A draw step's commands: read as JSON reads them first (functions and `undefined` fields left out, `undefined` and +/// function items and non-finite numbers `null`), then checked. +pub(crate) fn check_read(commands: &HostValue) -> Result { + check(&json(commands)) +} + +/// A draw's commands, as they crossed: the normalised commands as JSON, or the failure's message. +pub(crate) fn check(commands: &HostValue) -> Result { + let HostValue::Array(list) = commands else { + return Err("draw commands must be a list".into()); + }; + if list.len() > MAX_COMMANDS { + return Err(format!( + "{} draw commands is over the budget of {MAX_COMMANDS} per frame", + list.len() + )); + } + let mut out = String::with_capacity(list.len() * 24 + 2); + out.push('['); + for (i, c) in list.iter().enumerate() { + if i > 0 { + out.push(','); + } + command(c.as_ref(), &mut out).map_err(|e| format!("draw command {i}: {e}"))?; + } + out.push(']'); + Ok(out) +} + +/// `v` as JSON reads it. +fn json(v: &HostValue) -> HostValue { + match v { + HostValue::Number(n) if !n.is_finite() => HostValue::Null, + HostValue::Array(items) => HostValue::Array( + items + .iter() + .map(|i| match i { + None + | Some( + HostValue::Undefined | HostValue::FunctionMarker | HostValue::Function(_), + ) => Some(HostValue::Null), + Some(i) => Some(json(i)), + }) + .collect(), + ), + HostValue::Object(fields) => HostValue::Object( + fields + .iter() + .filter(|(_, v)| { + !matches!( + v, + HostValue::Undefined | HostValue::FunctionMarker | HostValue::Function(_) + ) + }) + .map(|(k, v)| (k.clone(), json(v))) + .collect(), + ), + other => other.clone(), + } +} + +/// An object's field: `None` when absent or `undefined`; `null` is a value. +fn field<'a>(v: &'a HostValue, name: &str) -> Option<&'a HostValue> { + v.get(name).filter(|v| !matches!(v, HostValue::Undefined)) +} + +fn number(n: f64, out: &mut String) { + out.push_str(ryu_js::Buffer::new().format_finite(n)); +} + +fn string(s: &str, out: &mut String) { + let _ = write!(out, "{}", serde_json::Value::from(s)); +} + +fn finite(v: Option<&HostValue>, what: &str) -> Result { + match v { + Some(HostValue::Number(n)) if n.is_finite() => Ok(*n), + _ => Err(format!("{what} must be a finite number")), + } +} + +fn color(v: Option<&HostValue>, out: &mut String) -> Checked { + if let Some(HostValue::String(s)) = v + && let Some(s) = s.as_str() + && match s.strip_prefix('#') { + None => TOKENS.contains(&s), + Some(hex) => { + matches!(hex.len(), 3 | 6 | 8) && hex.bytes().all(|b| b.is_ascii_hexdigit()) + } + } + { + string(s, out); + return Ok(()); + } + Err("not a color".into()) +} + +fn command(v: Option<&HostValue>, out: &mut String) -> Checked { + let Some(HostValue::Array(a)) = v else { + return Err("a command is an array".into()); + }; + let Some(Some(HostValue::String(op))) = a.first() else { + return Err("a command starts with its name".into()); + }; + let op = op.to_string_lossy(); + let op = &*op; + // The arguments a command takes after its name, and how many of them may be left off. + let (count, optional) = match op { + "save" | "restore" => (0, 0), + "rotate" | "alpha" => (1, 0), + "translate" | "scale" | "path" => (2, 0), + "circle" => (4, 0), + "rect" | "line" | "image" => (5, 0), + "rrect" => (6, 0), + "text" => (4, 1), + _ => return Err(format!("unknown draw command \"{op}\"")), + }; + if a.len() > count + 1 { + return Err(format!("\"{op}\" has more than {count} arguments")); + } + if a.len() < count + 1 - optional { + return Err(format!("\"{op}\" is missing argument {}", a.len())); + } + let at = |i: usize| a.get(i).and_then(Item::as_ref); + let n = |i: usize| finite(at(i), &format!("\"{op}\" argument {i}")); + out.push('['); + string(op, out); + match op { + "save" | "restore" => {} + "alpha" => { + out.push(','); + number(n(1)?.clamp(0.0, 1.0), out); + } + "path" => { + let Some(HostValue::Array(segments)) = at(1) else { + return Err("\"path\" takes a list of segments".into()); + }; + out.push_str(",["); + for (i, s) in segments.iter().enumerate() { + if i > 0 { + out.push(','); + } + segment(s.as_ref(), out)?; + } + out.push_str("],"); + paint(at(2), out)?; + } + "text" => { + let (x, y) = (n(1)?, n(2)?); + let Some(HostValue::String(text)) = at(3) else { + return Err("\"text\" argument 3 must be a string".into()); + }; + out.push(','); + number(x, out); + out.push(','); + number(y, out); + out.push(','); + string(&text.to_string_lossy(), out); + out.push(','); + style(at(4), out)?; + } + "image" => { + let Some(HostValue::String(src)) = at(1) else { + return Err("\"image\" takes a src".into()); + }; + out.push(','); + string(&src.to_string_lossy(), out); + for i in 2..=5 { + out.push(','); + number(n(i)?, out); + } + } + _ => { + // Numbers, then a paint for the shapes. + let shape = matches!(op, "rect" | "rrect" | "circle" | "line"); + let numbers = if shape { count - 1 } else { count }; + for i in 1..=numbers { + out.push(','); + number(n(i)?, out); + } + if shape { + out.push(','); + paint(at(count), out)?; + } + } + } + out.push(']'); + Ok(()) +} + +fn segment(v: Option<&HostValue>, out: &mut String) -> Checked { + let Some(HostValue::Array(s)) = v else { + return Err("a path segment is an array".into()); + }; + let verb = match s.first() { + Some(Some(HostValue::String(verb))) => verb.as_str(), + _ => None, + }; + let count = match verb { + Some("M" | "L") => 2, + Some("Q") => 4, + Some("C") => 6, + Some("Z") => 0, + _ => return Err("unknown path segment".into()), + }; + let verb = verb.unwrap_or_default(); + if s.len() != count + 1 { + return Err(format!( + "a \"{verb}\" path segment takes {count} coordinates" + )); + } + out.push('['); + string(verb, out); + for c in &s[1..] { + out.push(','); + number(finite(c.as_ref(), "a path coordinate")?, out); + } + out.push(']'); + Ok(()) +} + +/// Writes `"name":` before a field, with the comma when one came before. +fn key(name: &str, first: &mut bool, out: &mut String) { + if !std::mem::take(first) { + out.push(','); + } + out.push('"'); + out.push_str(name); + out.push_str("\":"); +} + +fn paint(v: Option<&HostValue>, out: &mut String) -> Checked { + let Some(m @ HostValue::Object(_)) = v else { + return Err("a paint is an object".into()); + }; + out.push('{'); + let first = &mut true; + if let Some(fill) = field(m, "fill") { + key("fill", first, out); + match fill { + HostValue::Object(_) => gradient(fill, out)?, + _ => color(Some(fill), out)?, + } + } + if let Some(stroke) = field(m, "stroke") { + key("stroke", first, out); + color(Some(stroke), out)?; + } + if let Some(width) = field(m, "width") { + let width = finite(Some(width), "a stroke's width")?.max(0.0); + key("width", first, out); + number(width, out); + } + if let Some(cap) = field(m, "cap") { + let Some(cap @ ("butt" | "round")) = cap.as_str() else { + return Err("a stroke's cap must be \"butt\" or \"round\"".into()); + }; + key("cap", first, out); + string(cap, out); + } + out.push('}'); + Ok(()) +} + +fn gradient(m: &HostValue, out: &mut String) -> Checked { + let coordinates = |name: &str, count: usize| -> Result>, String> { + let Some(list) = field(m, name) else { + return Ok(None); + }; + match list { + HostValue::Array(items) if items.len() == count => items + .iter() + .map(|i| finite(i.as_ref(), name)) + .collect::, _>>() + .map(Some), + _ => Err(format!("a {name} gradient takes {count} numbers")), + } + }; + // Both are checked when present; with both, it is linear. + let (linear, radial) = (coordinates("linear", 4)?, coordinates("radial", 3)?); + let (name, shape) = match (linear, radial) { + (Some(c), _) => ("linear", c), + (None, Some(c)) => ("radial", c), + (None, None) => return Err("a gradient needs linear or radial".into()), + }; + let Some(HostValue::Array(stops)) = field(m, "stops") else { + return Err("a gradient needs stops".into()); + }; + out.push_str("{\""); + out.push_str(name); + out.push_str("\":["); + for (i, c) in shape.iter().enumerate() { + if i > 0 { + out.push(','); + } + number(*c, out); + } + out.push_str("],\"stops\":["); + for (i, stop) in stops.iter().enumerate() { + let Some(HostValue::Array(pair)) = stop else { + return Err("a stop is [offset, color]".into()); + }; + if pair.len() != 2 { + return Err("a stop is [offset, color]".into()); + } + if i > 0 { + out.push(','); + } + let offset = finite(pair[0].as_ref(), "a stop's offset")?.clamp(0.0, 1.0); + out.push('['); + number(offset, out); + out.push(','); + color(pair[1].as_ref(), out)?; + out.push(']'); + } + out.push_str("]}"); + Ok(()) +} + +/// A text's style: left off, `undefined` or `null` is `{}`. +fn style(v: Option<&HostValue>, out: &mut String) -> Checked { + let m = match v { + None | Some(HostValue::Undefined | HostValue::Null) => { + out.push_str("{}"); + return Ok(()); + } + Some(m @ HostValue::Object(_)) => m, + Some(_) => return Err("a text style is an object".into()), + }; + out.push('{'); + let first = &mut true; + if let Some(size) = field(m, "size") { + let size = finite(Some(size), "a text size")?.clamp(1.0, 512.0); + key("size", first, out); + number(size, out); + } + if let Some(weight) = field(m, "weight") { + let Some(weight) = weight + .as_f64() + .filter(|w| [400.0, 500.0, 600.0, 700.0].contains(w)) + else { + return Err("a text weight must be 400, 500, 600 or 700".into()); + }; + key("weight", first, out); + number(weight, out); + } + if let Some(align) = field(m, "align") { + let Some(align @ ("left" | "center" | "right")) = align.as_str() else { + return Err("a text align must be \"left\", \"center\" or \"right\"".into()); + }; + key("align", first, out); + string(align, out); + } + if let Some(c) = field(m, "color") { + key("color", first, out); + color(Some(c), out)?; + } + if let Some(mono) = field(m, "mono") { + let HostValue::Bool(mono) = mono else { + return Err("a text mono must be true or false".into()); + }; + key("mono", first, out); + out.push_str(if *mono { "true" } else { "false" }); + } + out.push('}'); + Ok(()) +} diff --git a/packages/widgets-rs/crates/widget-web/src/error.rs b/packages/widgets-rs/crates/widget-web/src/error.rs new file mode 100644 index 00000000000..c8bbede1def --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/src/error.rs @@ -0,0 +1,165 @@ +use std::fmt; + +use psychoscript::{Diagnostic, DiagnosticKind}; + +/// Why a program didn't compile or a run failed: the same cases as `psychoscript-mobile`'s error. In JavaScript it is +/// an `Error` whose `name` is `"PsychoScriptError"`, with `type` (the variant, lowercase: `"syntax"`, `"runtime"`, +/// `"timeout"`, `"outputTooLarge"`, `"invalidInput"`, `"sliceBudget"`, `"invalidState"`, `"view"`, `"draw"`), `kind` (the +/// language's diagnostic kind), `line`/`column` (1-based) when known, and `phase` when it is a phase's own (`"view"`, `"draw"`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Error { + /// The source doesn't parse, or uses unsupported syntax (`ParseError`, `UnsupportedSyntax`). + Syntax { + kind: String, + reason: String, + line: Option, + column: Option, + }, + /// The run threw, or returned what isn't JSON data. + Runtime { + kind: String, + reason: String, + line: Option, + column: Option, + }, + /// The run went past `timeout_ms` of active time. + Timeout { reason: String, timeout_ms: u64 }, + /// The result is over `max_output_bytes` of JSON. + OutputTooLarge { + reason: String, + max_output_bytes: u64, + }, + /// The input isn't JSON, or the options are invalid. + InvalidInput { reason: String }, + /// A live run computed for more than `budget_ms` without waiting on its host, and was stopped. + SliceBudget { reason: String, budget_ms: u64 }, + /// A live run's method its state doesn't allow. + InvalidState { reason: String }, + /// A widget's view breaks a rule of views (widgets.md, "Keys and depth"): a program error in phase `view`. + View { reason: String }, + /// A live widget's draw post is invalid (more than 2,000 commands): a program error in phase `draw`. + Draw { reason: String }, +} + +impl Error { + pub(crate) fn from_diagnostic(d: Diagnostic, timeout_ms: Option) -> Error { + let kind = d.kind.name().to_owned(); + let reason = d.message_lossy(); + let (line, column) = d.location.map_or((None, None), |(l, c)| (Some(l), Some(c))); + match d.kind { + DiagnosticKind::TimeoutExceeded => Error::Timeout { + reason, + timeout_ms: timeout_ms.unwrap_or(0), + }, + DiagnosticKind::ParseError | DiagnosticKind::UnsupportedSyntax => Error::Syntax { + kind, + reason, + line, + column, + }, + _ => Error::Runtime { + kind, + reason, + line, + column, + }, + } + } + + pub(crate) fn invalid_input(reason: impl Into) -> Error { + Error::InvalidInput { + reason: reason.into(), + } + } + + /// The message, as the language gives it. + pub fn reason(&self) -> &str { + match self { + Error::Syntax { reason, .. } + | Error::Runtime { reason, .. } + | Error::Timeout { reason, .. } + | Error::OutputTooLarge { reason, .. } + | Error::InvalidInput { reason } + | Error::SliceBudget { reason, .. } + | Error::InvalidState { reason } + | Error::View { reason } + | Error::Draw { reason } => reason, + } + } + + /// The variant's name, as JavaScript sees it in `type`. + pub fn type_name(&self) -> &'static str { + match self { + Error::Syntax { .. } => "syntax", + Error::Runtime { .. } => "runtime", + Error::Timeout { .. } => "timeout", + Error::OutputTooLarge { .. } => "outputTooLarge", + Error::InvalidInput { .. } => "invalidInput", + Error::SliceBudget { .. } => "sliceBudget", + Error::InvalidState { .. } => "invalidState", + Error::View { .. } => "view", + Error::Draw { .. } => "draw", + } + } + + /// The language's diagnostic kind, when there is one. + pub fn kind(&self) -> Option<&str> { + match self { + Error::Syntax { kind, .. } | Error::Runtime { kind, .. } => Some(kind), + Error::Timeout { .. } => Some("TimeoutExceeded"), + _ => None, + } + } + + /// The widget phase it belongs to, when it isn't the step's or the run's: `"view"` or `"draw"`. + pub fn phase(&self) -> Option<&'static str> { + match self { + Error::View { .. } => Some("view"), + Error::Draw { .. } => Some("draw"), + _ => None, + } + } + + /// Where in the source, 1-based, when known. + pub fn location(&self) -> Option<(u32, u32)> { + match self { + Error::Syntax { + line: Some(l), + column: Some(c), + .. + } + | Error::Runtime { + line: Some(l), + column: Some(c), + .. + } => Some((*l, *c)), + _ => None, + } + } + + /// `{ type, kind?, message, line?, column?, phase? }`, as JSON. + pub fn to_json(&self) -> String { + let mut out = serde_json::Map::new(); + out.insert("type".into(), self.type_name().into()); + if let Some(kind) = self.kind() { + out.insert("kind".into(), kind.into()); + } + out.insert("message".into(), self.reason().into()); + if let Some((l, c)) = self.location() { + out.insert("line".into(), l.into()); + out.insert("column".into(), c.into()); + } + if let Some(phase) = self.phase() { + out.insert("phase".into(), phase.into()); + } + serde_json::Value::Object(out).to_string() + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.reason()) + } +} + +impl std::error::Error for Error {} diff --git a/packages/widgets-rs/crates/widget-web/src/fetch.rs b/packages/widgets-rs/crates/widget-web/src/fetch.rs new file mode 100644 index 00000000000..e08900a92c1 --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/src/fetch.rs @@ -0,0 +1,697 @@ +//! `__host.fetch(request)`'s rules, enforced here; the browser's `fetch` carries the request (the web package calls it +//! with `credentials: "omit"`, no referrer, no cache). +//! +//! `https:` only; the host on the run's allow-list (exact names, `*.` suffix wildcards, `*` for any; an entry may name a +//! port); no URL credentials; no localhost or `.local` names, no private, loopback or link-local literal addresses, +//! unless the host turned on dev mode (`Policy::local_network`): then those destinations, over `http:` too, when an +//! entry other than `*` declares them (widgets-live.md, "Local network in dev mode"); methods GET, +//! POST, PUT, PATCH, DELETE, HEAD; no cookie headers either way; request body <= 256 KB, response body <= 2 MB; 15 s +//! per request; at most 4 in flight and 10 a second per run. Rejections are errors with `kind` (`CapabilityDenied`, +//! `Network`, `Timeout`, `TooLarge`, `RateLimited`) and `message`. +//! +//! What a browser can't do: resolve names (a public name that resolves to a private address isn't caught here, though +//! Chromium's Private Network Access blocks most such requests), or show redirect hops: the browser follows them +//! (at most 20), and the final URL is checked against the same rules before the program sees anything. + +use std::collections::VecDeque; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; +use std::time::Duration; + +use psychoscript::{HostError, HostString, HostValue}; +use url::Url; + +use crate::time::Instant; + +pub const MAX_REQUEST_BYTES: usize = 256 * 1024; +pub const MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024; +pub const TIMEOUT: Duration = Duration::from_secs(15); +pub const MAX_IN_FLIGHT: usize = 4; +pub const MAX_PER_SECOND: usize = 10; +const METHODS: [&str; 6] = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"]; +/// Request headers the program can't set: cookies and credentials, and what the browser owns. +const DROPPED_HEADERS: [&str; 13] = [ + "cookie", + "cookie2", + "host", + "content-length", + "connection", + "keep-alive", + "transfer-encoding", + "te", + "trailer", + "upgrade", + "proxy-authorization", + "proxy-connection", + "origin", +]; + +/// Whether `ip` is a public unicast address a widget may reach. +pub fn public(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(v4) => public_v4(v4), + IpAddr::V6(v6) => match v6.to_ipv4_mapped() { + Some(v4) => public_v4(v4), + None => public_v6(v6), + }, + } +} + +fn public_v4(ip: Ipv4Addr) -> bool { + let [a, b, c, _] = ip.octets(); + !(ip.is_loopback() + || ip.is_private() + || ip.is_link_local() + || ip.is_unspecified() + || ip.is_broadcast() + || ip.is_multicast() + || ip.is_documentation() + || a == 0 + || (a == 100 && (64..128).contains(&b)) + || (a == 192 && b == 0 && c == 0) + || a >= 240) +} + +fn public_v6(ip: Ipv6Addr) -> bool { + let first = ip.segments()[0]; + !(ip.is_loopback() + || ip.is_unspecified() + || ip.is_multicast() + || (first & 0xfe00) == 0xfc00 + || (first & 0xffc0) == 0xfe80 + || (first & 0xffc0) == 0xfec0 + || (first == 0x2001 && ip.segments()[1] == 0x0db8) + || ip.to_ipv4().is_some_and(|v4| !public_v4(v4))) +} + +/// A rejection the program sees: an error with `kind` and `message`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Rejection { + pub kind: &'static str, + pub message: String, +} + +impl Rejection { + pub fn new(kind: &'static str, message: impl Into) -> Rejection { + Rejection { + kind, + message: message.into(), + } + } + + pub fn denied(message: impl Into) -> Rejection { + Rejection::new("CapabilityDenied", message) + } + + pub fn rate_limited(message: impl Into) -> Rejection { + Rejection::new("RateLimited", message) + } + + /// The kind a transport failure names (`Network`, `Timeout`, `TooLarge`), `Network` for any other. + pub fn transport(kind: &str, message: impl Into) -> Rejection { + let kind = match kind { + "Timeout" => "Timeout", + "TooLarge" => "TooLarge", + _ => "Network", + }; + Rejection::new(kind, message) + } + + pub fn value(self) -> HostValue { + HostValue::Error(Box::new( + HostError::named(self.kind, self.message.as_str()) + .with_field("kind", HostValue::String(self.kind.into())), + )) + } +} + +/// A request body: text as the program gave it, or bytes from `body64`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Body { + Text(String), + Bytes(Vec), +} + +impl Body { + fn len(&self) -> usize { + match self { + Body::Text(t) => t.len(), + Body::Bytes(b) => b.len(), + } + } +} + +/// A request as the program gave it, checked for shape and against the rules. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Request { + pub url: Url, + pub method: String, + pub headers: Vec<(String, String)>, + pub body: Option, +} + +impl Request { + pub fn parse(value: Option<&HostValue>, policy: &Policy) -> Result { + let bad = |m: &str| Rejection::new("Network", format!("invalid request: {m}")); + let Some(value) = value else { + return Err(bad("expected { url, method?, headers?, body? }")); + }; + let url = match value { + HostValue::String(s) => s.to_string_lossy().into_owned(), + _ => value + .get("url") + .and_then(HostValue::as_str) + .ok_or_else(|| bad("no url"))? + .to_owned(), + }; + let url = Url::parse(&url).map_err(|e| bad(&format!("{url}: {e}")))?; + check_url(&url, policy)?; + let method = match value.get("method") { + None | Some(HostValue::Undefined | HostValue::Null) => "GET".to_owned(), + Some(m) => m + .as_str() + .ok_or_else(|| bad("method isn't a string"))? + .to_ascii_uppercase(), + }; + if !METHODS.contains(&method.as_str()) { + return Err(Rejection::denied(format!( + "method {method} isn't allowed (GET, POST, PUT, PATCH, DELETE, HEAD)" + ))); + } + let mut headers = Vec::new(); + if let Some(HostValue::Object(fields)) = value.get("headers") { + for (name, v) in fields { + let name = name.to_string_lossy().to_ascii_lowercase(); + let value = match v { + HostValue::String(s) => s.to_string_lossy().into_owned(), + HostValue::Number(n) => n.to_string(), + HostValue::Bool(b) => b.to_string(), + _ => continue, + }; + if !DROPPED_HEADERS.contains(&name.as_str()) && !name.starts_with("sec-") { + headers.push((name, value)); + } + } + } + let body = match (value.get("body"), value.get("body64")) { + (Some(HostValue::String(s)), _) => Some(Body::Text(s.to_string_lossy().into_owned())), + (_, Some(HostValue::String(s))) => Some(Body::Bytes( + base64_decode(&s.to_string_lossy()).ok_or_else(|| bad("body64 isn't base64"))?, + )), + _ => None, + }; + if body.as_ref().is_some_and(|b| b.len() > MAX_REQUEST_BYTES) { + return Err(Rejection::new( + "TooLarge", + format!("the request body is over {} KB", MAX_REQUEST_BYTES / 1024), + )); + } + if body.is_some() && matches!(method.as_str(), "GET" | "HEAD") { + return Err(bad(&format!("a {method} request can't have a body"))); + } + Ok(Request { + url, + method, + headers, + body, + }) + } + + /// `{ id, url, method, headers: [[name, value]], body? | body64?, timeoutMs, maxResponseBytes }` for the + /// browser side. + pub fn to_json(&self, id: u64) -> String { + let mut out = serde_json::Map::new(); + out.insert("type".into(), "fetch".into()); + out.insert("id".into(), id.into()); + out.insert("url".into(), self.url.as_str().into()); + out.insert("method".into(), self.method.as_str().into()); + out.insert( + "headers".into(), + serde_json::Value::Array( + self.headers + .iter() + .map(|(n, v)| serde_json::json!([n, v])) + .collect(), + ), + ); + match &self.body { + Some(Body::Text(t)) => { + out.insert("body".into(), t.as_str().into()); + } + Some(Body::Bytes(b)) => { + out.insert("body64".into(), base64_encode(b).into()); + } + None => {} + } + out.insert("timeoutMs".into(), (TIMEOUT.as_millis() as u64).into()); + out.insert("maxResponseBytes".into(), MAX_RESPONSE_BYTES.into()); + serde_json::Value::Object(out).to_string() + } +} + +/// What a run's `fetch` may reach: the widget template's declared hosts and, in dev mode (`local_network`), the local +/// network among them. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Policy { + /// Exact names or addresses, `*.` suffixes, `*` for any; an entry may name a port (`localhost:4097`, + /// `[::1]:8080`), and then matches only that port. + pub hosts: Vec, + /// Dev mode: also loopback, private and link-local destinations and local names (`localhost`, `*.local`), over + /// `http:` too, when an entry other than `*` declares them. + pub local_network: bool, +} + +/// An allow-list entry: its host pattern (lowercase, no brackets or trailing dot) and port, if it names one. +fn entry(raw: &str) -> (String, Option) { + let e = raw.trim().to_ascii_lowercase(); + let (host, port) = if let Some(rest) = e.strip_prefix('[') { + match rest.split_once(']') { + Some((h, tail)) => ( + h.to_owned(), + tail.strip_prefix(':').and_then(|p| p.parse().ok()), + ), + None => (rest.to_owned(), None), + } + } else { + match e.rsplit_once(':') { + // One colon and digits after it: a port. More colons: a bare IPv6 address. + Some((h, p)) + if !h.contains(':') && !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) => + { + (h.to_owned(), p.parse().ok()) + } + _ => (e.clone(), None), + } + }; + (host.trim_end_matches('.').to_owned(), port) +} + +/// Whether `host` (at `port`) is on `allowed`: exact names, `*.` suffixes (not the bare domain), `*` unless +/// `explicit`; an entry with a port matches only that port. +pub fn host_allowed(host: &str, port: Option, allowed: &[String], explicit: bool) -> bool { + let host = host + .trim_matches(['[', ']']) + .trim_end_matches('.') + .to_ascii_lowercase(); + allowed.iter().any(|raw| { + let (pattern, want) = entry(raw); + if want.is_some() && want != port { + return false; + } + match pattern.strip_prefix("*.") { + _ if pattern == "*" => !explicit, + Some(suffix) => { + host.len() > suffix.len() + 1 + && host.ends_with(suffix) + && host[..host.len() - suffix.len()].ends_with('.') + } + None => host == pattern, + } + }) +} + +/// Whether a URL's host is on the local network: a loopback, private, link-local or other non-public address, or a +/// local name. +fn local(host: &url::Host<&str>) -> bool { + match host { + url::Host::Ipv4(ip) => !public_v4(*ip), + url::Host::Ipv6(ip) => !public(IpAddr::V6(*ip)), + url::Host::Domain(d) => { + let d = d.trim_end_matches('.').to_ascii_lowercase(); + d == "localhost" + || d.ends_with(".localhost") + || d.ends_with(".local") + || d.ends_with(".internal") + || !d.contains('.') + } + } +} + +/// A URL the run may reach: no credentials and a declared host; `https:` to a public destination, or in dev mode a +/// declared local one over `https:` or `http:`. +pub fn check_url(url: &Url, policy: &Policy) -> Result<(), Rejection> { + if !url.username().is_empty() || url.password().is_some() { + return Err(Rejection::denied("URLs with credentials aren't allowed")); + } + let Some(host) = url.host() else { + return Err(Rejection::denied("the URL has no host")); + }; + let is_local = local(&host); + let dev = policy.local_network && is_local; + if url.scheme() != "https" && !(dev && url.scheme() == "http") { + return Err(Rejection::denied(format!( + "only https: URLs, not {}:", + url.scheme() + ))); + } + let name = match &host { + url::Host::Domain(d) => (*d).to_owned(), + url::Host::Ipv4(ip) => ip.to_string(), + url::Host::Ipv6(ip) => ip.to_string(), + }; + if !host_allowed(&name, url.port_or_known_default(), &policy.hosts, is_local) { + return Err(Rejection::denied(format!( + "{name}{} isn't among the hosts this widget may reach", + url.port().map(|p| format!(":{p}")).unwrap_or_default() + ))); + } + if is_local && !dev { + return Err(Rejection::denied(match host { + url::Host::Domain(_) => format!("{name} is a local name (the local network is off)"), + _ => format!("{name} isn't a public address (the local network is off)"), + })); + } + Ok(()) +} + +/// A run's fetch budget: in flight, and started in the last second. +#[derive(Default)] +pub struct Budget { + pub in_flight: usize, + recent: VecDeque, +} + +impl Budget { + pub fn admit(&mut self) -> Result<(), Rejection> { + let now = Instant::now(); + while self + .recent + .front() + .is_some_and(|t| now.duration_since(*t) >= Duration::from_secs(1)) + { + self.recent.pop_front(); + } + if self.in_flight >= MAX_IN_FLIGHT { + return Err(Rejection::rate_limited(format!( + "at most {MAX_IN_FLIGHT} requests in flight" + ))); + } + if self.recent.len() >= MAX_PER_SECOND { + return Err(Rejection::rate_limited(format!( + "at most {MAX_PER_SECOND} requests a second" + ))); + } + self.in_flight += 1; + self.recent.push_back(now); + Ok(()) + } +} + +/// What the browser got: `{ status, url, headers }` (the final URL after redirects; headers as `[[name, value]]` or +/// an object) as JSON, and the body bytes. Checked, then made `{ status, url, headers, body | body64 }`: the body as +/// text when it's UTF-8, else base64. +pub fn response(meta_json: &str, body: Vec, policy: &Policy) -> Result { + let meta: serde_json::Value = serde_json::from_str(meta_json) + .map_err(|e| Rejection::new("Network", format!("bad response from the host: {e}")))?; + let status = meta + .get("status") + .and_then(serde_json::Value::as_f64) + .unwrap_or(0.0); + let url = meta + .get("url") + .and_then(serde_json::Value::as_str) + .unwrap_or(""); + let url = Url::parse(url) + .map_err(|e| Rejection::new("Network", format!("bad final URL {url}: {e}")))?; + check_url(&url, policy).map_err(|r| Rejection::denied(format!("redirected: {}", r.message)))?; + if body.len() > MAX_RESPONSE_BYTES { + return Err(Rejection::new( + "TooLarge", + format!("the response body is over {} MB", MAX_RESPONSE_BYTES >> 20), + )); + } + let mut headers: Vec<(HostString, HostValue)> = Vec::new(); + let pairs: Vec<(String, String)> = match meta.get("headers") { + Some(serde_json::Value::Array(items)) => items + .iter() + .filter_map(|p| { + Some(( + p.get(0)?.as_str()?.to_owned(), + p.get(1)?.as_str()?.to_owned(), + )) + }) + .collect(), + Some(serde_json::Value::Object(map)) => map + .iter() + .filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_owned()))) + .collect(), + _ => Vec::new(), + }; + for (name, value) in pairs { + let name = name.to_ascii_lowercase(); + if name == "set-cookie" || name == "set-cookie2" { + continue; + } + match headers + .iter_mut() + .find(|(k, _)| k.as_str() == Some(name.as_str())) + { + Some((_, HostValue::String(v))) => { + *v = format!("{}, {}", v.to_string_lossy(), value).into() + } + _ => headers.push((name.into(), HostValue::String(value.into()))), + } + } + let body = match String::from_utf8(body) { + Ok(text) => ("body", HostValue::String(text.into())), + Err(e) => ( + "body64", + HostValue::String(base64_encode(e.as_bytes()).into()), + ), + }; + Ok(HostValue::object([ + ("status", HostValue::Number(status)), + ("url", HostValue::String(url.as_str().into())), + ("headers", HostValue::Object(headers)), + body, + ])) +} + +const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +fn base64_encode(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let n = (u32::from(chunk[0]) << 16) + | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8) + | u32::from(*chunk.get(2).unwrap_or(&0)); + for i in 0..4 { + if i <= chunk.len() { + out.push(ALPHABET[(n >> (18 - 6 * i)) as usize & 63] as char); + } else { + out.push('='); + } + } + } + out +} + +fn base64_decode(text: &str) -> Option> { + let mut out = Vec::with_capacity(text.len() / 4 * 3); + let (mut n, mut bits) = (0u32, 0); + for c in text + .bytes() + .filter(|c| !c.is_ascii_whitespace() && *c != b'=') + { + let v = ALPHABET.iter().position(|a| *a == c)? as u32; + n = (n << 6) | v; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((n >> bits) as u8); + } + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hosts(list: &[&str]) -> Vec { + list.iter().map(|s| (*s).to_owned()).collect() + } + + fn policy(list: &[&str], local_network: bool) -> Policy { + Policy { + hosts: hosts(list), + local_network, + } + } + + #[test] + fn hosts_match_exactly_or_by_suffix() { + let allowed = hosts(&["api.github.com", "*.coingecko.com"]); + let ok = |h: &str| host_allowed(h, Some(443), &allowed, false); + assert!(ok("api.github.com")); + assert!(ok("API.GitHub.com.")); + assert!(!ok("github.com")); + assert!(ok("pro.api.coingecko.com")); + assert!(!ok("coingecko.com")); + assert!(!ok("evilcoingecko.com")); + assert!(host_allowed( + "anything.example", + Some(443), + &hosts(&["*"]), + false + )); + assert!(!host_allowed("localhost", Some(80), &hosts(&["*"]), true)); + } + + #[test] + fn entries_may_name_a_port() { + let allowed = hosts(&[ + "localhost:4097", + "[::1]:8080", + "127.0.0.1", + "api.example.com:8443", + ]); + assert!(host_allowed("localhost", Some(4097), &allowed, true)); + assert!(!host_allowed("localhost", Some(4098), &allowed, true)); + assert!(host_allowed("::1", Some(8080), &allowed, true)); + assert!(!host_allowed("::1", Some(80), &allowed, true)); + assert!(host_allowed("127.0.0.1", Some(3000), &allowed, true)); + assert!(host_allowed("api.example.com", Some(8443), &allowed, false)); + assert!(!host_allowed("api.example.com", Some(443), &allowed, false)); + assert!(host_allowed( + "fe80::1", + Some(80), + &hosts(&["fe80::1"]), + true + )); + } + + #[test] + fn urls_follow_the_rules() { + let any = policy(&["*"], false); + let check = |u: &str| check_url(&Url::parse(u).unwrap(), &any).map_err(|r| r.kind); + assert_eq!(check("https://example.com/x"), Ok(())); + assert_eq!(check("http://example.com/x"), Err("CapabilityDenied")); + assert_eq!( + check("https://user:pw@example.com/"), + Err("CapabilityDenied") + ); + assert_eq!(check("https://localhost/"), Err("CapabilityDenied")); + assert_eq!(check("https://printer.local/"), Err("CapabilityDenied")); + assert_eq!(check("https://10.0.0.1/"), Err("CapabilityDenied")); + assert_eq!(check("https://[::1]/"), Err("CapabilityDenied")); + assert_eq!(check("https://169.254.169.254/"), Err("CapabilityDenied")); + assert_eq!(check("https://1.1.1.1/"), Ok(())); + // A declared local host is still refused while the local network is off. + let declared = policy(&["localhost:4097", "10.0.0.5"], false); + let off = |u: &str| check_url(&Url::parse(u).unwrap(), &declared).map_err(|r| r.message); + assert!( + off("http://localhost:4097/") + .unwrap_err() + .contains("only https") + ); + assert!( + off("https://localhost:4097/") + .unwrap_err() + .contains("local network is off") + ); + assert!( + off("https://10.0.0.5/") + .unwrap_err() + .contains("local network is off") + ); + } + + #[test] + fn dev_mode_lets_declared_local_hosts_through() { + let dev = policy( + &[ + "localhost:4097", + "127.0.0.1", + "*.local", + "192.168.1.20:8000", + "*", + ], + true, + ); + let check = |u: &str| check_url(&Url::parse(u).unwrap(), &dev).map_err(|r| r.message); + assert_eq!(check("http://localhost:4097/api"), Ok(())); + assert_eq!(check("https://localhost:4097/api"), Ok(())); + assert!( + check("http://localhost:4098/") + .unwrap_err() + .contains("isn't among the hosts") + ); + assert_eq!(check("http://127.0.0.1:5173/"), Ok(())); + assert_eq!(check("http://printer.local/status"), Ok(())); + assert_eq!(check("http://192.168.1.20:8000/"), Ok(())); + // `*` doesn't declare the local network, and plain http stays local-only. + assert!( + check("http://10.0.0.1/") + .unwrap_err() + .contains("isn't among the hosts") + ); + assert!( + check("http://example.com/") + .unwrap_err() + .contains("only https") + ); + assert_eq!(check("https://example.com/"), Ok(())); + // Redirects end where the same rules allow. + let to_local = response( + r#"{"status":200,"url":"http://localhost:4097/x"}"#, + Vec::new(), + &policy(&["api.example.com"], true), + ); + assert_eq!(to_local.unwrap_err().kind, "CapabilityDenied"); + } + + #[test] + fn responses_are_checked_and_shaped() { + let allowed = policy(&["api.example.com"], false); + let ok = response( + r#"{"status":200,"url":"https://api.example.com/a","headers":[["Content-Type","text/plain"],["Set-Cookie","a=b"]]}"#, + b"hi".to_vec(), + &allowed, + ) + .unwrap(); + assert_eq!(ok.get("body").and_then(HostValue::as_str), Some("hi")); + let headers = ok.get("headers").unwrap(); + assert!(headers.get("set-cookie").is_none()); + assert_eq!( + headers.get("content-type").and_then(HostValue::as_str), + Some("text/plain") + ); + let binary = response( + r#"{"status":200,"url":"https://api.example.com/a"}"#, + vec![0xff, 0x00], + &allowed, + ) + .unwrap(); + assert_eq!( + binary.get("body64").and_then(HostValue::as_str), + Some("/wA=") + ); + let redirected = response( + r#"{"status":200,"url":"https://elsewhere.com/"}"#, + Vec::new(), + &allowed, + ); + assert_eq!(redirected.unwrap_err().kind, "CapabilityDenied"); + let big = response( + r#"{"status":200,"url":"https://api.example.com/"}"#, + vec![b'a'; MAX_RESPONSE_BYTES + 1], + &allowed, + ); + assert_eq!(big.unwrap_err().kind, "TooLarge"); + } + + #[test] + fn budget_limits_in_flight_and_rate() { + let mut b = Budget::default(); + for _ in 0..MAX_IN_FLIGHT { + b.admit().unwrap(); + } + assert_eq!(b.admit().unwrap_err().kind, "RateLimited"); + b.in_flight = 0; + for _ in MAX_IN_FLIGHT..MAX_PER_SECOND { + b.admit().unwrap(); + b.in_flight = 0; + } + assert_eq!(b.admit().unwrap_err().kind, "RateLimited"); + } +} diff --git a/packages/widgets-rs/crates/widget-web/src/json.rs b/packages/widgets-rs/crates/widget-web/src/json.rs new file mode 100644 index 00000000000..eec7551080f --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/src/json.rs @@ -0,0 +1,280 @@ +//! JSON text to and from [`HostValue`]s, with no `serde_json::Value` in between: a run's input, delivered messages, +//! and posted ones. + +use std::fmt; + +use psychoscript::{HostError, HostString, HostValue}; +use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor}; + +/// JSON text read as a host value: numbers as `f64`, objects keeping their keys' order. +pub(crate) struct Input(pub(crate) HostValue); + +impl Input { + pub(crate) fn parse(text: &str) -> Result { + serde_json::from_str::(text).map(|i| i.0) + } +} + +impl<'de> Deserialize<'de> for Input { + fn deserialize>(d: D) -> Result { + d.deserialize_any(Json).map(Input) + } +} + +struct Json; + +impl<'de> Visitor<'de> for Json { + type Value = HostValue; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("JSON") + } + + fn visit_unit(self) -> Result { + Ok(HostValue::Null) + } + + fn visit_bool(self, b: bool) -> Result { + Ok(HostValue::Bool(b)) + } + + fn visit_i64(self, n: i64) -> Result { + Ok(HostValue::Number(n as f64)) + } + + fn visit_u64(self, n: u64) -> Result { + Ok(HostValue::Number(n as f64)) + } + + fn visit_f64(self, n: f64) -> Result { + Ok(HostValue::Number(n)) + } + + fn visit_str(self, s: &str) -> Result { + Ok(HostValue::String(s.into())) + } + + fn visit_string(self, s: String) -> Result { + Ok(HostValue::String(s.into())) + } + + fn visit_seq>(self, mut seq: A) -> Result { + let mut items = Vec::with_capacity(seq.size_hint().unwrap_or(0)); + while let Some(Input(item)) = seq.next_element()? { + items.push(Some(item)); + } + Ok(HostValue::Array(items)) + } + + fn visit_map>(self, mut map: A) -> Result { + let mut fields: Vec<(HostString, HostValue)> = + Vec::with_capacity(map.size_hint().unwrap_or(0)); + // A repeated key stays repeated: the run sets it again, so its last value wins at its first + // place, as with `JSON.parse`. + while let Some((key, Input(value))) = map.next_entry::()? { + fields.push((key.into(), value)); + } + Ok(HostValue::Object(fields)) + } +} + +/// A host call's argument as `JSON.stringify` writes it (`undefined` is left out of objects, `null` in arrays and at +/// the top; non-finite numbers are `null`), or `None` when it holds a function, which a host call's argument may not. +pub(crate) fn write_checked(value: &HostValue) -> Option { + let mut out = String::new(); + write_into(value, &mut out, &mut false).then_some(out) +} + +/// A GPU batch's ops as [`write_checked`] writes them, and, when they hold non-finite numbers (which it writes as +/// `null`), those numbers by path from the ops, `[[path, "NaN" | "Infinity" | "-Infinity"], …]`: ops are read as JSON +/// reads them except that numbers stay as they are (widgets-gpu.md, Transport), so the client puts them back. +pub(crate) fn write_ops(value: &HostValue) -> Option<(String, Option)> { + let mut out = String::new(); + let mut seen = false; + if !write_into(value, &mut out, &mut seen) { + return None; + } + if !seen { + return Some((out, None)); + } + let mut list = String::from("["); + non_finite(value, &mut Vec::new(), &mut list); + list.push(']'); + Some((out, Some(list))) +} + +/// A step on the way to a value inside ops: a list index or an object key. +enum Step<'a> { + Index(usize), + Key(&'a HostString), +} + +/// Lists the non-finite numbers in `value`, at `path`, where [`write_into`] writes them. +fn non_finite<'a>(value: &'a HostValue, path: &mut Vec>, list: &mut String) { + match value { + HostValue::Number(n) if !n.is_finite() => { + if list.len() > 1 { + list.push(','); + } + list.push_str("[["); + for (i, step) in path.iter().enumerate() { + if i > 0 { + list.push(','); + } + match step { + Step::Index(i) => list.push_str(&i.to_string()), + Step::Key(k) => string(&k.to_string_lossy(), list), + } + } + list.push_str("],"); + list.push_str(if n.is_nan() { + r#""NaN""# + } else if *n > 0.0 { + r#""Infinity""# + } else { + r#""-Infinity""# + }); + list.push(']'); + } + HostValue::Array(items) => { + for (i, item) in items.iter().enumerate() { + if let Some(item) = item.as_ref().filter(|item| !skipped(item)) { + path.push(Step::Index(i)); + non_finite(item, path, list); + path.pop(); + } + } + } + HostValue::Object(fields) => { + for (k, v) in fields.iter().filter(|(_, v)| !skipped(v)) { + path.push(Step::Key(k)); + non_finite(v, path, list); + path.pop(); + } + } + _ => {} + } +} + +fn is_function(v: &HostValue) -> bool { + matches!(v, HostValue::Function(_) | HostValue::FunctionMarker) +} + +/// What a host call throws for a function in its argument `n` (from 1), as the runtime does without `"mark"` +/// (widgets.md, "Native hosts"): its `TypeError`, located at the call, with the function's name as the program called +/// it. +pub(crate) fn carried(n: usize, name: &str) -> HostValue { + HostError::located( + "TypeError", + format!("Argument {n} to {name} contains a function, which cannot be passed to the host."), + ) +} + +/// Fails with [`carried`] for the first of `args`, from index `from`, that is or holds a function. +pub(crate) fn unmarked(args: &[HostValue], name: &str, from: usize) -> Result<(), HostValue> { + match args.iter().skip(from).position(has_function) { + Some(i) => Err(carried(from + i + 1, name)), + None => Ok(()), + } +} + +fn has_function(v: &HostValue) -> bool { + match v { + HostValue::Function(_) | HostValue::FunctionMarker => true, + HostValue::Array(items) => items.iter().flatten().any(has_function), + HostValue::Object(fields) => fields.iter().any(|(_, v)| has_function(v)), + HostValue::Map(entries) => entries + .iter() + .any(|(k, v)| has_function(k) || has_function(v)), + HostValue::Set(items) => items.iter().any(has_function), + _ => false, + } +} + +/// Writes `value`; false when it holds a function. `seen`: set when it writes a non-finite number (as `null`). +fn write_into(value: &HostValue, out: &mut String, seen: &mut bool) -> bool { + match value { + HostValue::Null => out.push_str("null"), + HostValue::Bool(b) => out.push_str(if *b { "true" } else { "false" }), + HostValue::Number(n) => { + *seen |= !n.is_finite(); + number(*n, out) + } + HostValue::String(s) => string(&s.to_string_lossy(), out), + HostValue::Array(items) => { + out.push('['); + for (i, item) in items.iter().enumerate() { + if i > 0 { + out.push(','); + } + match item { + Some(item) if is_function(item) => return false, + Some(item) if !skipped(item) => { + if !write_into(item, out, seen) { + return false; + } + } + _ => out.push_str("null"), + } + } + out.push(']'); + } + HostValue::Object(fields) => { + out.push('{'); + let mut first = true; + for (k, v) in fields.iter() { + if is_function(v) { + return false; + } + if skipped(v) { + continue; + } + if !first { + out.push(','); + } + first = false; + string(&k.to_string_lossy(), out); + out.push(':'); + if !write_into(v, out, seen) { + return false; + } + } + out.push('}'); + } + HostValue::Function(_) | HostValue::FunctionMarker => return false, + HostValue::Map(_) | HostValue::Set(_) if has_function(value) => return false, + other => match other.to_json() { + Some(json) => out.push_str(&json.to_string()), + None => out.push_str("null"), + }, + } + true +} + +/// What `JSON.stringify` leaves out of an object, functions aside. +fn skipped(v: &HostValue) -> bool { + matches!( + v, + HostValue::Undefined + | HostValue::Durable(_) + | HostValue::Namespace(_) + | HostValue::Interrupt + ) +} + +fn number(n: f64, out: &mut String) { + use std::fmt::Write as _; + if !n.is_finite() { + out.push_str("null"); + } else if n.fract() == 0.0 && n.abs() < 9.0e15 { + let _ = write!(out, "{}", n as i64); + } else { + out.push_str( + &serde_json::Number::from_f64(n).map_or_else(|| "null".to_owned(), |n| n.to_string()), + ); + } +} + +fn string(s: &str, out: &mut String) { + out.push_str(&serde_json::to_string(s).unwrap_or_else(|_| "\"\"".to_owned())); +} diff --git a/packages/widgets-rs/crates/widget-web/src/lib.rs b/packages/widgets-rs/crates/widget-web/src/lib.rs new file mode 100644 index 00000000000..85ea6b9722e --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/src/lib.rs @@ -0,0 +1,36 @@ +//! PsychoScript in the browser: wasm-bindgen bindings over the `psychoscript` crate, the web counterpart of +//! `psychoscript-mobile`, for hosts that run on one thread (a Web Worker) and hand programs JSON. +//! +//! With feature `language` (default): [`Program`] compiles a source once; [`Program::run`] runs it with its JSON +//! input behind one sync host function (`__input()` unless named otherwise) and returns its completion value as JSON; +//! [`Program::start_live`] starts a [`LiveRun`] instead, a long-running program with `__host` (`post`, `receive`, +//! `sleep`, `now`, `fetch`) that the host drives from its event loop with [`LiveRun::pump`]. +//! +//! The native parts are plain Rust (tested natively); `wasm` holds the JavaScript bindings, built for +//! `wasm32-unknown-unknown` only. + +#[cfg(feature = "language")] +mod draw; +#[cfg(feature = "language")] +mod error; +#[cfg(feature = "language")] +pub mod fetch; +#[cfg(feature = "language")] +mod json; +#[cfg(feature = "language")] +mod live; +#[cfg(feature = "language")] +mod program; +#[cfg(feature = "language")] +mod time; +#[cfg(feature = "language")] +pub mod tree; +#[cfg(target_arch = "wasm32")] +mod wasm; + +#[cfg(feature = "language")] +pub use error::Error; +#[cfg(feature = "language")] +pub use live::{LiveExit, LiveOptions, LiveRun, Pump}; +#[cfg(feature = "language")] +pub use program::Program; diff --git a/packages/widgets-rs/crates/widget-web/src/live.rs b/packages/widgets-rs/crates/widget-web/src/live.rs new file mode 100644 index 00000000000..560d31cf6a0 --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/src/live.rs @@ -0,0 +1,1108 @@ +//! Long-running programs driven on one thread, by the host's event loop: a [`LiveRun`] has these host functions under +//! `__host`, beside the input function: +//! +//! - `__host.post(message)` (sync): queues `message`, as JSON, in the run's outbox. +//! - `await __host.receive()` (async, idempotent): the next message [`LiveRun::deliver`] queued, in order. +//! - `await __host.sleep(ms)` (async, idempotent): resolves after `ms` (clamped to >= 0) of running time. +//! - `__host.now()` (sync): milliseconds the program has been running, paused time left out. +//! - `await __host.fetch(request)` (async): an HTTPS request, checked here (see `fetch`) and queued in the outbox for +//! the host to carry out and answer with [`LiveRun::fetch_done`] or [`LiveRun::fetch_failed`]. +//! +//! Nothing runs by itself: the host calls [`LiveRun::pump`] when something happened (a delivery, a timer, a fetch +//! answer, a resume) and again as it asks, then takes [`LiveRun::take_outbox`]. In a browser the language yields every +//! millisecond or so of compute, so `pump` returns within its time slice and the event loop stays responsive; a +//! stretch of compute longer than the slice budget, with no wait on the host in between, stops the run. + +use std::collections::{HashMap, VecDeque}; +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::task::{Context, Poll, Wake, Waker}; +use std::time::Duration; + +use psychoscript::{ + Compiled, HostError, HostFunction, HostResult, HostString, HostValue, Interrupted, Limits, + ProgramOptions, RunOutcome, Runtime, Translate, TranslateFunctions, TranslatePromises, + TypedKind, +}; + +use crate::draw; +use crate::error::Error; +use crate::fetch::{self, Rejection, Request}; +use crate::json::{self, Input}; +use crate::program::uri_error; +use crate::time::Instant; +use crate::tree::{Drawn, Walk, WalkError}; + +/// A live run's budgets and capabilities. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LiveOptions { + /// Longest the program may compute without waiting on its host; past it the run stops with `SliceBudget`. + pub slice_budget_ms: u64, + /// A native run's post rate (widgets-live.md, "Post rate"): its token bucket refills at this many tokens a second. + pub max_posts_per_second: u32, + /// The `https` capability: hosts `__host.fetch` may reach (exact names, `*.` suffixes, `*` for any). `None`: + /// every fetch is rejected with `CapabilityDenied`. + pub https_hosts: Option>, + /// Dev mode (widgets-live.md, "Local network in dev mode"): `fetch` may also reach loopback, private and + /// link-local destinations and local names, over `http:` too, when the widget template declares them (not through `*`). + /// Off by default. + pub allow_local_network: bool, + /// A native run (`__widget_live(__input(), true)`, widgets.md, "Native hosts"): functions cross as markers; a posted + /// `render` carries the view as built, which goes out as the tree clients get, and `post` returns whether it has + /// handlers; a `draw` names its canvas by `key`, mapped to the canvas's id from the last render. A render whose view + /// breaks a rule of views (or that the prelude found too deep to post, `{ type: "render", node: null, failure }`) + /// ends the run at once with [`Error::View`]. A function anywhere else in a host call's argument fails the call. + /// `render` and `draw` posts go out under the post rate ([`Rate`]); a `draw` without a string `key` ends the run. + pub native: bool, +} + +impl Default for LiveOptions { + fn default() -> Self { + LiveOptions { + slice_budget_ms: 50, + max_posts_per_second: 240, + https_hosts: None, + allow_local_network: false, + native: false, + } + } +} + +/// How a live run ended. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LiveExit { + /// The program returned: its completion value as JSON. + Finished { result_json: String }, + /// It threw, or went over a budget. + Failed { error: Error }, + /// [`LiveRun::stop`] ended it. + Stopped, +} + +impl LiveExit { + /// `{ type: "finished", result }`, `{ type: "failed", error }` or `{ type: "stopped" }`, as JSON. + pub fn to_json(&self) -> String { + match self { + LiveExit::Finished { result_json } => { + format!(r#"{{"type":"finished","result":{result_json}}}"#) + } + LiveExit::Failed { error } => { + format!(r#"{{"type":"failed","error":{}}}"#, error.to_json()) + } + LiveExit::Stopped => r#"{"type":"stopped"}"#.to_owned(), + } + } +} + +/// What [`LiveRun::pump`] left the run doing. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Pump { + /// Still computing: pump again soon (after letting the event loop run). + Again, + /// Waiting on the host: pump after a delivery, a fetch answer, a resume, or this many ms for its next timer. + Wait(Option), + /// It ended: [`LiveRun::exit`] says how. + Ended, +} + +type RunFuture = Pin>>>; + +/// A program running on its host's event loop, talking to it through `__host` (see the module docs). +pub struct LiveRun { + shared: Arc>, + future: Option, + woken: Arc, + waker: Waker, + options: LiveOptions, + exit: Option, +} + +impl std::fmt::Debug for LiveRun { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("LiveRun") + } +} + +#[derive(Default)] +struct Flag(AtomicBool); + +impl Wake for Flag { + fn wake(self: Arc) { + self.0.store(true, Ordering::SeqCst); + } + + fn wake_by_ref(self: &Arc) { + self.0.store(true, Ordering::SeqCst); + } +} + +struct Sleep { + /// Running time it ends at. + deadline: f64, + waker: Option, +} + +#[derive(Default)] +struct FetchSlot { + result: Option, + waker: Option, +} + +struct Shared { + input: Arc, + native: bool, + /// Native runs: the last render's canvases by `String(key)`: id, and how it is drawn. + canvases: HashMap, + /// The bytes of the GPU batches in the outbox, which their posts name by `[offset, length]` ([`LiveRun::take_bytes`]). + bytes: Vec, + /// `None`: no https capability. + policy: Option, + /// Native runs: the post rate. + rate: Rate, + inbox: VecDeque, + receive: Option, + sleeps: HashMap, + fetches: HashMap, + budget: fetch::Budget, + next_fetch: u64, + /// Running time: `offset_ms`, plus the time since `base` unless paused. + base: Instant, + offset_ms: f64, + paused: Option, + /// The outbox: comma-separated JSON envelopes. + out: String, + /// When the current stretch of compute began, or `None` while waiting on the host. + slice: Option, + stopping: bool, + /// Why a native post ended the run. + failed: Option, +} + +/// A native run's post rate (widgets-live.md, "Post rate"): a token bucket of [`BURST`] tokens refilled at `per_second` +/// by the monotonic clock, paused or not. A `render` or `draw` post takes a token and goes out at once when nothing +/// waits; otherwise it waits, in place of the waiting post of its kind (the render, or the draw for its canvas key), +/// and the waiting posts go out in order, one per token, as tokens come; all at once when the run ends, unless the +/// client stopped it. A post carrying a GPU batch takes no token, but never overtakes a waiting post: it waits behind +/// them and goes out right after the one before it. +struct Rate { + per_second: f64, + tokens: f64, + at: Instant, + /// The waiting posts, oldest first. + waiting: Vec<(Slot, Post)>, +} + +/// What a waiting post is, for coalescing: a render, a canvas's draw, or a GPU batch in its place in the order. +#[derive(PartialEq)] +enum Slot { + Render, + Draw(String), + Batch, +} + +/// A post on its way to the outbox: its envelope, and a GPU batch's bytes, whose `[offset, length]` in the byte outbox +/// go between `head` and `tail` once it is there. +struct Post { + head: String, + bytes: Option>, + tail: &'static str, +} + +/// The post rate's burst, and the tolerance for its fractional tokens. +const BURST: f64 = 8.0; +const EPSILON: f64 = 1e-9; + +impl Rate { + fn refill(&mut self) { + let now = Instant::now(); + let elapsed = now.duration_since(self.at).as_secs_f64(); + self.tokens = (self.tokens + elapsed * self.per_second).min(BURST); + self.at = now; + } + + /// Takes a token when one is there. + fn take(&mut self) -> bool { + self.refill(); + if self.tokens < 1.0 - EPSILON { + return false; + } + self.tokens -= 1.0; + true + } + + /// Ms until the next waiting post may go out, while one waits (a batch never waits at the front). + fn due(&mut self) -> Option { + if self.waiting.is_empty() { + return None; + } + self.refill(); + Some(((1.0 - self.tokens) * 1000.0 / self.per_second).max(0.0)) + } +} + +impl Shared { + fn now_ms(&self) -> f64 { + match self.paused { + Some(_) => self.offset_ms, + None => self.offset_ms + self.base.elapsed().as_secs_f64() * 1000.0, + } + } + + fn push(&mut self, envelope: &str) { + if !self.out.is_empty() { + self.out.push(','); + } + self.out.push_str(envelope); + } + + /// Takes a posted message; a native `render` returns whether its view has handlers, a native `draw` with an unknown + /// or GPU canvas's key throws. A function where none may go throws; a render that breaks a rule of views, or a draw + /// without a string key, ends the run. All of it is checked now, whether the post goes out now or waits. + fn post(&mut self, message: &HostValue) -> HostResult { + let mut reply = HostValue::Undefined; + let mut native = None; + // Native `render` and `draw` posts: counted, with what they coalesce by; or a GPU batch's post. + let mut counted = None; + let mut batch = None; + if self.native { + match message.get("type").and_then(HostValue::as_str) { + Some("render") => { + if let Some(HostValue::String(failure)) = message.get("failure") { + return Err(self.fail(Error::View { + reason: failure.to_string_lossy().into_owned(), + })); + } + let mut node = String::new(); + let mut out = String::from(r#"{"type":"render""#); + for (name, value) in fields(message) { + if name == "type" || name == "node" || name == "failure" { + continue; + } + let value = + json::write_checked(value).ok_or_else(|| json::carried(1, POST))?; + out.push(','); + out.push_str(&serde_json::Value::from(name.to_string_lossy()).to_string()); + out.push(':'); + out.push_str(&value); + } + let walked = Walk::new().run( + message.get("node").unwrap_or(&HostValue::Undefined), + &mut node, + ); + let tree = match walked { + Ok(tree) => tree, + Err(WalkError::View(reason)) => { + return Err(self.fail(Error::View { + reason: reason.to_owned(), + })); + } + Err(WalkError::Function) => { + return Err(json::carried(1, POST)); + } + Err(WalkError::Uri) => return Err(uri_error()), + }; + reply = HostValue::Bool(tree.has_handlers); + self.canvases = tree.canvases; + out.push_str(r#","node":"#); + out.push_str(&node); + // The GPU canvases' ids by key, for the client's replay to find each context's canvas by + // (widgets-gpu.md, Transport). + let mut first = true; + for (key, (id, drawn)) in &self.canvases { + if *drawn != Drawn::Gpu { + continue; + } + out.push_str(if std::mem::take(&mut first) { + r#","gpu":{"# + } else { + "," + }); + out.push_str(&serde_json::Value::from(key.as_str()).to_string()); + out.push(':'); + out.push_str(&serde_json::Value::from(id.as_str()).to_string()); + } + if !first { + out.push('}'); + } + out.push('}'); + native = Some(out); + counted = Some(Slot::Render); + } + Some("draw") => { + let Some(key) = message.get("key").and_then(HostValue::as_str) else { + return Err(self.fail(Error::Runtime { + kind: "InvalidPost".into(), + reason: "A draw post needs a string key".into(), + line: None, + column: None, + })); + }; + let id = match self.canvases.get(key) { + None => { + return Err(error( + "Error", + &format!(r#"No canvas with key "{key}" in the rendered view"#), + )); + } + Some((_, Drawn::Wgsl)) => { + return Err(error( + "Error", + &format!( + r#"Canvas "{key}" is drawn by its wgsl; it takes no draw commands"# + ), + )); + } + Some((_, Drawn::Gpu)) => { + return Err(error( + "Error", + &format!( + r#"Canvas "{key}" is drawn by the GPU; it takes no draw commands"# + ), + )); + } + Some((id, Drawn::Commands)) => id, + }; + // The client gets the canvas's id and the normalised commands, nothing else. A function in them + // fails the call; an invalid draw is an invalid post: the run ends with a program error in phase + // `draw` (widgets.md, Canvas, "Draw command checks"). + let commands = message.get("commands").unwrap_or(&HostValue::Undefined); + json::unmarked(std::slice::from_ref(commands), POST, 0)?; + let written = match draw::check(commands) { + Ok(written) => written, + Err(reason) => return Err(self.fail(Error::Draw { reason })), + }; + let out = format!( + r#"{{"type":"draw","id":{},"commands":{written}}}"#, + serde_json::Value::from(id.as_str()) + ); + native = Some(out); + counted = Some(Slot::Draw(key.to_owned())); + } + // GPU batches (widgets-gpu.md, Transport): in a frame request, or on their own; never counted. + Some("frame") => { + if let Some(gpu) = message + .get("gpu") + .filter(|b| !matches!(b, HostValue::Undefined)) + { + let head = r#"{"type":"post","message":{"type":"frame","gpu":"#; + batch = Some(self.batch_post(gpu, head)?); + } + } + // `{ type: "gpu", ops, bytes }`: the message is the batch (only its `ops` and `bytes` are read). + Some("gpu") => { + let head = r#"{"type":"post","message":{"type":"gpu","batch":"#; + batch = Some(self.batch_post(message, head)?); + } + // An answer goes out after what waits for the rate. + Some("submit" | "dismiss") => self.release(), + _ => {} + } + } + // A GPU batch never overtakes a waiting post (it may name a canvas a waiting render adds). + if let Some(post) = batch { + if self.rate.waiting.is_empty() { + self.send(post); + } else { + self.rate.waiting.push((Slot::Batch, post)); + } + return Ok(reply); + } + let message = match native { + Some(message) => message, + None => json::write_checked(message).ok_or_else(|| json::carried(1, POST))?, + }; + let envelope = format!(r#"{{"type":"post","message":{message}}}"#); + match counted { + Some(by) => self.counted(by, envelope), + None => self.push(&envelope), + } + Ok(reply) + } + + /// Puts `post` in the outbox, its batch's bytes in the byte outbox. + fn send(&mut self, post: Post) { + let Some(bytes) = post.bytes else { + return self.push(&post.head); + }; + let start = self.bytes.len(); + if start == 0 { + self.bytes = bytes; + } else { + self.bytes.extend_from_slice(&bytes); + } + let envelope = format!( + "{}[{start},{}]{}", + post.head, + self.bytes.len() - start, + post.tail + ); + self.push(&envelope); + } + + /// A GPU batch's post, its envelope opened by `head`. + fn batch_post(&self, batch: &HostValue, head: &str) -> Result { + let mut head = head.to_owned(); + Ok(match self.batch(batch, &mut head)? { + Some(bytes) => Post { + head, + bytes: Some(bytes), + tail: "}}}", + }, + None => { + head.push_str("}}"); + Post { + head, + bytes: None, + tail: "", + } + } + }) + } + + /// Writes a GPU batch as it is, for the client's checks (widgets-gpu.md, Host checks): an object as `{"ops":..., + /// "bytes":` with its bytes given (an `ArrayBuffer`'s, read in place), their `[offset, length]` and `}` to follow + /// once it is in the outbox; else whole, `bytes` `null` when they aren't an `ArrayBuffer`. Its ops' non-finite + /// numbers, written `null`, are listed in `nonFinite` too ([`json::write_ops`]). A function in it fails the call. + fn batch(&self, batch: &HostValue, out: &mut String) -> Result>, HostValue> { + let carried = || json::carried(1, POST); + let HostValue::Object(_) = batch else { + out.push_str(&json::write_checked(batch).ok_or_else(carried)?); + return Ok(None); + }; + out.push('{'); + if let Some(ops) = batch + .get("ops") + .filter(|o| !matches!(o, HostValue::Undefined)) + { + let (ops, non_finite) = json::write_ops(ops).ok_or_else(carried)?; + out.push_str(r#""ops":"#); + out.push_str(&ops); + out.push(','); + // Numbers stay as they are: the non-finite ones, written null, by path (the client puts them back). + if let Some(list) = non_finite { + out.push_str(r#""nonFinite":"#); + out.push_str(&list); + out.push(','); + } + } + out.push_str(r#""bytes":"#); + match batch.get("bytes") { + Some(HostValue::TypedArray(t)) if t.kind() == TypedKind::ArrayBuffer => { + Ok(Some(t.to_vec())) + } + _ => { + out.push_str("null}"); + Ok(None) + } + } + } + + /// A `render` (`by` `None`) or a canvas's `draw` under the post rate: out now, or waiting in place of the waiting + /// post of its kind, else at the end of the queue. + fn counted(&mut self, by: Slot, envelope: String) { + if self.rate.waiting.is_empty() && self.rate.take() { + return self.push(&envelope); + } + let post = Post { + head: envelope, + bytes: None, + tail: "", + }; + match self.rate.waiting.iter_mut().find(|(k, _)| *k == by) { + Some(waiting) => waiting.1 = post, + None => self.rate.waiting.push((by, post)), + } + } + + /// Sends the waiting posts the bucket has tokens for, in order: a batch at the front takes none. + fn drain(&mut self) { + while let Some((slot, _)) = self.rate.waiting.first() { + if *slot != Slot::Batch && !self.rate.take() { + break; + } + let (_, post) = self.rate.waiting.remove(0); + self.send(post); + } + } + + /// Sends every waiting post now, in order. + fn release(&mut self) { + for (_, post) in std::mem::take(&mut self.rate.waiting) { + self.send(post); + } + } + + /// Ends the run with `error`: what `post` throws, which the program can't catch. + fn fail(&mut self, error: Error) -> HostValue { + self.failed = Some(error); + self.stopping = true; + HostValue::Interrupt + } + + fn begin_slice(&mut self) { + self.slice = Some(Instant::now()); + } +} + +/// An object's fields; none for anything else. +fn fields(v: &HostValue) -> &[(HostString, HostValue)] { + match v { + HostValue::Object(fields) => fields, + _ => &[], + } +} + +/// What the program called `__host.post` as, for its errors. +const POST: &str = "__host.post"; + +/// An error the program can catch, thrown from a host call, located at the call. +fn error(name: &str, message: &str) -> HostValue { + HostError::located(name, message) +} + +fn lock(m: &Mutex) -> MutexGuard<'_, Shared> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// A `fetch` the program awaits: its answer arrives in the slot; dropped unanswered (the run stopped), it is +/// cancelled. +struct Fetching { + id: u64, + shared: Arc>, + done: bool, +} + +impl Future for Fetching { + type Output = HostResult; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let mut s = lock(&self.shared); + if s.stopping { + return Poll::Ready(Err(HostValue::Interrupt)); + } + let paused = s.paused.is_some(); + let id = self.id; + let Some(slot) = s.fetches.get_mut(&id) else { + drop(s); + self.done = true; + return Poll::Ready(Err( + Rejection::new("Network", "the request was lost").value() + )); + }; + match slot.result.take() { + Some(result) if !paused => { + s.fetches.remove(&id); + s.begin_slice(); + drop(s); + self.done = true; + Poll::Ready(result) + } + held => { + slot.result = held; + slot.waker = Some(cx.waker().clone()); + Poll::Pending + } + } + } +} + +impl Drop for Fetching { + fn drop(&mut self) { + if self.done { + return; + } + let mut s = lock(&self.shared); + if s.fetches.remove(&self.id).is_some() { + s.budget.in_flight = s.budget.in_flight.saturating_sub(1); + let envelope = format!(r#"{{"type":"cancel","id":{}}}"#, self.id); + s.push(&envelope); + } + } +} + +impl LiveRun { + pub(crate) fn start( + compiled: Compiled, + input_name: String, + input_json: &str, + options: LiveOptions, + ) -> Result { + Input::parse(input_json) + .map_err(|e| Error::invalid_input(format!("the input isn't JSON: {e}")))?; + let now = Instant::now(); + let shared = Arc::new(Mutex::new(Shared { + input: input_json.into(), + native: options.native, + canvases: HashMap::new(), + bytes: Vec::new(), + policy: options.https_hosts.clone().map(|hosts| fetch::Policy { + hosts, + local_network: options.allow_local_network, + }), + rate: Rate { + per_second: f64::from(options.max_posts_per_second.max(1)), + tokens: BURST, + at: now, + waiting: Vec::new(), + }, + inbox: VecDeque::new(), + receive: None, + sleeps: HashMap::new(), + fetches: HashMap::new(), + budget: fetch::Budget::default(), + next_fetch: 1, + base: now, + offset_ms: 0.0, + paused: None, + out: String::new(), + slice: None, + stopping: false, + failed: None, + })); + let mut runtime = runtime(&shared, input_name); + if options.native { + // A native (widget) run posts views as built: handler functions cross as markers, 100 levels of view deep. + runtime = runtime.translate(MARK).limits(Limits { + max_value_depth: Some(WIDGET_DEPTH), + ..Limits::default() + }); + } + let future: RunFuture = Box::pin(async move { + let program = runtime.program(&compiled, &ProgramOptions::new()); + program.run_resumable_async().await + }); + let woken = Arc::new(Flag::default()); + let waker = Waker::from(woken.clone()); + Ok(LiveRun { + shared, + future: Some(future), + woken, + waker, + options, + exit: None, + }) + } + + /// Runs the program until it waits on the host, ends, or has computed for `max_ms` in this call (then + /// [`Pump::Again`]). Stops it with `SliceBudget` once a stretch of compute without a wait passes the budget. + pub fn pump(&mut self, max_ms: f64) -> Pump { + let Some(future) = self.future.as_mut() else { + return Pump::Ended; + }; + let started = Instant::now(); + let budget = Duration::from_millis(self.options.slice_budget_ms.max(1)); + let wakers = { + let mut s = lock(&self.shared); + if s.slice.is_none() { + s.slice = Some(started); + } + s.drain(); + due_sleeps(&mut s) + }; + for w in wakers { + w.wake(); + } + let mut cx = Context::from_waker(&self.waker); + loop { + self.woken.0.store(false, Ordering::SeqCst); + match future.as_mut().poll(&mut cx) { + Poll::Ready(result) => { + let failed = lock(&self.shared).failed.take(); + let exit = match (failed, result) { + (Some(error), _) => LiveExit::Failed { error }, + (None, Ok(RunOutcome::Done(outcome))) => match outcome.result { + Ok(data) => LiveExit::Finished { + result_json: data.to_json_string(), + }, + Err(d) => LiveExit::Failed { + error: Error::from_diagnostic(d, None), + }, + }, + (None, Ok(RunOutcome::Suspended(_)) | Err(_)) => LiveExit::Stopped, + }; + self.end(exit); + return Pump::Ended; + } + Poll::Pending if self.woken.0.load(Ordering::SeqCst) => { + let over = lock(&self.shared) + .slice + .is_some_and(|at| at.elapsed() > budget); + if over { + let budget_ms = self.options.slice_budget_ms; + self.end(LiveExit::Failed { + error: Error::SliceBudget { + reason: format!( + "the program computed for more than {budget_ms} ms without waiting" + ), + budget_ms, + }, + }); + return Pump::Ended; + } + if started.elapsed().as_secs_f64() * 1000.0 >= max_ms { + lock(&self.shared).drain(); + return Pump::Again; + } + } + Poll::Pending => { + let mut s = lock(&self.shared); + s.slice = None; + s.drain(); + return Pump::Wait(next_timer(&mut s)); + } + } + } + } + + /// Whether something woke the run since it last stopped (natively, a stretch of compute coming back from its + /// worker thread): pump it again. + pub fn woken(&self) -> bool { + self.woken.0.load(Ordering::SeqCst) + } + + /// Queues a JSON message for `__host.receive()`; held while paused. Pump afterwards. + pub fn deliver(&mut self, message_json: &str) -> Result<(), Error> { + let message = Input::parse(message_json) + .map_err(|e| Error::invalid_input(format!("the message isn't JSON: {e}")))?; + if self.future.is_none() { + return Err(ended()); + } + let waker = { + let mut s = lock(&self.shared); + s.inbox.push_back(message); + s.receive.take() + }; + if let Some(w) = waker { + w.wake(); + } + Ok(()) + } + + /// The bytes of the GPU batches in the outbox [`LiveRun::take_outbox`] just gave, which their posts name by + /// `[offset, length]`: take them right after it. + pub fn take_bytes(&mut self) -> Vec { + std::mem::take(&mut lock(&self.shared).bytes) + } + + /// The outbox since the last call, as a JSON array of `{ type: "post", message }`, `{ type: "warning", message }`, + /// `{ type: "fetch", id, url, method, headers, body? | body64?, timeoutMs, maxResponseBytes }` and + /// `{ type: "cancel", id }`. + pub fn take_outbox(&mut self) -> String { + let mut s = lock(&self.shared); + if s.out.is_empty() { + return "[]".to_owned(); + } + let out = std::mem::take(&mut s.out); + format!("[{out}]") + } + + /// Answers fetch `id` with the browser's response: `meta_json` is `{ status, url, headers }` (the final URL after + /// redirects), `body` the body's bytes. Pump afterwards. + pub fn fetch_done(&mut self, id: u64, meta_json: &str, body: Vec) { + let s = lock(&self.shared); + let policy = s.policy.clone().unwrap_or_default(); + let result = fetch::response(meta_json, body, &policy).map_err(Rejection::value); + answer(s, id, result); + } + + /// Fails fetch `id`: `kind` is `Network`, `Timeout` or `TooLarge`. Pump afterwards. + pub fn fetch_failed(&mut self, id: u64, kind: &str, message: &str) { + let s = lock(&self.shared); + answer(s, id, Err(Rejection::transport(kind, message).value())); + } + + /// Pauses the run: `sleep` timers freeze with their remaining time, `now()` stops, delivered messages and fetch + /// answers are held. A stretch of compute in progress finishes first. No-op when already paused. + pub fn pause(&mut self) -> Result<(), Error> { + if self.future.is_none() { + return Err(ended()); + } + let mut s = lock(&self.shared); + if s.paused.is_none() { + s.offset_ms += s.base.elapsed().as_secs_f64() * 1000.0; + s.paused = Some(Instant::now()); + } + Ok(()) + } + + /// Continues a paused run; the program first receives `{ type: "resumed", pausedMs }`. Pump afterwards. + pub fn resume(&mut self) -> Result<(), Error> { + if self.future.is_none() { + return Err(ended()); + } + let wakers = { + let mut s = lock(&self.shared); + let Some(at) = s.paused.take() else { + return Err(Error::InvalidState { + reason: "the run isn't paused".into(), + }); + }; + s.base = Instant::now(); + let paused_ms = (at.elapsed().as_secs_f64() * 1000.0).round(); + s.inbox.push_front(HostValue::object([ + ("type", HostValue::String("resumed".into())), + ("pausedMs", HostValue::Number(paused_ms)), + ])); + let mut wakers: Vec = s.receive.take().into_iter().collect(); + wakers.extend(s.sleeps.values_mut().filter_map(|s| s.waker.take())); + wakers.extend(s.fetches.values_mut().filter_map(|f| f.waker.take())); + wakers + }; + for w in wakers { + w.wake(); + } + Ok(()) + } + + pub fn is_paused(&self) -> bool { + lock(&self.shared).paused.is_some() + } + + /// Milliseconds the program has been running, paused time left out. + pub fn now_ms(&self) -> f64 { + lock(&self.shared).now_ms() + } + + /// Ends the run (exit `Stopped`) whatever it's doing; fetches in flight are cancelled (see the outbox). + pub fn stop(&mut self) { + if self.future.is_some() { + self.end(LiveExit::Stopped); + } + } + + /// How the run ended, once it has. + pub fn exit(&self) -> Option<&LiveExit> { + self.exit.as_ref() + } + + fn end(&mut self, exit: LiveExit) { + { + let mut s = lock(&self.shared); + s.stopping = true; + // The last view is never lost: what waits for the post rate goes out, unless the client stopped the run. + match exit { + LiveExit::Stopped => s.rate.waiting.clear(), + _ => s.release(), + } + } + // Dropping the run interrupts it and drops its host calls, which cancel their fetches. + drop(self.future.take()); + let mut s = lock(&self.shared); + s.receive = None; + s.sleeps.clear(); + s.slice = None; + drop(s); + self.exit = Some(exit); + } +} + +impl Drop for LiveRun { + fn drop(&mut self) { + self.stop(); + } +} + +fn ended() -> Error { + Error::InvalidState { + reason: "the run has ended".into(), + } +} + +fn answer(mut s: MutexGuard<'_, Shared>, id: u64, result: HostResult) { + let Some(slot) = s.fetches.get_mut(&id) else { + return; + }; + if slot.result.is_some() { + return; + } + slot.result = Some(result); + let waker = slot.waker.take(); + s.budget.in_flight = s.budget.in_flight.saturating_sub(1); + drop(s); + if let Some(w) = waker { + w.wake(); + } +} + +/// The wakers of sleeps whose time has come (none while paused). +fn due_sleeps(s: &mut Shared) -> Vec { + if s.paused.is_some() { + return Vec::new(); + } + let now = s.now_ms(); + s.sleeps + .values_mut() + .filter(|sleep| sleep.deadline <= now) + .filter_map(|sleep| sleep.waker.take()) + .collect() +} + +/// Ms until the earliest sleep ends (unless paused) or the next post waiting for the post rate may go out. +fn next_timer(s: &mut Shared) -> Option { + // Posts waiting for the post rate go out while paused too. + let posts = s.rate.due(); + if s.paused.is_some() { + return posts; + } + let now = s.now_ms(); + s.sleeps + .values() + .map(|sleep| (sleep.deadline - now).max(0.0)) + .chain(posts) + .min_by(f64::total_cmp) +} + +/// The boundary value depth of widget runs (widgets.md, "Native hosts"): the deepest value of a view of 100 levels in +/// a live `{ type: "render", node }`, 1 + 2 x 99 + 3. +pub(crate) const WIDGET_DEPTH: usize = 202; + +/// How a native run's functions cross into posts and results: as markers (widgets.md, "Native hosts"). +pub(crate) const MARK: Translate = Translate { + functions: TranslateFunctions::Mark, + promises: TranslatePromises::Error, +}; + +/// The runtime for one run: the input function and `__host`. +fn runtime(shared: &Arc>, input_name: String) -> Runtime { + let shared = shared.clone(); + Runtime::make().globals(move |_run| { + let s = shared.clone(); + let name = input_name.clone(); + let input = HostFunction::new(move |args: Vec, _call| -> HostResult { + json::unmarked(&args, &name, 0)?; + let text = lock(&s).input.clone(); + Ok(Input::parse(&text).unwrap_or_default()) + }); + let s = shared.clone(); + let post = HostFunction::new(move |args: Vec, _call| -> HostResult { + let mut s = lock(&s); + if s.stopping { + return Err(HostValue::Interrupt); + } + json::unmarked(&args, POST, 1)?; + s.post(args.first().unwrap_or(&HostValue::Undefined)) + }); + let s = shared.clone(); + let now = HostFunction::new(move |args: Vec, _call| -> HostResult { + json::unmarked(&args, "__host.now", 0)?; + Ok(HostValue::Number(lock(&s).now_ms())) + }); + let s = shared.clone(); + let receive = HostFunction::new_async(move |args: Vec, _call| { + let s = s.clone(); + let mut checked = Some(json::unmarked(&args, "__host.receive", 0)); + std::future::poll_fn(move |cx| { + if let Some(Err(e)) = checked.take() { + return Poll::Ready(Err(e)); + } + let mut s = lock(&s); + if s.stopping { + return Poll::Ready(Err(HostValue::Interrupt)); + } + let next = if s.paused.is_some() { + None + } else { + s.inbox.pop_front() + }; + match next { + Some(message) => { + s.begin_slice(); + Poll::Ready(Ok(message)) + } + None => { + s.receive = Some(cx.waker().clone()); + Poll::Pending + } + } + }) + }) + .idempotent(); + let s = shared.clone(); + let sleep = HostFunction::new_async(move |args: Vec, call| { + let s = s.clone(); + let ms = args + .first() + .and_then(HostValue::as_f64) + .filter(|n| !n.is_nan()) + .unwrap_or(0.0) + .max(0.0); + let key = call.key(); + let mut checked = Some(json::unmarked(&args, "__host.sleep", 0)); + std::future::poll_fn(move |cx| { + if let Some(Err(e)) = checked.take() { + return Poll::Ready(Err(e)); + } + let mut s = lock(&s); + if s.stopping { + return Poll::Ready(Err(HostValue::Interrupt)); + } + let paused = s.paused.is_some(); + let now = s.now_ms(); + let sleep = s.sleeps.entry(key.clone()).or_insert(Sleep { + deadline: now + ms, + waker: None, + }); + if now >= sleep.deadline && !paused { + s.sleeps.remove(&key); + s.begin_slice(); + return Poll::Ready(Ok(HostValue::Undefined)); + } + sleep.waker = Some(cx.waker().clone()); + Poll::Pending + }) + }) + .idempotent(); + let s = shared.clone(); + let fetch = HostFunction::new_async(move |args: Vec, _call| { + let started = json::unmarked(&args, "__host.fetch", 0) + .map_err(Err) + .and_then(|()| start_fetch(&s, args.first()).map_err(Ok)); + async move { + match started { + Ok(fetching) => fetching.await, + Err(Ok(rejection)) => Err(rejection.value()), + Err(Err(thrown)) => Err(thrown), + } + } + }); + let host = HostValue::object([ + ("post", HostValue::Function(post.named("post").length(1))), + ("receive", HostValue::Function(receive.named("receive"))), + ("sleep", HostValue::Function(sleep.named("sleep").length(1))), + ("now", HostValue::Function(now.named("now"))), + ("fetch", HostValue::Function(fetch.named("fetch").length(1))), + ]); + [ + ( + input_name.clone(), + HostValue::Function(input.named(input_name.clone())), + ), + ("__host".to_owned(), host), + ] + }) +} + +/// Checks a fetch against the capability, the rules and the budget, and queues it for the host. +fn start_fetch( + shared: &Arc>, + request: Option<&HostValue>, +) -> Result { + let mut s = lock(shared); + let Some(policy) = s.policy.clone() else { + return Err(Rejection::denied("this widget has no https capability")); + }; + let request = Request::parse(request, &policy)?; + s.budget.admit()?; + let id = s.next_fetch; + s.next_fetch += 1; + s.fetches.insert(id, FetchSlot::default()); + let envelope = request.to_json(id); + s.push(&envelope); + Ok(Fetching { + id, + shared: shared.clone(), + done: false, + }) +} diff --git a/packages/widgets-rs/crates/widget-web/src/program.rs b/packages/widgets-rs/crates/widget-web/src/program.rs new file mode 100644 index 00000000000..063780f0454 --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/src/program.rs @@ -0,0 +1,255 @@ +use std::sync::{Arc, Mutex, PoisonError}; + +use psychoscript::{ + Compiled, Data, HostError, HostFunction, HostResult, HostValue, Limits, Runtime, +}; + +use crate::draw; +use crate::error::Error; +use crate::json::{self, Input}; +use crate::live::{LiveOptions, LiveRun, MARK, WIDGET_DEPTH}; +use crate::tree::{Walk, WalkError}; + +/// A program compiled once, to run as often as needed: each run has its own VM. A run reads its JSON input through +/// one sync host function, `input_name` (`__input` by default), and its result is the program's completion value. +#[derive(Debug, Clone)] +pub struct Program { + compiled: Compiled, + input_name: String, +} + +impl Program { + /// Compiles `source`. Fails with `Syntax` when it doesn't parse. + pub fn new(source: &str, input_name: Option) -> Result { + let compiled = Runtime::make() + .compile(source) + .map_err(|d| Error::from_diagnostic(d, None))?; + Ok(Program { + compiled, + input_name: input_name.unwrap_or_else(|| "__input".to_owned()), + }) + } + + /// Runs the program to its end with `input_json` behind its input function, under `timeout_ms` of active time, + /// and returns its result as JSON (`undefined` as `null`), at most `max_output_bytes` of it. + pub fn run( + &self, + input_json: &str, + timeout_ms: Option, + max_output_bytes: Option, + ) -> Result { + let out = self.execute(input_json, timeout_ms, None)?.to_json_string(); + limit(out, max_output_bytes) + } + + /// [`Program::run`] for a widget step run natively (`return __widget_native_step(__input())`, widgets.md, "Native + /// hosts"): functions cross as markers, and `__widget_emit(view)` hands over the view as built, which goes out as + /// the tree clients get, built while it is written ([`crate::tree`]). The result is the run's, its functions left + /// out as JSON leaves them, with `view` added when one was emitted (`init` and `event` steps; draw steps run with + /// [`Program::run_draw`]). A view that breaks a rule of views (or that the prelude found too deep to hand over, `__widget_emit(null, + /// message)`) fails the step with [`Error::View`] once it has run; a function where none may go, or a key + /// `encodeURIComponent` can't encode, is thrown from `__widget_emit` as the runtime's own error. + pub fn run_step( + &self, + input_json: &str, + timeout_ms: Option, + max_output_bytes: Option, + ) -> Result { + let emitted = Arc::new(Mutex::new(Emitted::default())); + let result = self.execute(input_json, timeout_ms, Some(&emitted)); + let emitted = std::mem::take(&mut *emitted.lock().unwrap_or_else(PoisonError::into_inner)); + if let Some(failure) = emitted.failure { + return Err(failure); + } + let mut out = result?.to_json_string(); + if let Some(view) = emitted.view + && out.ends_with('}') + { + out.pop(); + if out.len() > 1 { + out.push(','); + } + out.push_str("\"view\":"); + out.push_str(&view); + out.push('}'); + } + limit(out, max_output_bytes) + } + + /// A widget draw step run natively (`return __widget_native_step(__input())` on a `draw` input, widgets.md, + /// "Native hosts"): functions cross as markers, and the commands the program gives `__widget_emit(commands)`, read + /// as JSON reads them and checked (widgets.md, Canvas, "Draw command checks"), come back normalised, or `null` when + /// it gave none; invalid ones fail with [`Error::Draw`]. The run's own result isn't read. + pub fn run_draw( + &self, + input_json: &str, + timeout_ms: Option, + max_output_bytes: Option, + ) -> Result { + let emitted = Arc::new(Mutex::new(Emitted { + draw: true, + ..Emitted::default() + })); + let result = self.execute(input_json, timeout_ms, Some(&emitted)); + let emitted = std::mem::take(&mut *emitted.lock().unwrap_or_else(PoisonError::into_inner)); + if let Some(failure) = emitted.failure { + return Err(failure); + } + result?; + limit( + emitted.view.unwrap_or_else(|| "null".to_owned()), + max_output_bytes, + ) + } + + /// One run's result; with `emitted`, a native step's: functions cross as markers, and `__widget_emit` writes the + /// view there. + fn execute( + &self, + input_json: &str, + timeout_ms: Option, + emitted: Option<&Arc>>, + ) -> Result { + if timeout_ms == Some(0) { + return Err(Error::invalid_input("timeout_ms must be at least 1")); + } + let first = Input::parse(input_json) + .map_err(|e| Error::invalid_input(format!("the input isn't JSON: {e}")))?; + let slot = Arc::new(Mutex::new(Slot { + text: input_json.into(), + first: Some(first), + })); + let name = self.input_name.clone(); + let emit = emitted.cloned(); + let mut runtime = Runtime::make() + .globals(move |_run| { + let slot = slot.clone(); + let input_name = name.clone(); + let mut globals = vec![( + name.clone(), + HostFunction::new(move |args: Vec, _call| -> HostResult { + json::unmarked(&args, &input_name, 0)?; + Ok(slot.lock().unwrap_or_else(PoisonError::into_inner).read()) + }), + )]; + if let Some(emitted) = emit.clone() { + globals.push(( + EMIT.to_owned(), + HostFunction::new(move |args: Vec, _call| { + emitted + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take(&args) + }) + .length(1), + )); + } + globals + }) + .limits(Limits { + timeout_ms, + max_value_depth: emitted.is_some().then_some(WIDGET_DEPTH), + ..Limits::default() + }); + if emitted.is_some() { + // A widget step: handler functions cross as markers. + runtime = runtime.translate(MARK); + } + let outcome = runtime.execute(&self.compiled); + drop(runtime); + outcome + .result + .map_err(|d| Error::from_diagnostic(d, timeout_ms)) + } +} + +/// The host global a native step hands its view to. +const EMIT: &str = "__widget_emit"; + +/// What a native step's `__widget_emit` took: the view's wire JSON (a draw step's commands as JSON), or why the view +/// failed. +#[derive(Default)] +struct Emitted { + /// A draw step: `__widget_emit(commands)`. + draw: bool, + view: Option, + failure: Option, +} + +impl Emitted { + /// `__widget_emit(view, failure?)`: a string `failure` fails the view with it; else the view is walked. In a draw + /// step, `__widget_emit(commands)`. + fn take(&mut self, args: &[HostValue]) -> HostResult { + json::unmarked(args, EMIT, 1)?; + if self.draw { + match draw::check_read(args.first().unwrap_or(&HostValue::Undefined)) { + Ok(commands) => self.view = Some(commands), + Err(reason) => self.failure = Some(Error::Draw { reason }), + } + return Ok(HostValue::Undefined); + } + if let Some(HostValue::String(failure)) = args.get(1) { + self.failure = Some(Error::View { + reason: failure.to_string_lossy().into_owned(), + }); + return Ok(HostValue::Undefined); + } + let mut out = String::new(); + match Walk::new().run(args.first().unwrap_or(&HostValue::Undefined), &mut out) { + Ok(_) => self.view = Some(out), + Err(WalkError::View(reason)) => { + self.failure = Some(Error::View { + reason: reason.to_owned(), + }) + } + Err(WalkError::Function) => return Err(json::carried(1, EMIT)), + Err(WalkError::Uri) => return Err(uri_error()), + } + Ok(HostValue::Undefined) + } +} + +/// The prelude's error for a key `encodeURIComponent` can't encode, located at the call. +pub(crate) fn uri_error() -> HostValue { + HostError::located("URIError", "URI malformed") +} + +/// `out`, unless it's over `max_output_bytes`. +fn limit(out: String, max_output_bytes: Option) -> Result { + match max_output_bytes { + Some(max) if out.len() as u64 > max => Err(Error::OutputTooLarge { + reason: format!( + "the result is {} bytes of JSON, over the limit of {max}", + out.len() + ), + max_output_bytes: max, + }), + _ => Ok(out), + } +} + +impl Program { + /// Starts the program as a [`LiveRun`] with `input_json` behind its input function and `__host`. + pub fn start_live(&self, input_json: &str, options: LiveOptions) -> Result { + LiveRun::start( + self.compiled.clone(), + self.input_name.clone(), + input_json, + options, + ) + } +} + +/// A run's input: the parsed value, handed over whole on the first read, and the text to read it again from. +struct Slot { + text: Arc, + first: Option, +} + +impl Slot { + fn read(&mut self) -> HostValue { + self.first + .take() + .unwrap_or_else(|| Input::parse(&self.text).unwrap_or_default()) + } +} diff --git a/packages/widgets-rs/crates/widget-web/src/time.rs b/packages/widgets-rs/crates/widget-web/src/time.rs new file mode 100644 index 00000000000..a15e544da83 --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/src/time.rs @@ -0,0 +1,6 @@ +//! `std::time::Instant` panics in a browser: `web-time` reads `performance.now()` there. + +#[cfg(not(target_arch = "wasm32"))] +pub use std::time::Instant; +#[cfg(target_arch = "wasm32")] +pub use web_time::Instant; diff --git a/packages/widgets-rs/crates/widget-web/src/tree.rs b/packages/widgets-rs/crates/widget-web/src/tree.rs new file mode 100644 index 00000000000..9d3128ebce6 --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/src/tree.rs @@ -0,0 +1,598 @@ +//! Building the view tree clients get, natively (widgets.md, "Native hosts"): from a view as the program built it +//! (handler props as function markers, `key`s, `children` as written) straight to the wire JSON, while writing it. It +//! makes exactly what the prelude's `__widget_tree` makes: props in order without `key`, `id`, `pointer`, `onPress`, +//! `onChange`, `onPointer` and `children`; then `id` (the node's path) on controls, `pointer: true` on a canvas with a +//! handler, and `children` last, flattened. It also tells which ids have handlers and the canvas ids by key. +//! +//! It holds views to the rules of views (widgets.md, "Keys and depth"): a key is a string, a number or a boolean, and +//! a view nests at most [`LEVELS`] levels. A function anywhere but a node's handler props fails, as it fails a host +//! call's argument without `"mark"`. +//! +//! The walk is generic over the value it reads ([`View`]): a host call's argument ([`HostValue`]), or JSON in tests. +//! Numbers and strings are written as `JSON.stringify` writes them. + +use std::borrow::Cow; +use std::collections::HashMap; +use std::fmt::Write as _; + +use psychoscript::{HostString, HostValue}; + +/// The most levels a view nests (widgets.md, "Keys and depth"). +pub const LEVELS: u32 = 100; +/// The failure of a view deeper than [`LEVELS`]. +pub const DEEP: &str = "The view nests more than 100 levels"; +/// The failure of a view with a key of another type. +pub const KEY: &str = "A node's key must be a string, a number or a boolean"; + +/// What a value is, as far as the walk cares. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// `undefined`, or a hole: falsy, left out of an object, `null` in an array. + Undefined, + /// A program function (the function marker): only a node's handler prop may hold one, which makes the node's id a + /// handler's. + Function, + Null, + Bool, + Number, + String, + Array, + Object, + /// Another object (a `Date`, a `Map`, ...): written as JSON writes it ([`View::write_other`]). + Other, +} + +/// A string as the walk reads it: UTF-8, or UTF-16 code units when it has an unpaired surrogate. +pub enum Text<'a> { + Str(&'a str), + Units(Cow<'a, [u16]>), +} + +/// A value the walk can read. +pub trait View: Sized { + fn kind(&self) -> Kind; + fn boolean(&self) -> bool; + fn number(&self) -> f64; + fn text(&self) -> Text<'_>; + /// An array's items in order; `None` for a hole. + fn items(&self) -> impl Iterator>; + /// An object's props in order. + fn props(&self) -> impl Iterator, &Self)>; + /// An object's prop by name. + fn get(&self, name: &str) -> Option<&Self>; + /// A [`Kind::Other`] value as JSON. + fn write_other(&self, out: &mut String) { + out.push_str("null"); + } +} + +/// The controls (widgets.md, Events): handler prop, event, whether it always has an id, whether a `key` gives one. +fn control(kind: &str) -> Option<(&'static str, &'static str, bool, bool)> { + Some(match kind { + "button" => ("onPress", "press", true, false), + "card" => ("onPress", "press", false, false), + "checkbox" => ("onChange", "change", true, false), + "slider" => ("onChange", "change", true, false), + "select" => ("onChange", "change", true, false), + "input" => ("onChange", "change", true, false), + "carousel" => ("onChange", "change", false, false), + "canvas" => ("onPointer", "pointer", false, true), + _ => return None, + }) +} + +const HANDLERS: [&str; 3] = ["onPress", "onChange", "onPointer"]; + +/// What the walk learned of a view besides its JSON. +#[derive(Debug, Default)] +pub struct Tree { + /// Some id has a handler. + pub has_handlers: bool, + /// The ids with handlers and their events, in the order met (a later node with the same id overrides), when asked + /// for ([`Walk::handlers`]). + pub handlers: Option>, + /// The first canvas with each `String(key)`: its id and how it is drawn. + pub canvases: HashMap, +} + +/// How a canvas is drawn (widgets.md, Canvas; widgets-gpu.md): one way only. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Drawn { + /// By draw commands. + Commands, + /// By its `wgsl`. + Wgsl, + /// By the program's WebGPU calls (`gpu: true`). + Gpu, +} + +/// Why a view didn't walk. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum WalkError { + /// It breaks a rule of views ([`KEY`], [`DEEP`]): a program error in phase `view`. + View(&'static str), + /// A function where none may go: the host call fails with the runtime's `TypeError`. + Function, + /// A key `encodeURIComponent` can't encode (a lone surrogate): the prelude's `URIError`. + Uri, +} + +/// One walk of one view. +pub struct Walk { + tree: Tree, + path: String, +} + +impl Walk { + pub fn new() -> Self { + Walk { + tree: Tree::default(), + path: String::with_capacity(64), + } + } + + /// Also collect every handler id with its event (for tests; a host only needs [`Tree::has_handlers`]). + pub fn handlers(mut self) -> Self { + self.tree.handlers = Some(Vec::new()); + self + } + + /// Writes the wire JSON of view `root` to `out`, and returns what it learned. `out` holds part of it on an error. + pub fn run(mut self, root: &V, out: &mut String) -> Result { + self.path.clear(); + if root.kind() != Kind::Object { + write_json(root, out)?; + return Ok(self.tree); + } + match root.get("key") { + Some(key) if keyed(key)? => segment(key, &mut self.path)?, + _ => self.path.push('0'), + } + self.node(root, 1, out)?; + Ok(self.tree) + } + + /// Node `v` at `self.path`, at `level`, its key checked. + fn node(&mut self, v: &V, level: u32, out: &mut String) -> Result<(), WalkError> { + out.push('{'); + let mut first = true; + let mut kind = None; + let mut children = None; + for (text, prop) in v.props() { + let name = match &text { + Text::Str(s) => Some(*s), + Text::Units(_) => None, + }; + match name { + Some("type") if prop.kind() == Kind::String => { + if let Text::Str(s) = prop.text() { + kind = control(s).map(|c| (s == "canvas", c)); + } + } + Some("children") => { + children = Some(prop); + continue; + } + Some(n) if HANDLERS.contains(&n) => continue, + Some("key" | "id" | "pointer") => { + if carries_function(prop) { + return Err(WalkError::Function); + } + continue; + } + _ => {} + } + match prop.kind() { + Kind::Undefined => continue, + Kind::Function => return Err(WalkError::Function), + _ => {} + } + if !first { + out.push(','); + } + first = false; + write_text(&text, out); + out.push(':'); + write_json(prop, out)?; + } + if let Some((canvas, (handler, event, always, by_key))) = kind { + let handled = v.get(handler).is_some_and(|h| h.kind() == Kind::Function); + let key = if by_key { + v.get("key") + .filter(|k| !matches!(k.kind(), Kind::Undefined | Kind::Null)) + } else { + None + }; + if handled || always || key.is_some() { + if !first { + out.push(','); + } + first = false; + // A path is ASCII without quotes or backslashes: `0`, `/`, digits, `.`, `~` and encoded keys. + out.push_str("\"id\":\""); + out.push_str(&self.path); + out.push('"'); + if handled { + self.tree.has_handlers = true; + if let Some(list) = &mut self.tree.handlers { + list.push((self.path.clone(), event)); + } + if canvas { + out.push_str(",\"pointer\":true"); + } + } + if let Some(key) = key { + let name = string_of(key); + if !self.tree.canvases.contains_key(&name) { + let drawn = if v.get("wgsl").is_some_and(|w| w.kind() == Kind::String) { + Drawn::Wgsl + } else if v + .get("gpu") + .is_some_and(|g| g.kind() == Kind::Bool && g.boolean()) + { + Drawn::Gpu + } else { + Drawn::Commands + }; + self.tree.canvases.insert(name, (self.path.clone(), drawn)); + } + } + } + } + if let Some(list) = children.filter(|c| c.kind() != Kind::Undefined) { + if !first { + out.push(','); + } + out.push_str("\"children\":["); + let mut seen: HashMap = HashMap::new(); + let mut any = false; + if list.kind() == Kind::Array { + self.flatten(list, "", level + 1, out, &mut seen, &mut any)?; + } else { + self.item(list, "0", level + 1, out, &mut seen, &mut any)?; + } + out.push(']'); + } + out.push('}'); + Ok(()) + } + + /// An array of children at `prefix` (`""`, `"2."`, `"2.1."`), its items at `level`. + fn flatten( + &mut self, + list: &V, + prefix: &str, + level: u32, + out: &mut String, + seen: &mut HashMap, + any: &mut bool, + ) -> Result<(), WalkError> { + let mut index = String::new(); + for (i, item) in list.items().enumerate() { + let Some(item) = item else { continue }; + index.clear(); + index.push_str(prefix); + let _ = write!(index, "{i}"); + self.item(item, &index, level, out, seen, any)?; + } + Ok(()) + } + + /// One item among a node's children, at `index` and `level`: skipped when falsy, flattened when an array. + fn item( + &mut self, + item: &V, + index: &str, + level: u32, + out: &mut String, + seen: &mut HashMap, + any: &mut bool, + ) -> Result<(), WalkError> { + if falsy(item) { + return Ok(()); + } + let kind = item.kind(); + if level > LEVELS && matches!(kind, Kind::Array | Kind::Object | Kind::Other) { + return Err(WalkError::View(DEEP)); + } + if kind == Kind::Array { + let mut deeper = String::with_capacity(index.len() + 1); + deeper.push_str(index); + deeper.push('.'); + return self.flatten(item, &deeper, level + 1, out, seen, any); + } + if *any { + out.push(','); + } + *any = true; + if kind != Kind::Object { + // A string, a number, `true`, or another object. + return write_json(item, out); + } + let len = self.path.len(); + self.path.push('/'); + match item.get("key") { + Some(key) if keyed(key)? => { + let at = self.path.len(); + segment(key, &mut self.path)?; + let n = seen.entry(self.path[at..].to_owned()).or_insert(0); + *n += 1; + if *n > 1 { + let _ = write!(self.path, "~{n}"); + } + } + _ => self.path.push_str(index), + } + let done = self.node(item, level, out); + self.path.truncate(len); + done + } +} + +impl Default for Walk { + fn default() -> Self { + Self::new() + } +} + +/// Whether `key` names a node: `undefined` and `null` don't, a string, a number or a boolean does, and anything else +/// fails the view. +fn keyed(key: &V) -> Result { + match key.kind() { + Kind::Undefined | Kind::Null => Ok(false), + Kind::String | Kind::Number | Kind::Bool => Ok(true), + Kind::Function | Kind::Array | Kind::Object | Kind::Other => Err(WalkError::View(KEY)), + } +} + +/// Whether `v` is or holds a function. +fn carries_function(v: &V) -> bool { + match v.kind() { + Kind::Function => true, + Kind::Array => v.items().flatten().any(carries_function), + Kind::Object => v.props().any(|(_, p)| carries_function(p)), + _ => false, + } +} + +/// JavaScript's truthiness, for children. +fn falsy(v: &V) -> bool { + match v.kind() { + Kind::Undefined | Kind::Null => true, + Kind::Bool => !v.boolean(), + Kind::Number => { + let n = v.number(); + n == 0.0 || n.is_nan() + } + Kind::String => match v.text() { + Text::Str(s) => s.is_empty(), + Text::Units(u) => u.is_empty(), + }, + Kind::Function | Kind::Array | Kind::Object | Kind::Other => false, + } +} + +/// `":" + encodeURIComponent(String(key))` of a key (a string, a number or a boolean), appended to `out`. +fn segment(key: &V, out: &mut String) -> Result<(), WalkError> { + out.push(':'); + match key.kind() { + Kind::String => match key.text() { + Text::Str(s) => encode(s, out), + Text::Units(_) => return Err(WalkError::Uri), + }, + _ => encode(&string_of(key), out), + } + Ok(()) +} + +/// `String(key)` of a key (a string, a number or a boolean), lossy for a lone surrogate (which `segment` refuses first). +fn string_of(v: &V) -> String { + match v.kind() { + Kind::String => match v.text() { + Text::Str(s) => s.to_owned(), + Text::Units(u) => String::from_utf16_lossy(&u), + }, + Kind::Number => number(v.number()), + Kind::Bool => (if v.boolean() { "true" } else { "false" }).to_owned(), + _ => String::new(), + } +} + +/// ECMAScript `Number::toString`. +fn number(n: f64) -> String { + let mut buffer = ryu_js::Buffer::new(); + buffer.format(n).to_owned() +} + +/// `encodeURIComponent` of well-formed text: UTF-8 bytes percent-encoded, uppercase, except `A-Z a-z 0-9 - _ . ! ~ * ' ( )`. +fn encode(s: &str, out: &mut String) { + for &b in s.as_bytes() { + if b.is_ascii_alphanumeric() + || matches!( + b, + b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')' + ) + { + out.push(b as char); + } else { + let _ = write!(out, "%{b:02X}"); + } + } +} + +/// A value of a view as `JSON.stringify` writes it (`undefined` left out of objects, `null` in arrays, non-finite +/// numbers `null`); a function fails. +fn write_json(v: &V, out: &mut String) -> Result<(), WalkError> { + match v.kind() { + Kind::Function => return Err(WalkError::Function), + Kind::Undefined | Kind::Null => out.push_str("null"), + Kind::Bool => out.push_str(if v.boolean() { "true" } else { "false" }), + Kind::Number => { + let n = v.number(); + if n.is_finite() { + out.push_str(ryu_js::Buffer::new().format_finite(n)); + } else { + out.push_str("null"); + } + } + Kind::String => write_text(&v.text(), out), + Kind::Other => v.write_other(out), + Kind::Array => { + out.push('['); + for (i, item) in v.items().enumerate() { + if i > 0 { + out.push(','); + } + match item { + Some(item) => write_json(item, out)?, + None => out.push_str("null"), + } + } + out.push(']'); + } + Kind::Object => { + out.push('{'); + let mut first = true; + for (name, prop) in v.props() { + match prop.kind() { + Kind::Undefined => continue, + Kind::Function => return Err(WalkError::Function), + _ => {} + } + if !first { + out.push(','); + } + first = false; + write_text(&name, out); + out.push(':'); + write_json(prop, out)?; + } + out.push('}'); + } + } + Ok(()) +} + +fn write_text(t: &Text<'_>, out: &mut String) { + match t { + Text::Str(s) => write_str(s, out), + Text::Units(u) => write_units(u, out), + } +} + +/// A string as `JSON.stringify` quotes it. +fn write_str(s: &str, out: &mut String) { + out.push('"'); + let mut start = 0; + for (i, b) in s.bytes().enumerate() { + let escape = match b { + b'"' => "\\\"", + b'\\' => "\\\\", + b'\n' => "\\n", + b'\r' => "\\r", + b'\t' => "\\t", + 0x08 => "\\b", + 0x0c => "\\f", + 0..=0x1f => "", + _ => continue, + }; + out.push_str(&s[start..i]); + if escape.is_empty() { + let _ = write!(out, "\\u{b:04x}"); + } else { + out.push_str(escape); + } + start = i + 1; + } + out.push_str(&s[start..]); + out.push('"'); +} + +/// UTF-16 text with unpaired surrogates, as `JSON.stringify` quotes it (`\udxxx` for each lone one). +fn write_units(units: &[u16], out: &mut String) { + out.push('"'); + for unit in char::decode_utf16(units.iter().copied()) { + match unit { + Ok(c) => { + let mut buf = [0u8; 4]; + let s: &str = c.encode_utf8(&mut buf); + let mut quoted = String::new(); + write_str(s, &mut quoted); + out.push_str("ed[1..quoted.len() - 1]); + } + Err(e) => { + let _ = write!(out, "\\u{:04x}", e.unpaired_surrogate()); + } + } + } + out.push('"'); +} + +fn host_text(s: &HostString) -> Text<'_> { + match s.as_str() { + Some(s) => Text::Str(s), + None => Text::Units(s.to_utf16()), + } +} + +impl View for HostValue { + fn kind(&self) -> Kind { + match self { + HostValue::Null => Kind::Null, + HostValue::Bool(_) => Kind::Bool, + HostValue::Number(_) => Kind::Number, + HostValue::String(_) => Kind::String, + HostValue::Array(_) => Kind::Array, + HostValue::Object(_) => Kind::Object, + HostValue::Function(_) | HostValue::FunctionMarker => Kind::Function, + HostValue::Undefined + | HostValue::Interrupt + | HostValue::Durable(_) + | HostValue::Namespace(_) => Kind::Undefined, + _ => Kind::Other, + } + } + fn boolean(&self) -> bool { + matches!(self, HostValue::Bool(true)) + } + fn number(&self) -> f64 { + match self { + HostValue::Number(n) => *n, + _ => f64::NAN, + } + } + fn text(&self) -> Text<'_> { + match self { + HostValue::String(s) => host_text(s), + _ => Text::Str(""), + } + } + fn items(&self) -> impl Iterator> { + let items: &[Option] = match self { + HostValue::Array(items) => items, + _ => &[], + }; + items.iter().map(Option::as_ref) + } + fn props(&self) -> impl Iterator, &Self)> { + let props: &[(HostString, HostValue)] = match self { + HostValue::Object(props) => props, + _ => &[], + }; + props.iter().map(|(k, v)| (host_text(k), v)) + } + fn get(&self, name: &str) -> Option<&Self> { + match self { + HostValue::Object(props) => props.iter().rev().find(|(k, _)| k == name).map(|(_, v)| v), + _ => None, + } + } + fn write_other(&self, out: &mut String) { + match self.to_json() { + Some(json) => { + let _ = write!(out, "{json}"); + } + None => out.push_str("null"), + } + } +} diff --git a/packages/widgets-rs/crates/widget-web/src/wasm.rs b/packages/widgets-rs/crates/widget-web/src/wasm.rs new file mode 100644 index 00000000000..12348593877 --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/src/wasm.rs @@ -0,0 +1,208 @@ +//! The JavaScript bindings (`wasm32-unknown-unknown`, wasm-bindgen). Errors are thrown as `Error`s named +//! `PsychoScriptError` with `type`, `kind`, `line`, `column` and `phase` (see [`crate::Error`]). + +use wasm_bindgen::prelude::*; + +#[cfg(feature = "language")] +use crate::{Error, LiveOptions, LiveRun, Program, Pump}; + +fn set(target: &JsValue, key: &str, value: JsValue) { + let _ = js_sys::Reflect::set(target, &JsValue::from_str(key), &value); +} + +#[cfg(feature = "language")] +fn thrown(e: Error) -> JsValue { + let error = js_sys::Error::new(e.reason()); + error.set_name("PsychoScriptError"); + let value: JsValue = error.into(); + set(&value, "type", e.type_name().into()); + if let Some(kind) = e.kind() { + set(&value, "kind", kind.into()); + } + if let Some((line, column)) = e.location() { + set(&value, "line", line.into()); + set(&value, "column", column.into()); + } + if let Some(phase) = e.phase() { + set(&value, "phase", phase.into()); + } + value +} + +/// A program compiled once, to run as often as needed (each run has its own VM). +#[cfg(feature = "language")] +#[wasm_bindgen(js_name = Program)] +pub struct JsProgram(Program); + +#[cfg(feature = "language")] +#[wasm_bindgen(js_class = Program)] +impl JsProgram { + /// Compiles `source`; its runs read their input through `inputName()` (`__input` by default). + #[wasm_bindgen(constructor)] + pub fn new(source: &str, input_name: Option) -> Result { + Program::new(source, input_name) + .map(JsProgram) + .map_err(thrown) + } + + /// Runs the program with `inputJson` behind its input function; returns its completion value as JSON. + pub fn run( + &self, + input_json: &str, + timeout_ms: Option, + max_output_bytes: Option, + ) -> Result { + self.0 + .run( + input_json, + timeout_ms.map(|t| t.max(1.0) as u64), + max_output_bytes.map(|m| m.max(0.0) as u64), + ) + .map_err(thrown) + } + + /// Runs a widget step natively (`return __widget_native_step(__input())`, widgets.md "Native hosts"): as `run`, + /// with the view the program gave `__widget_emit` added as `view`, written as the tree clients get. + #[wasm_bindgen(js_name = runStep)] + pub fn run_step( + &self, + input_json: &str, + timeout_ms: Option, + max_output_bytes: Option, + ) -> Result { + self.0 + .run_step( + input_json, + timeout_ms.map(|t| t.max(1.0) as u64), + max_output_bytes.map(|m| m.max(0.0) as u64), + ) + .map_err(thrown) + } + + /// Runs a widget draw step natively: the commands the program gave `__widget_emit`, as JSON (`null` for none). + #[wasm_bindgen(js_name = runDraw)] + pub fn run_draw( + &self, + input_json: &str, + timeout_ms: Option, + max_output_bytes: Option, + ) -> Result { + self.0 + .run_draw( + input_json, + timeout_ms.map(|t| t.max(1.0) as u64), + max_output_bytes.map(|m| m.max(0.0) as u64), + ) + .map_err(thrown) + } + + /// Starts the program as a live run with `inputJson` behind its input function and `__host`. `options`: + /// `{ sliceBudgetMs = 50, maxPostsPerSecond = 240, httpsHosts?: string[], allowLocalNetwork = false, + /// native = false }` (`native`: a `__widget_live(__input(), true)` run, widgets.md "Native hosts"). + #[wasm_bindgen(js_name = startLive)] + pub fn start_live(&self, input_json: &str, options: JsValue) -> Result { + let mut o = LiveOptions::default(); + if options.is_object() { + let get = |k: &str| js_sys::Reflect::get(&options, &JsValue::from_str(k)).ok(); + if let Some(n) = get("sliceBudgetMs").and_then(|v| v.as_f64()) { + o.slice_budget_ms = n.max(1.0) as u64; + } + if let Some(n) = get("maxPostsPerSecond").and_then(|v| v.as_f64()) { + o.max_posts_per_second = n.max(0.0) as u32; + } + o.allow_local_network = + get("allowLocalNetwork").is_some_and(|v| v.as_bool() == Some(true)); + o.native = get("native").is_some_and(|v| v.as_bool() == Some(true)); + if let Some(hosts) = get("httpsHosts").filter(js_sys::Array::is_array) { + o.https_hosts = Some( + js_sys::Array::from(&hosts) + .iter() + .filter_map(|h| h.as_string()) + .collect(), + ); + } + } + self.0 + .start_live(input_json, o) + .map(JsLiveRun) + .map_err(thrown) + } +} + +/// A long-running program, driven by `pump` (see `LiveRun` in the crate docs). +#[cfg(feature = "language")] +#[wasm_bindgen(js_name = LiveRun)] +pub struct JsLiveRun(LiveRun); + +#[cfg(feature = "language")] +#[wasm_bindgen(js_class = LiveRun)] +impl JsLiveRun { + /// Runs the program for up to `maxMs`. Returns `-3` once it ended (`exit()` says how), `-2` while still computing + /// (pump again soon), `-1` when it waits on the host with no timer, else the ms until its next timer. + pub fn pump(&mut self, max_ms: f64) -> f64 { + match self.0.pump(max_ms) { + Pump::Ended => -3.0, + Pump::Again => -2.0, + Pump::Wait(None) => -1.0, + Pump::Wait(Some(ms)) => ms, + } + } + + /// Queues a JSON message for `__host.receive()`. Pump afterwards. + pub fn deliver(&mut self, message_json: &str) -> Result<(), JsValue> { + self.0.deliver(message_json).map_err(thrown) + } + + /// What the program posted and the requests it made since the last call, as a JSON array. + #[wasm_bindgen(js_name = takeOutbox)] + pub fn take_outbox(&mut self) -> String { + self.0.take_outbox() + } + + /// The bytes of the GPU batches in the outbox `takeOutbox` just gave (`bytes: [offset, length]`): call it right + /// after. + #[wasm_bindgen(js_name = takeBytes)] + pub fn take_bytes(&mut self) -> Vec { + self.0.take_bytes() + } + + /// Answers fetch `id`: `metaJson` is `{ status, url, headers }` (the final URL), `body` the body's bytes. + #[wasm_bindgen(js_name = fetchDone)] + pub fn fetch_done(&mut self, id: f64, meta_json: &str, body: Vec) { + self.0.fetch_done(id as u64, meta_json, body); + } + + /// Fails fetch `id` with `kind` (`Network`, `Timeout`, `TooLarge`). + #[wasm_bindgen(js_name = fetchFailed)] + pub fn fetch_failed(&mut self, id: f64, kind: &str, message: &str) { + self.0.fetch_failed(id as u64, kind, message); + } + + pub fn pause(&mut self) -> Result<(), JsValue> { + self.0.pause().map_err(thrown) + } + + pub fn resume(&mut self) -> Result<(), JsValue> { + self.0.resume().map_err(thrown) + } + + pub fn stop(&mut self) { + self.0.stop(); + } + + #[wasm_bindgen(js_name = isPaused)] + pub fn is_paused(&self) -> bool { + self.0.is_paused() + } + + #[wasm_bindgen(js_name = nowMs)] + pub fn now_ms(&self) -> f64 { + self.0.now_ms() + } + + /// How the run ended, as JSON (`{ type: "finished", result }`, `{ type: "failed", error }`, + /// `{ type: "stopped" }`), or `undefined` while it runs. + pub fn exit(&self) -> Option { + self.0.exit().map(|e| e.to_json()) + } +} diff --git a/packages/widgets-rs/crates/widget-web/tests/draw.rs b/packages/widgets-rs/crates/widget-web/tests/draw.rs new file mode 100644 index 00000000000..dc2ca63693f --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/tests/draw.rs @@ -0,0 +1,139 @@ +//! The draw command checks against the shared fixtures (`packages/widget/test/fixtures/draw.json`, read in place): +//! every case through a draw step (the commands read as JSON reads them) and a live `widget.draw` (as they +//! cross) gives exactly its normalised commands, or fails with exactly its message in phase `draw`. + +use std::path::Path; +use std::time::{Duration, Instant}; + +use serde_json::Value; +use widget_web::{Error, LiveExit, LiveOptions, Program, Pump}; + +const SPECIAL: [&str; 4] = ["NaN", "Infinity", "-Infinity", "undefined"]; + +/// The case's commands as a JavaScript expression, `"$NaN"` and the like as those values. +fn expression(case: &Value) -> String { + if let Some(repeat) = case.get("repeat") { + return format!( + "Array.from({{ length: {} }}, () => {})", + repeat["count"], repeat["command"] + ); + } + let mut text = case["commands"].to_string(); + for name in SPECIAL { + text = text.replace(&format!("\"${name}\""), name); + } + text +} + +/// What the case expects: the normalised commands, or the failure's message. +fn expected(case: &Value) -> Result { + if let Some(error) = case.get("error") { + return Err(error.as_str().unwrap().to_owned()); + } + let valid = &case["valid"]; + Ok(match valid.get("repeat") { + Some(repeat) => Value::Array(vec![ + repeat["command"].clone(); + repeat["count"].as_u64().unwrap() as usize + ]), + None => valid.clone(), + }) +} + +/// A file of `@opencode/widget` (`packages/widget`), read in place. +fn read(name: &str) -> String { + std::fs::read_to_string( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../../widget") + .join(name), + ) + .unwrap() +} + +/// A step program's prelude; a live one's adds the live prelude (`packages/widget/src`). +fn prelude() -> String { + read("src/prelude.js") +} + +fn live_prelude() -> String { + format!( + "{}\n{}", + read("src/prelude.js"), + read("src/prelude-live.js") + ) +} + +fn parse(text: &str) -> Value { + serde_json::from_str(text).expect("JSON") +} + +fn failure(error: &Error) -> String { + assert_eq!(error.phase(), Some("draw"), "{error}"); + error.reason().to_owned() +} + +fn step(expression: &str) -> Result { + let program = format!( + "{}\nfunction view() {{ return ui.canvas({{ key: \"c\", height: 1 }}) }}\nfunction draw() {{ return {expression} }}\nreturn __widget_native_step(__input())", + prelude() + ); + let input = r#"{"phase":"draw","data":null,"state":{},"frame":{"id":":c","t":0,"dt":0,"width":10,"height":10,"scale":1,"pointer":null,"dark":false}}"#; + Program::new(&program, None) + .unwrap() + .run_draw(input, None, None) + .map(|out| parse(&out)) + .map_err(|e| failure(&e)) +} + +fn live(expression: &str) -> Result { + let program = format!( + "{}\nasync function main() {{\n widget.render(ui.canvas({{ key: \"c\", height: 1 }}))\n widget.draw(\"c\", {expression})\n}}\nreturn await __widget_live(__input(), true)", + live_prelude() + ); + let mut run = Program::new(&program, None) + .unwrap() + .start_live( + r#"{"data":null}"#, + LiveOptions { + native: true, + ..Default::default() + }, + ) + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(5); + let mut posts = Vec::new(); + loop { + let pump = run.pump(8.0); + let out = parse(&run.take_outbox()); + posts.extend(out.as_array().unwrap().iter().cloned()); + if pump == Pump::Ended || Instant::now() > deadline { + break; + } + std::thread::sleep(Duration::from_micros(200)); + } + match run.exit() { + Some(LiveExit::Failed { error }) => Err(failure(error)), + Some(LiveExit::Finished { .. }) => Ok(posts + .iter() + .find(|e| e["message"]["type"] == "draw") + .map(|e| { + assert_eq!(e["message"]["id"], ":c"); + e["message"]["commands"].clone() + }) + .unwrap_or(Value::Array(Vec::new()))), + other => panic!("{other:?}"), + } +} + +#[test] +fn every_draw_fixture_checks_alike_in_a_step_and_a_live_draw() { + let fixture = parse(&read("test/fixtures/draw.json")); + let cases = fixture["cases"].as_array().unwrap(); + assert_eq!(cases.len(), 89); + for case in cases { + let name = case["name"].as_str().unwrap(); + let (expression, want) = (expression(case), expected(case)); + assert_eq!(step(&expression), want, "step: {name}"); + assert_eq!(live(&expression), want, "live: {name}"); + } +} diff --git a/packages/widgets-rs/crates/widget-web/tests/live.rs b/packages/widgets-rs/crates/widget-web/tests/live.rs new file mode 100644 index 00000000000..bb598b236b6 --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/tests/live.rs @@ -0,0 +1,909 @@ +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use widget_web::{LiveExit, LiveOptions, LiveRun, Program, Pump}; + +const LOOP: &str = r#" +const input = __input() +__host.post({ type: "hello", n: input.n }) +while (true) { + const m = await __host.receive() + if (m.type === "sleep") { const t = __host.now(); await __host.sleep(m.ms); __host.post({ type: "slept", took: __host.now() - t }) } + if (m.type === "flood") { for (let i = 0; i < 300; i++) __host.post({ i }); __host.post({ type: "flooded" }) } + if (m.type === "throw") throw new TypeError("bad frame") + if (m.type === "resumed") __host.post({ type: "resumed", pausedMs: m.pausedMs }) + if (m.type === "fetch") { + try { __host.post({ type: "fetched", response: await __host.fetch(m.request) }) } + catch (e) { __host.post({ type: "rejected", kind: e.kind, message: e.message }) } + } + if (m.type === "done") return { ok: true } +} +"#; + +fn start(options: LiveOptions) -> LiveRun { + Program::new(LOOP, None) + .unwrap() + .start_live(r#"{"n":7}"#, options) + .unwrap() +} + +/// Pumps until the run waits with nothing woken, or ends; returns what it posted meanwhile. +fn settle(run: &mut LiveRun) -> Vec { + let mut out = Vec::new(); + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let pump = run.pump(8.0); + let outbox = run.take_outbox(); + // Views of 100 levels nest past serde_json's default limit of 128. + let mut reader = serde_json::Deserializer::from_str(&outbox); + reader.disable_recursion_limit(); + let batch: Vec = serde::Deserialize::deserialize(&mut reader).unwrap(); + out.extend(batch); + match pump { + Pump::Ended => return out, + Pump::Wait(_) if !run.woken() => return out, + _ if Instant::now() > deadline => panic!("the run didn't settle"), + _ => std::thread::sleep(Duration::from_micros(200)), + } + } +} + +fn posts(out: &[Value]) -> Vec { + out.iter() + .filter(|e| e["type"] == "post") + .map(|e| e["message"].clone()) + .collect() +} + +#[test] +fn posts_receives_and_finishes() { + let mut run = start(LiveOptions::default()); + assert_eq!( + posts(&settle(&mut run)), + vec![json!({ "type": "hello", "n": 7 })] + ); + run.deliver(r#"{"type":"done"}"#).unwrap(); + settle(&mut run); + assert_eq!( + run.exit(), + Some(&LiveExit::Finished { + result_json: r#"{"ok":true}"#.into() + }) + ); + assert!(run.deliver("{}").is_err()); +} + +#[test] +fn sleeps_report_their_timer_and_pause_freezes_them() { + let mut run = start(LiveOptions::default()); + settle(&mut run); + run.deliver(r#"{"type":"sleep","ms":40}"#).unwrap(); + assert!(posts(&settle(&mut run)).is_empty()); + let Pump::Wait(Some(left)) = run.pump(8.0) else { + panic!("expected a timer") + }; + assert!(left > 0.0 && left <= 40.0, "{left}"); + run.pause().unwrap(); + assert_eq!(run.pump(8.0), Pump::Wait(None)); + std::thread::sleep(Duration::from_millis(60)); + assert!( + posts(&settle(&mut run)).is_empty(), + "a paused sleep doesn't end" + ); + run.resume().unwrap(); + let mut seen = Vec::new(); + let deadline = Instant::now() + Duration::from_secs(2); + while seen.len() < 2 && Instant::now() < deadline { + seen.extend(posts(&settle(&mut run))); + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(seen[0]["type"], "slept"); + assert!(seen[0]["took"].as_f64().unwrap() < 55.0, "{seen:?}"); + assert_eq!(seen[1]["type"], "resumed"); + assert!(seen[1]["pausedMs"].as_f64().unwrap() >= 55.0); +} + +#[test] +fn deliveries_wait_while_paused() { + let mut run = start(LiveOptions::default()); + settle(&mut run); + run.pause().unwrap(); + run.deliver(r#"{"type":"throw"}"#).unwrap(); + settle(&mut run); + assert!(run.exit().is_none()); + run.resume().unwrap(); + settle(&mut run); + match run.exit() { + Some(LiveExit::Failed { error }) => { + assert!(error.reason().contains("bad frame"), "{error}") + } + other => panic!("{other:?}"), + } +} + +/// A generic run has no post rate: the widget rule lives in native runs. +#[test] +fn generic_runs_post_without_a_rate() { + let mut run = start(LiveOptions::default()); + settle(&mut run); + run.deliver(r#"{"type":"flood"}"#).unwrap(); + let out = settle(&mut run); + assert_eq!(posts(&out).len(), 301); + assert_eq!(out.iter().filter(|e| e["type"] == "warning").count(), 0); +} + +#[test] +fn fetches_need_the_capability_and_go_through_the_host() { + let mut denied = start(LiveOptions::default()); + settle(&mut denied); + denied + .deliver(r#"{"type":"fetch","request":{"url":"https://api.example.com/x"}}"#) + .unwrap(); + assert_eq!(posts(&settle(&mut denied))[0]["kind"], "CapabilityDenied"); + + let mut run = start(LiveOptions { + https_hosts: Some(vec!["api.example.com".into()]), + ..Default::default() + }); + settle(&mut run); + run.deliver(r#"{"type":"fetch","request":{"url":"https://other.example.com/x"}}"#) + .unwrap(); + assert_eq!(posts(&settle(&mut run))[0]["kind"], "CapabilityDenied"); + run.deliver( + r#"{"type":"fetch","request":{"url":"https://api.example.com/x","method":"post","headers":{"Cookie":"a","X-Key":"k"},"body":"hi"}}"#, + ) + .unwrap(); + let out = settle(&mut run); + let request = out + .iter() + .find(|e| e["type"] == "fetch") + .expect("a fetch for the host"); + assert_eq!(request["method"], "POST"); + assert_eq!(request["headers"], json!([["x-key", "k"]])); + assert_eq!(request["body"], "hi"); + let id = request["id"].as_u64().unwrap(); + run.fetch_done( + id, + r#"{"status":201,"url":"https://api.example.com/x","headers":[["content-type","application/json"]]}"#, + br#"{"a":1}"#.to_vec(), + ); + let fetched = posts(&settle(&mut run)); + assert_eq!(fetched[0]["response"]["status"], 201); + assert_eq!(fetched[0]["response"]["body"], r#"{"a":1}"#); + + run.deliver(r#"{"type":"fetch","request":{"url":"https://api.example.com/slow"}}"#) + .unwrap(); + let id = settle(&mut run)[0]["id"].as_u64().unwrap(); + run.fetch_failed(id, "Timeout", "no response within 15 s"); + assert_eq!(posts(&settle(&mut run))[0]["kind"], "Timeout"); + + run.deliver(r#"{"type":"fetch","request":{"url":"https://api.example.com/never"}}"#) + .unwrap(); + let id = settle(&mut run)[0]["id"].as_u64().unwrap(); + run.stop(); + assert_eq!(run.exit(), Some(&LiveExit::Stopped)); + let out: Vec = serde_json::from_str(&run.take_outbox()).unwrap(); + assert_eq!(out, vec![json!({ "type": "cancel", "id": id })]); +} + +#[test] +fn native_runs_build_render_trees_and_draw_by_key() { + const NATIVE: &str = r#" +const view = { type: "column", children: [ + [null, { type: "canvas", key: "board", height: 10, onPointer: () => {} }], + { type: "canvas", key: "sky", wgsl: "fn shade(p: vec2f) -> vec4f { return vec4f(1.0); }", height: 10 }, +] } +const interactive = __host.post({ type: "render", node: view }) +const still = __host.post({ type: "render", node: { ...view, children: [view.children[1]] } }) +__host.post({ type: "render", node: view }) +__host.post({ type: "draw", key: "board", commands: [["rect", 0, 0, 1, 1, { fill: "accent" }]] }) +const caught = [] +for (const key of ["nope", "sky"]) { + try { __host.post({ type: "draw", key, commands: [] }) } catch (e) { caught.push(e.message) } +} +// A function anywhere but a node's handler props fails the call with the runtime's TypeError. +const functions = [ + () => __host.post({ type: "send", value: { f: () => 1 } }), + () => __host.post({ type: "draw", key: "board", commands: [["rect", 0, 0, 1, 1, { fill: () => 1 }]] }), + () => __host.post({ type: "render", node: { type: "text", text: "x", extra: [() => 1] } }), + () => __host.post({ type: "render", node: { type: "button", label: "b", id: () => 1 } }), + () => __host.post({ type: "render", node: { type: "column", children: [() => 1] } }), + () => __host.post({ type: "render", node: view }, () => 1), + () => __host.now(() => 1), +] +// A real TypeError, sync or async. +const named = (e) => (e instanceof TypeError && e.constructor === TypeError ? "" : "not a TypeError: ") + e.name + ": " + e.message +for (const f of functions) { + try { f() } catch (e) { caught.push(named(e)) } +} +try { await __host.sleep(() => 1) } catch (e) { caught.push(named(e)) } +__host.post({ type: "result", interactive, still, caught }) +"#; + let mut run = Program::new(NATIVE, None) + .unwrap() + .start_live( + "null", + LiveOptions { + native: true, + ..Default::default() + }, + ) + .unwrap(); + let out = posts(&settle(&mut run)); + assert_eq!( + out[0], + json!({ "type": "render", "node": { "type": "column", "children": [ + { "type": "canvas", "height": 10, "id": "0/:board", "pointer": true }, + { "type": "canvas", "wgsl": "fn shade(p: vec2f) -> vec4f { return vec4f(1.0); }", "height": 10, "id": "0/:sky" }, + ] } }) + ); + assert_eq!(out[1]["node"]["children"][0]["id"], "0/:sky"); + assert_eq!(out[2], out[0]); + assert_eq!( + out[3], + json!({ "type": "draw", "id": "0/:board", "commands": [["rect", 0, 0, 1, 1, { "fill": "accent" }]] }) + ); + assert_eq!( + out[4], + json!({ "type": "result", "interactive": true, "still": false, "caught": [ + "No canvas with key \"nope\" in the rendered view", + "Canvas \"sky\" is drawn by its wgsl; it takes no draw commands", + "TypeError: Argument 1 to __host.post contains a function, which cannot be passed to the host.", + "TypeError: Argument 1 to __host.post contains a function, which cannot be passed to the host.", + "TypeError: Argument 1 to __host.post contains a function, which cannot be passed to the host.", + "TypeError: Argument 1 to __host.post contains a function, which cannot be passed to the host.", + "TypeError: Argument 1 to __host.post contains a function, which cannot be passed to the host.", + "TypeError: Argument 2 to __host.post contains a function, which cannot be passed to the host.", + "TypeError: Argument 1 to __host.now contains a function, which cannot be passed to the host.", + "TypeError: Argument 1 to __host.sleep contains a function, which cannot be passed to the host.", + ] }) + ); + assert_eq!(out.len(), 5); +} + +/// A live program on the prelude, started natively with a post rate of `rate` a second. +fn start_widget(source: &str, rate: u32) -> LiveRun { + let program = format!( + "{}\n{source}\nreturn await __widget_live(__input(), true)", + live_prelude() + ); + Program::new(&program, None) + .unwrap() + .start_live( + r#"{"data":null}"#, + LiveOptions { + native: true, + max_posts_per_second: rate, + ..Default::default() + }, + ) + .unwrap() +} + +/// Pumps `run` as a host does, its timers included, for `ms` or until it ends; returns what it posted meanwhile. +fn run_for(run: &mut LiveRun, ms: u64) -> Vec { + let mut out = Vec::new(); + let deadline = Instant::now() + Duration::from_millis(ms); + loop { + let pump = run.pump(8.0); + out.extend(posts(&parse(&run.take_outbox()))); + if pump == Pump::Ended || Instant::now() >= deadline { + return out; + } + std::thread::sleep(Duration::from_micros(500)); + } +} + +fn parse(outbox: &str) -> Vec { + let mut reader = serde_json::Deserializer::from_str(outbox); + reader.disable_recursion_limit(); + serde::Deserialize::deserialize(&mut reader).unwrap() +} + +/// The texts of the text views rendered in `out`. +fn texts(out: &[Value]) -> Vec { + out.iter() + .filter(|m| m["type"] == "render" && m["node"]["type"] == "text") + .map(|m| m["node"]["text"].as_str().unwrap_or_default().to_owned()) + .collect() +} + +/// The post rate (widgets-live.md): 30 renders at 10 a second: 8 at once (the burst), then the latest alone a tenth of +/// a second later; ending sends what waits first, before an answer. +#[test] +fn renders_over_the_post_rate_wait_and_coalesce() { + let mut run = start_widget( + "async function main() {\n for (let i = 0; i < 30; i++) widget.render(ui.text(String(i)))\n await widget.sleep(1000)\n widget.submit(1)\n}", + 10, + ); + let first: Vec = (0..8).map(|i| i.to_string()).collect(); + let mut out = run_for(&mut run, 60); + assert_eq!(texts(&out), first); + out.extend(run_for(&mut run, 100)); + assert_eq!(texts(&out), [first.clone(), vec!["29".into()]].concat()); + out.extend(run_for(&mut run, 3000)); + assert_eq!(out.last().unwrap()["type"], "submit"); + assert!(matches!(run.exit(), Some(LiveExit::Finished { .. }))); + for last in ["widget.submit(1)", "return"] { + let mut run = start_widget( + &format!( + "async function main() {{\n for (let i = 0; i < 30; i++) widget.render(ui.text(String(i)))\n {last}\n}}" + ), + 10, + ); + let out = run_for(&mut run, 3000); + assert_eq!( + texts(&out), + [first.clone(), vec!["29".into()]].concat(), + "{last}" + ); + let after: Vec<&str> = out + .iter() + .skip(9) + .filter_map(|m| m["type"].as_str()) + .collect(); + let want: &[&str] = if last == "return" { &[] } else { &["submit"] }; + assert_eq!(after, want, "{last}"); + } + // A client stop drops what waits. + let mut run = start_widget( + "async function main() {\n for (let i = 0; i < 30; i++) widget.render(ui.text(String(i)))\n await widget.sleep(1000)\n}", + 10, + ); + let out = run_for(&mut run, 30); + run.stop(); + assert_eq!(texts(&out), first); + assert_eq!(run.take_outbox(), "[]"); +} + +/// Draws coalesce by canvas key; a frame request under load is never counted or held. +#[test] +fn a_frame_request_under_load_is_answered_and_draws_coalesce_by_canvas() { + let mut run = start_widget( + r#"async function main() { + widget.render(ui.column([ui.canvas({ key: "a", height: 1 }), ui.canvas({ key: "b", height: 1 })])) + for (let i = 0; i < 20; i++) { widget.draw("a", [["alpha", i / 100]]); widget.draw("b", [["alpha", i / 50]]) } + const frame = await widget.frame() + widget.render(ui.text("frame " + frame.t)) +}"#, + 10, + ); + let mut out = run_for(&mut run, 20); + // The render and 7 draws took the burst; the frame request went out at once, ahead of the waiting draws. + let kinds: Vec<&str> = out.iter().map(|m| m["type"].as_str().unwrap()).collect(); + assert_eq!( + kinds, + [vec!["render"], vec!["draw"; 7], vec!["frame"]].concat() + ); + run.deliver(r#"{"type":"frame","frame":{"t":1,"dt":0,"width":2,"height":2,"scale":1,"pointer":null,"dark":true,"fullscreen":false,"close":null}}"#) + .unwrap(); + out.extend(run_for(&mut run, 3000)); + let draws: Vec = out + .iter() + .filter(|m| m["type"] == "draw") + .map(|m| json!([m["id"], m["commands"]])) + .collect(); + assert_eq!(draws.len(), 9); + assert_eq!( + draws[7..], + [ + json!(["0/:b", [["alpha", 0.38]]]), + json!(["0/:a", [["alpha", 0.19]]]) + ] + ); + assert_eq!(texts(&out), ["frame 1"]); + assert_eq!(out.last().unwrap()["type"], "render"); + assert!(matches!(run.exit(), Some(LiveExit::Finished { .. }))); +} + +/// A 120 Hz game posting a render and two draws a frame (360 a second): every frame request goes out, the counted posts +/// stay within the rate, and the last frame's view and drawings arrive. +#[test] +fn a_game_at_120_hz_runs_every_frame_and_shows_its_last_one() { + let mut run = start_widget( + r#"async function main() { + for (let n = 0; n < 120; n++) { + const frame = await widget.frame() + widget.render(ui.column([ui.text("n " + n), ui.canvas({ key: "a", height: 1 }), ui.canvas({ key: "b", height: 1 })])) + widget.draw("a", [["alpha", n / 1000]]) + widget.draw("b", [["alpha", n / 200]]) + } +}"#, + 240, + ); + let started = Instant::now(); + let mut out: Vec = Vec::new(); + let (mut frames, mut answered) = (0, 0); + let mut counted_in_a_second = 0; + while run.exit().is_none() && started.elapsed() < Duration::from_secs(5) { + let tick = Instant::now(); + let posted = run_for(&mut run, 0); + frames += posted.iter().filter(|m| m["type"] == "frame").count(); + if started.elapsed() <= Duration::from_secs(1) { + counted_in_a_second += posted + .iter() + .filter(|m| m["type"] == "render" || m["type"] == "draw") + .count(); + } + out.extend(posted); + // Each frame request is answered on the next display frame, as the page does. + if answered < frames && run.exit().is_none() { + answered += 1; + run.deliver(&format!( + r#"{{"type":"frame","frame":{{"t":{},"dt":0.008,"width":2,"height":2,"scale":1,"pointer":null,"dark":true,"fullscreen":false,"close":null}}}}"#, + answered as f64 / 120.0 + )) + .unwrap(); + } + std::thread::sleep(Duration::from_secs_f64(1.0 / 120.0).saturating_sub(tick.elapsed())); + } + out.extend(run_for(&mut run, 0)); + assert_eq!(frames, 120); + assert!(counted_in_a_second <= 240 + 8 + 3, "{counted_in_a_second}"); + assert!( + matches!(run.exit(), Some(LiveExit::Finished { .. })), + "{:?}", + run.exit() + ); + let last_render = out.iter().rev().find(|m| m["type"] == "render").unwrap(); + assert_eq!(last_render["node"]["children"][0]["text"], "n 119"); + let last_b = out + .iter() + .rev() + .find(|m| m["type"] == "draw" && m["id"] == "0/:b") + .unwrap(); + assert_eq!(last_b["commands"], json!([["alpha", 0.595]])); +} + +/// A draw post without a string key is an invalid post: the run ends. +#[test] +fn a_draw_post_without_a_string_key_ends_the_run() { + for post in [ + r#"__host.post({ type: "draw", id: "0", commands: [] })"#, + r#"__host.post({ type: "draw", key: 1, commands: [] })"#, + ] { + let mut run = start_widget( + &format!( + "async function main() {{\n widget.render(ui.canvas({{ key: \"c\", height: 1 }}))\n try {{ {post} }} catch (e) {{ widget.send(\"caught\") }}\n}}" + ), + 240, + ); + let out = run_for(&mut run, 3000); + assert_eq!(out.len(), 1, "{post}: {out:?}"); + match run.exit() { + Some(LiveExit::Failed { error }) => { + assert_eq!(error.reason(), "A draw post needs a string key", "{post}") + } + other => panic!("{post}: {other:?}"), + } + } +} + +/// A draw post goes to the client as its canvas's id and commands only; one over 2,000 commands is an invalid post, +/// which ends the run in phase `draw`, what waits for the post rate going out first. +#[test] +fn draw_posts_carry_id_and_commands_and_end_the_run_over_2000_commands() { + let mut run = start_widget( + r#"async function main() { + widget.render(ui.canvas({ key: "c", height: 1 })) + __host.post({ type: "draw", key: "c", commands: [["rect", 0, 0, 1, 1, { fill: "accent" }]], extra: 1 }) + for (let i = 0; i < 10; i++) widget.render(ui.canvas({ key: "c", height: i + 1 })) + try { widget.draw("c", Array.from({ length: 2001 }, () => ["save"])) } catch (e) { widget.send("caught") } + widget.send("after") +}"#, + 240, + ); + let out = run_for(&mut run, 3000); + assert_eq!( + out[1], + json!({ "type": "draw", "id": ":c", "commands": [["rect", 0, 0, 1, 1, { "fill": "accent" }]] }) + ); + // The latest render goes out (at once or when the run ends); nothing after the invalid draw does. + assert_eq!(out.last().unwrap()["node"]["height"], 10, "{out:?}"); + assert!(out.iter().all(|m| m["type"] != "send"), "{out:?}"); + match run.exit() { + Some(LiveExit::Failed { error }) => { + assert_eq!(error.phase(), Some("draw")); + assert_eq!( + error.reason(), + "2001 draw commands is over the budget of 2000 per frame" + ); + } + other => panic!("{other:?}"), + } +} + +/// Every command is checked when the program posts it, with the other hosts' rules and messages: the first invalid one +/// ends the run in phase `draw`, named by its index; valid ones of every kind go through. +#[test] +fn an_invalid_draw_command_ends_the_run_in_phase_draw() { + let draw = |commands: &str| { + let mut run = start_widget( + &format!( + "async function main() {{\n widget.render(ui.canvas({{ key: \"c\", height: 1 }}))\n __host.post({{ type: \"draw\", key: \"c\"{commands} }})\n widget.send(\"after\")\n}}" + ), + 240, + ); + let out = run_for(&mut run, 3000); + match run.exit() { + Some(LiveExit::Failed { error }) => { + assert_eq!(error.phase(), Some("draw"), "{commands}"); + assert!( + out.iter() + .all(|m| m["type"] != "send" && m["type"] != "draw"), + "{out:?}" + ); + Err(error.reason().to_owned()) + } + Some(LiveExit::Finished { .. }) => { + Ok(out.into_iter().find(|m| m["type"] == "draw").unwrap()) + } + other => panic!("{commands}: {other:?}"), + } + }; + for (commands, message) in [ + ( + r#", commands: [["save"], ["rect", 0, 0, 1, 1, "accent"]]"#, + "draw command 1: a paint is an object", + ), + ( + r#", commands: [["blur", 1]]"#, + "draw command 0: unknown draw command \"blur\"", + ), + ( + r#", commands: [["alpha", "x"]]"#, + "draw command 0: \"alpha\" argument 1 must be a finite number", + ), + ( + r#", commands: [["rect", 0, 0, 1, NaN, {}]]"#, + "draw command 0: \"rect\" argument 4 must be a finite number", + ), + ( + r##", commands: [["circle", 0, 0, 1, { fill: "#12" }]]"##, + "draw command 0: not a color", + ), + ( + r#", commands: [["line", 0, 0, 1, 1, { stroke: "accent", width: "2" }]]"#, + "draw command 0: a stroke's width must be a finite number", + ), + ( + r#", commands: [["rect", 0, 0, 1, 1, { fill: { linear: [0, 0, 1], stops: [] } }]]"#, + "draw command 0: a linear gradient takes 4 numbers", + ), + ( + r#", commands: [["rect", 0, 0, 1, 1, { fill: { radial: [0, 0, 1], stops: [[0]] } }]]"#, + "draw command 0: a stop is [offset, color]", + ), + ( + r#", commands: [["path", [["M", 0, 0], ["X", 1]], {}]]"#, + "draw command 0: unknown path segment", + ), + ( + r#", commands: [["text", 0, 0]]"#, + "draw command 0: \"text\" is missing argument 3", + ), + ( + r#", commands: [["text", 0, 0, "t", { size: "big" }]]"#, + "draw command 0: a text size must be a finite number", + ), + ( + r#", commands: [["image", 1, 0, 0, 1, 1]]"#, + "draw command 0: \"image\" takes a src", + ), + ( + r#", commands: [5]"#, + "draw command 0: a command is an array", + ), + ( + r#", commands: [[1]]"#, + "draw command 0: a command starts with its name", + ), + (r#", commands: "x""#, "draw commands must be a list"), + ("", "draw commands must be a list"), + ] { + assert_eq!(draw(commands), Err(message.to_owned()), "{commands}"); + } + // Every kind, as the prelude's builder writes it, goes through as it was posted. + let valid = r##"ui.draw().save().translate(1, 2).rotate(0.5).scale(2).alpha(0.5).rect(0, 0, 1, 1, "accent").rrect(0, 0, 4, 4, 1, { fill: { linear: [0, 0, 1, 1], stops: [[0, "#fff"], [1, "#000000aa"]] }, stroke: "border", width: 2, cap: "round" }).circle(1, 1, 1, { fill: { radial: [1, 1, 1], stops: [[0, "bg"]] } }).line(0, 0, 1, 1, "muted").path([["M", 0, 0], ["L", 1, 1], ["Q", 1, 0, 2, 2], ["C", 0, 0, 1, 1, 2, 2], ["Z"]], "success").text(0, 10, "hi", { size: 12, weight: 600, align: "center", color: "#abc", mono: true }).image("a.png", 0, 0, 1, 1).restore().commands"##; + let posted = draw(&format!(", commands: {valid}")).expect("valid commands"); + assert_eq!(posted["commands"].as_array().unwrap().len(), 13); +} + +/// GPU batches (widgets-gpu.md, Transport) go out at once, in a frame request or on their own, as they are for the +/// client's checks: their ops as JSON and an `ArrayBuffer`'s bytes in the byte outbox, named by `[offset, length]`; +/// other bytes `null`, a batch that isn't an object whole. A render names its GPU canvases' ids by key. +#[test] +fn gpu_batches_carry_their_ops_and_bytes() { + let mut run = start_widget( + r#"async function main() { + widget.render(ui.column([ui.canvas({ key: "scene", gpu: true, height: 10 }), ui.canvas({ key: "flat", height: 10 })])) + const data = new Float32Array([1, 2]) + __host.post({ type: "gpu", ops: [["context", 1, "scene", "bgra8unorm", "opaque"], ["buffer", 3, 8, 40], ["writeBuffer", 3, 0, 0, 8]], bytes: data.buffer }) + __host.post({ type: "frame", gpu: { ops: [["writeBuffer", 3, 0, 0, 4]], bytes: new Uint32Array([7]).buffer } }) + __host.post({ type: "gpu", ops: "x", bytes: new Uint8Array(2) }) + __host.post({ type: "gpu", bytes: new ArrayBuffer(1) }) + __host.post({ type: "frame", gpu: 5 }) + try { widget.draw("scene", []) } catch (e) { widget.send(e.message) } + try { __host.post({ type: "gpu", ops: [["shader", 4, () => 1]], bytes: new ArrayBuffer(0) }) } catch (e) { widget.send(e.name) } +}"#, + 240, + ); + let mut out = Vec::new(); + let mut bytes = Vec::new(); + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let pump = run.pump(8.0); + out.extend(posts(&parse(&run.take_outbox()))); + bytes.extend(run.take_bytes()); + if pump == Pump::Ended || Instant::now() > deadline { + break; + } + } + assert_eq!( + out[0]["gpu"], + json!({ "scene": out[0]["node"]["children"][0]["id"] }) + ); + assert_eq!( + out[1], + json!({ "type": "gpu", "batch": { "ops": [ + ["context", 1, "scene", "bgra8unorm", "opaque"], + ["buffer", 3, 8, 40], + ["writeBuffer", 3, 0, 0, 8], + ], "bytes": [0, 8] } }) + ); + assert_eq!( + out[2], + json!({ "type": "frame", "gpu": { "ops": [["writeBuffer", 3, 0, 0, 4]], "bytes": [8, 4] } }) + ); + assert_eq!( + out[3], + json!({ "type": "gpu", "batch": { "ops": "x", "bytes": null } }) + ); + assert_eq!( + out[4], + json!({ "type": "gpu", "batch": { "bytes": [12, 1] } }) + ); + assert_eq!(out[5], json!({ "type": "frame", "gpu": 5 })); + let floats: Vec = [1.0f32, 2.0].iter().flat_map(|f| f.to_le_bytes()).collect(); + assert_eq!( + bytes, + [floats, 7u32.to_le_bytes().to_vec(), vec![0]].concat() + ); + assert_eq!( + out[6]["value"], + "Canvas \"scene\" is drawn by the GPU; it takes no draw commands" + ); + assert_eq!(out[7]["value"], "TypeError"); +} + +/// A GPU batch's ops cross as JSON reads them (widgets-gpu.md, Transport): an `undefined` list item is `null`, an +/// `undefined` member is absent. Numbers stay as they are: a non-finite one, written `null`, is listed by its path in +/// `nonFinite` for the client to put back; a batch without one has no `nonFinite`. +#[test] +fn gpu_batch_ops_keep_non_finite_numbers_by_path() { + let mut run = start_widget( + r#"async function main() { + widget.render(ui.canvas({ key: "scene", gpu: true, height: 10 })) + __host.post({ type: "gpu", ops: [["pass", { colorAttachments: [undefined, { clearValue: [0, NaN, Infinity], "a\"b": -Infinity, gone: undefined }] }], ["buffer", 1, NaN, 4]], bytes: new ArrayBuffer(0) }) + __host.post({ type: "frame", gpu: { ops: NaN, bytes: new ArrayBuffer(0) } }) + __host.post({ type: "gpu", ops: [["buffer", 2, null, 4]], bytes: new ArrayBuffer(0) }) +}"#, + 240, + ); + let out = run_for(&mut run, 200); + assert_eq!( + out[1], + json!({ "type": "gpu", "batch": { + "ops": [["pass", { "colorAttachments": [null, { "clearValue": [0, null, null], "a\"b": null }] }], ["buffer", 1, null, 4]], + "nonFinite": [ + [[0, 1, "colorAttachments", 1, "clearValue", 1], "NaN"], + [[0, 1, "colorAttachments", 1, "clearValue", 2], "Infinity"], + [[0, 1, "colorAttachments", 1, "a\"b"], "-Infinity"], + [[1, 2], "NaN"], + ], + "bytes": [0, 0], + } }) + ); + assert_eq!( + out[2], + json!({ "type": "frame", "gpu": { "ops": null, "nonFinite": [[[], "NaN"]], "bytes": [0, 0] } }) + ); + assert_eq!( + out[3], + json!({ "type": "gpu", "batch": { "ops": [["buffer", 2, null, 4]], "bytes": [0, 0] } }) + ); +} + +/// A GPU batch never overtakes a waiting render or draw: it waits behind them (taking no token) and goes out right +/// after the post before it, with its bytes; a frame request without a batch still goes out at once. +#[test] +fn gpu_batches_wait_in_order_behind_waiting_posts() { + let mut run = start_widget( + r#"async function main() { + for (let i = 0; i < 10; i++) widget.render(ui.column([ui.text(String(i)), ui.canvas({ key: "scene", gpu: true, height: 1 })])) + __host.post({ type: "gpu", ops: [["context", 1, "scene", "bgra8unorm", "opaque"]], bytes: new Uint8Array([9, 8]).buffer }) + __host.post({ type: "frame" }) + __host.post({ type: "frame", gpu: { ops: [["submit"]], bytes: new Uint8Array([7]).buffer } }) + await widget.sleep(1000) +}"#, + 10, + ); + let (mut out, mut bytes) = (Vec::new(), Vec::new()); + let collect = |run: &mut LiveRun, ms, out: &mut Vec, bytes: &mut Vec| { + out.extend(run_for(run, ms)); + bytes.extend(run.take_bytes()); + }; + collect(&mut run, 30, &mut out, &mut bytes); + let kinds = |out: &[Value]| -> Vec { + out.iter() + .map(|m| match m["type"].as_str().unwrap() { + "render" => format!( + "render {}", + m["node"]["children"][0]["text"].as_str().unwrap() + ), + other => other.to_owned(), + }) + .collect() + }; + // The burst's 8 renders, and the bare frame request at once; the batches wait behind render 9. + assert_eq!( + kinds(&out), + [ + "render 0", "render 1", "render 2", "render 3", "render 4", "render 5", "render 6", + "render 7", "frame" + ] + ); + assert!(out[8].get("gpu").is_none()); + collect(&mut run, 150, &mut out, &mut bytes); + assert_eq!(kinds(&out)[9..], ["render 9", "gpu", "frame"]); + assert_eq!(out[10]["batch"]["bytes"], json!([0, 2])); + assert_eq!(out[11]["gpu"]["bytes"], json!([2, 1])); + assert_eq!(bytes, [9, 8, 7]); +} + +/// A live program on the live prelude, run natively. +fn widget(source: &str) -> (Vec, Option) { + let program = format!( + "{}\n{source}\nreturn await __widget_live(__input(), true)", + live_prelude() + ); + let mut run = Program::new(&program, None) + .unwrap() + .start_live( + r#"{"data":null}"#, + LiveOptions { + native: true, + ..Default::default() + }, + ) + .unwrap(); + let out = posts(&settle(&mut run)); + (out, run.exit().cloned()) +} + +/// Uncaught, a function where none may go fails the run as the runtime's TypeError, at the call, sync or async; so +/// does a draw to an unknown canvas key. +#[test] +fn a_function_posted_where_none_may_go_fails_the_run_at_the_call() { + for (call, line) in [ + ("widget.send({ f: () => 1 })", 2), + ("__host.post({ type: \"send\", value: 1 }, () => 1)", 2), + ("await __host.sleep(() => 1)", 2), + ("await __host.receive(() => 1)", 2), + ("__host.now(() => 1)", 2), + ] { + let (_, exit) = widget(&format!("async function main() {{\n {call}\n}}")); + let Some(LiveExit::Failed { error }) = exit else { + panic!("{call}: {exit:?}") + }; + assert!( + error.reason().starts_with("TypeError: Argument ") + && error + .reason() + .contains(" contains a function, which cannot be passed to the host.") + && error.location().is_some() == (line > 0), + "{call}: {error}" + ); + if line > 0 && !call.starts_with("widget.") { + assert_eq!( + error.location().map(|(l, _)| l), + Some(prelude_lines() + 1 + line), + "{call}" + ); + } + } + let (_, exit) = widget( + "async function main() {\n __host.post({ type: \"draw\", key: \"nope\", commands: [] })\n}", + ); + let Some(LiveExit::Failed { error }) = exit else { + panic!("{exit:?}") + }; + assert_eq!( + (error.reason(), error.location().map(|(l, _)| l)), + ( + format!( + "Error: No canvas with key \"nope\" in the rendered view (line {}, col 3)", + prelude_lines() + 3 + ) + .as_str(), + Some(prelude_lines() + 3) + ) + ); +} + +/// What a live program has before its source (`packages/widget/src`, read in place): the prelude, a newline, the +/// live prelude. +fn live_prelude() -> String { + let read = |name: &str| { + std::fs::read_to_string( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../../widget/src") + .join(name), + ) + .unwrap() + }; + format!("{}\n{}", read("prelude.js"), read("prelude-live.js")) +} + +/// The live prelude's lines; it ends with a newline, so with the joining one the widget template starts two lines on. +fn prelude_lines() -> u32 { + live_prelude().lines().count() as u32 +} + +#[test] +fn a_render_that_breaks_a_rule_of_views_ends_the_run_in_phase_view() { + let view = |reason: &str| { + Some(LiveExit::Failed { + error: widget_web::Error::View { + reason: reason.into(), + }, + }) + }; + // Rendered first, then the key of another type: the first render went out, the run ends at the second. + let (out, exit) = widget( + r#"async function main() { + widget.render(ui.text("first")) + try { widget.render(ui.column([ui.button("b", { key: {} })])) } catch (e) { widget.send("caught " + e.message) } + widget.send("after") +}"#, + ); + assert_eq!( + out, + vec![json!({ "type": "render", "node": { "type": "text", "text": "first" } })] + ); + assert_eq!(exit, view(widget_web::tree::KEY)); + // 100 levels render; 101 end the run. + let deep = |levels: usize| { + format!( + "async function main() {{\n let node = ui.text(\"x\")\n for (let i = 1; i < {levels}; i++) node = ui.column([node])\n widget.render(node)\n}}" + ) + }; + let (out, exit) = widget(&deep(100)); + assert_eq!( + (out.len(), exit), + ( + 1, + Some(LiveExit::Finished { + result_json: "null".into() + }) + ) + ); + let (out, exit) = widget(&deep(101)); + assert!(out.is_empty()); + assert_eq!(exit, view(widget_web::tree::DEEP)); + // Deep only in a prop, past the boundary of 202: the boundary's own error, which the program gets. + let (_, exit) = widget( + r#"async function main() { + widget.render(ui.text("x", { extra: JSON.parse("[".repeat(210) + "]".repeat(210)) })) +}"#, + ); + match exit { + Some(LiveExit::Failed { error }) => { + assert!( + error.reason().contains("exceeds the maximum value depth"), + "{error}" + ) + } + other => panic!("{other:?}"), + } +} diff --git a/packages/widgets-rs/crates/widget-web/tests/program.rs b/packages/widgets-rs/crates/widget-web/tests/program.rs new file mode 100644 index 00000000000..5a68f9a1d35 --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/tests/program.rs @@ -0,0 +1,112 @@ +use widget_web::{Error, LiveOptions, Program, Pump}; + +const STEP: &str = r#" +function __widget_step(input) { + if (input.phase === "init") return { state: { n: 0 }, view: { type: "text", text: "0" } } + const n = input.state.n + 1 + return { state: { n }, view: { type: "text", text: String(n) } } +} +return __widget_step(__input()) +"#; + +#[test] +fn runs_a_step_per_input() { + let program = Program::new(STEP, None).unwrap(); + let init = program + .run(r#"{"phase":"init","data":{}}"#, Some(250), None) + .unwrap(); + assert_eq!( + init, + r#"{"state":{"n":0},"view":{"type":"text","text":"0"}}"# + ); + let next = program + .run( + r#"{"phase":"event","data":{},"state":{"n":4},"event":{"id":"x","type":"press"}}"#, + Some(250), + None, + ) + .unwrap(); + assert_eq!( + next, + r#"{"state":{"n":5},"view":{"type":"text","text":"5"}}"# + ); +} + +#[test] +fn syntax_errors_have_a_place() { + let e = Program::new("let x = ;", None).unwrap_err(); + assert!(matches!(e, Error::Syntax { line: Some(1), .. }), "{e:?}"); + assert_eq!(e.type_name(), "syntax"); +} + +#[test] +fn runs_time_out_and_throw() { + let spin = Program::new("while (true) {}", None).unwrap(); + assert!(matches!( + spin.run("null", Some(20), None), + Err(Error::Timeout { timeout_ms: 20, .. }) + )); + let throws = Program::new("throw new TypeError('bad')", None).unwrap(); + let e = throws.run("null", None, None).unwrap_err(); + assert_eq!(e.kind(), Some("ExecutionFailure")); + assert!(e.reason().contains("TypeError: bad"), "{e}"); + assert!(e.to_json().contains(r#""type":"runtime""#)); +} + +#[test] +fn inputs_and_outputs_are_checked() { + let echo = Program::new("return __input()", None).unwrap(); + assert!(matches!( + echo.run("{", None, None), + Err(Error::InvalidInput { .. }) + )); + assert!(matches!( + echo.run(r#""a long string""#, None, Some(4)), + Err(Error::OutputTooLarge { + max_output_bytes: 4, + .. + }) + )); + let named = Program::new("return input().a", Some("input".into())).unwrap(); + assert_eq!( + named.run(r#"{"a":[1,"x"]}"#, None, None).unwrap(), + r#"[1,"x"]"# + ); +} + +/// Typed arrays are the language's (psychoscript 0.1): plain runs and widget runs (`run_step`, native live runs) +/// alike have them. +#[test] +fn every_run_has_typed_arrays() { + let probe = "typeof Float32Array + \" \" + typeof ArrayBuffer"; + let plain = Program::new(&format!("return {probe}"), None).unwrap(); + assert_eq!( + plain.run("null", None, None).unwrap(), + r#""function function""# + ); + let step = Program::new( + &format!("__widget_emit({{ type: \"text\", text: {probe} }})\nreturn {{ state: {{}} }}"), + None, + ) + .unwrap(); + assert!( + step.run_step("null", None, None) + .unwrap() + .contains(r#""text":"function function""#) + ); + let mut live = Program::new( + &format!("__host.post({{ type: \"probe\", text: {probe} }})"), + None, + ) + .unwrap() + .start_live( + "null", + LiveOptions { + native: true, + ..Default::default() + }, + ) + .unwrap(); + while live.pump(8.0) != Pump::Ended {} + assert!(live.take_outbox().contains(r#""text":"function function""#)); +} diff --git a/packages/widgets-rs/crates/widget-web/tests/tree.rs b/packages/widgets-rs/crates/widget-web/tests/tree.rs new file mode 100644 index 00000000000..bd349263a32 --- /dev/null +++ b/packages/widgets-rs/crates/widget-web/tests/tree.rs @@ -0,0 +1,549 @@ +//! The native host against the conformance fixtures (`packages/widget/test/fixtures/wire`, read in place, with +//! `packages/widget/src/prelude.js`). Each fixture holds a widget template `source` and a step `input`, `built` (the +//! view as emitted, each function as `"$function"`) when it crosses, and either `view`, `handlers`, `canvases` and +//! `result`, or `error`. The view the walk must write byte for byte is `JSON.stringify(JSON.parse(..).view)` +//! ([`stringify`]). + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::Instant; + +use psychoscript::{ + HostFunction, HostValue, Limits, Runtime, Translate, TranslateFunctions, TranslatePromises, +}; +use serde_json::Value; +use widget_web::tree::{DEEP, Walk, WalkError}; +use widget_web::{Error, Program}; + +const ENTRY: &str = "\nreturn __widget_native_step(__input())"; + +/// `@opencode/widget` (`packages/widget`). +fn widget() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../widget") +} + +fn dir() -> PathBuf { + widget().join("test/fixtures/wire") +} + +/// A fixture's JSON as `JSON.stringify` writes it once `JSON.parse` has read it: numbers as ECMAScript writes them +/// (`Number::toString`), an object's array-index keys first in ascending order, then the others in order. +fn stringify(v: &Value, out: &mut String) { + match v { + Value::Number(n) => { + out.push_str(ryu_js::Buffer::new().format(n.as_f64().expect("a number"))); + } + Value::Array(items) => { + out.push('['); + for (i, item) in items.iter().enumerate() { + if i > 0 { + out.push(','); + } + stringify(item, out); + } + out.push(']'); + } + Value::Object(props) => { + let index = |k: &str| { + k.parse::() + .ok() + .filter(|i| *i != u32::MAX && i.to_string() == k) + }; + let mut keys: Vec<&String> = props.keys().collect(); + keys.sort_by_key(|k| index(k).map_or((1, 0), |i| (0, i))); + out.push('{'); + for (i, k) in keys.into_iter().enumerate() { + if i > 0 { + out.push(','); + } + out.push_str(&serde_json::to_string(k).unwrap()); + out.push(':'); + stringify(&props[k], out); + } + out.push('}'); + } + // null, booleans, and strings, which `serde_json` escapes as `JSON.stringify` does. + other => out.push_str(&serde_json::to_string(other).unwrap()), + } +} + +/// A fixture's `built` as the host value `__widget_emit` gets. +fn host(v: &Value) -> HostValue { + match v { + Value::Null => HostValue::Null, + Value::Bool(b) => HostValue::Bool(*b), + Value::Number(n) => HostValue::Number(n.as_f64().unwrap_or(f64::NAN)), + Value::String(s) => match s.as_str() { + "$function" => HostValue::FunctionMarker, + "$NaN" => HostValue::Number(f64::NAN), + "$Infinity" => HostValue::Number(f64::INFINITY), + "$-Infinity" => HostValue::Number(f64::NEG_INFINITY), + s => HostValue::String(s.into()), + }, + Value::Array(items) => HostValue::Array(items.iter().map(|i| Some(host(i))).collect()), + Value::Object(props) => HostValue::Object( + props + .iter() + .map(|(k, v)| (k.as_str().into(), host(v))) + .collect(), + ), + } +} + +/// An emitted view as a fixture's `built` writes it. +fn built(v: &HostValue) -> Value { + match v { + HostValue::Null | HostValue::Undefined => Value::Null, + HostValue::Bool(b) => Value::Bool(*b), + HostValue::Number(n) if n.is_nan() => "$NaN".into(), + HostValue::Number(n) if n.is_infinite() => { + (if *n > 0.0 { "$Infinity" } else { "$-Infinity" }).into() + } + HostValue::Number(n) if n.fract() == 0.0 && n.abs() < 9e15 => (*n as i64).into(), + HostValue::Number(n) => (*n).into(), + HostValue::String(s) => s.to_string_lossy().into_owned().into(), + HostValue::FunctionMarker => "$function".into(), + HostValue::Array(items) => Value::Array( + items + .iter() + .map(|i| i.as_ref().map_or(Value::Null, built)) + .collect(), + ), + HostValue::Object(props) => Value::Object( + props + .iter() + .filter(|(_, v)| !matches!(v, HostValue::Undefined)) + .map(|(k, v)| (k.to_string_lossy().into_owned(), built(v))) + .collect(), + ), + other => panic!("not in a view: {other:?}"), + } +} + +struct Fixture { + name: String, + json: Value, + wire: Option, +} + +impl Fixture { + fn map(&self, field: &str) -> BTreeMap { + self.json[field] + .as_object() + .into_iter() + .flatten() + .map(|(k, v)| (k.clone(), v.as_str().unwrap_or_default().to_owned())) + .collect() + } + + fn program(&self) -> String { + format!( + "{}\n{}{ENTRY}", + prelude(), + self.json["source"].as_str().unwrap_or_default() + ) + } +} + +fn fixtures() -> Vec { + let mut out = Vec::new(); + for entry in std::fs::read_dir(dir()).expect("the fixtures") { + let path = entry.expect("an entry").path(); + if path.extension().and_then(|e| e.to_str()) != Some("json") { + continue; + } + // The depth fixtures nest past serde_json's default limit of 128. + let text = std::fs::read_to_string(&path).expect("read"); + let mut reader = serde_json::Deserializer::from_str(&text); + reader.disable_recursion_limit(); + let json: Value = serde::Deserialize::deserialize(&mut reader).expect("JSON"); + out.push(Fixture { + name: json["name"].as_str().unwrap_or_default().to_owned(), + wire: json.get("view").map(|view| { + let mut wire = String::new(); + stringify(view, &mut wire); + wire + }), + json, + }); + } + out.sort_by(|a, b| a.name.cmp(&b.name)); + assert_eq!(out.len(), 58); + out +} + +/// The prelude a fixture's program starts with (`packages/widget/src/prelude.js`). +fn prelude() -> String { + std::fs::read_to_string(widget().join("src/prelude.js")).expect("the prelude") +} + +/// What the walk of `view` gives: its JSON, handlers (id -> event) and canvases (key -> id). +type Walked = Result<(String, BTreeMap, BTreeMap), WalkError>; + +fn walk(view: &HostValue) -> Walked { + let mut out = String::new(); + let tree = Walk::new().handlers().run(view, &mut out)?; + // A later node with the same id takes it, as in the prelude's table. + let handlers = tree + .handlers + .unwrap_or_default() + .into_iter() + .map(|(id, event)| (id, event.to_owned())) + .collect(); + let canvases = tree + .canvases + .into_iter() + .map(|(k, (id, _))| (k, id)) + .collect(); + Ok((out, handlers, canvases)) +} + +/// What a fixture expects of the walk of its view. +fn expected(f: &Fixture) -> Walked { + let error = &f.json["error"]; + if error["view"] == true { + let message = error["message"].as_str().unwrap_or_default(); + return Err(WalkError::View( + [widget_web::tree::KEY, DEEP] + .into_iter() + .find(|m| *m == message) + .expect("a view failure"), + )); + } + if error["message"] + .as_str() + .is_some_and(|m| m.contains("contains a function")) + { + return Err(WalkError::Function); + } + Ok(( + f.wire.clone().unwrap_or_default(), + f.map("handlers"), + f.map("canvases"), + )) +} + +#[test] +fn every_fixture_walks_from_its_built_view() { + let mut walked = 0; + for f in fixtures() { + if f.json.get("built").is_none() { + continue; + } + let got = walk(&host(&f.json["built"])); + let want = expected(&f); + match (&got, &want) { + // A failing step's view: its error, unless the run fails for another reason (the result's). + (Ok(_), Ok(_)) if f.wire.is_none() => {} + _ => assert_eq!(got, want, "{}", f.name), + } + walked += 1; + } + assert_eq!(walked, 57); +} + +/// Each fixture's program run natively on its input with real function markers: the view `__widget_emit` gets is +/// `built` and walks to the fixture's (view byte for byte, handlers, canvases), and `Program::run_step` gives the +/// fixture's `result` and view, or fails with its `error`. +#[test] +fn every_fixture_runs_natively_to_its_view_result_or_error() { + let mut count = 0; + for f in fixtures() { + let program = f.program(); + // The run with an `__widget_emit` that keeps what it gets. + let input = host(&f.json["input"]); + let emitted: Arc>>> = Arc::default(); + let keep = emitted.clone(); + let runtime = Runtime::make() + .globals(move |_run| { + let input = input.clone(); + let keep = keep.clone(); + [ + ("__input", HostFunction::new(move |_, _| input.clone())), + ( + "__widget_emit", + HostFunction::new(move |args, _| { + keep.lock().unwrap().push(args); + HostValue::Undefined + }), + ), + ] + }) + .translate(Translate { + functions: TranslateFunctions::Mark, + promises: TranslatePromises::Error, + }) + .limits(Limits { + max_value_depth: Some(202), + ..Limits::default() + }); + let _ = runtime.execute(program.as_str()); + let emitted = std::mem::take(&mut *emitted.lock().unwrap()); + if let Some(want) = f.json.get("built") { + assert_eq!(emitted.len(), 1, "{}: one emit", f.name); + assert_eq!(&built(&emitted[0][0]), want, "{}: built", f.name); + let got = walk(&emitted[0][0]); + match expected(&f) { + Ok(_) if f.wire.is_none() => assert!(got.is_ok(), "{}", f.name), + want => assert_eq!(got, want, "{}", f.name), + } + } else { + // Too deep to cross: the prelude hands over the reason instead. + assert_eq!(emitted.len(), 1, "{}: one emit", f.name); + assert!( + matches!(&emitted[0][..], [HostValue::Null, HostValue::String(s)] if s == DEEP) + ); + } + + // The host's own entry point. + let step = Program::new(&program, None).unwrap().run_step( + &f.json["input"].to_string(), + None, + None, + ); + let error = &f.json["error"]; + match step { + Ok(text) => { + assert!(error.is_null(), "{}: expected {error}, got {text}", f.name); + let wire = f.wire.as_deref().expect("a view"); + assert!( + text.ends_with(&format!(",\"view\":{wire}}}")), + "{}: the view in {text}", + f.name + ); + let mut reader = serde_json::Deserializer::from_str(&text); + reader.disable_recursion_limit(); + let mut output: Value = serde::Deserialize::deserialize(&mut reader).expect("JSON"); + output.as_object_mut().unwrap().shift_remove("view"); + assert_eq!(output, f.json["result"], "{}: the result", f.name); + } + Err(e) => { + let want = error["message"].as_str().unwrap_or("(no error)"); + assert_eq!( + (matches!(e, Error::View { .. }), e.reason()), + (error["view"] == true, want), + "{}", + f.name + ); + } + } + count += 1; + } + assert_eq!(count, 58); +} + +/// The walk counts levels itself, for views the boundary lets through (its default depth stops them at 16 levels). +#[test] +fn a_view_nests_at_most_100_levels() { + let leaf = || HostValue::object([("type", HostValue::String("text".into()))]); + let column = |child: HostValue| { + HostValue::object([ + ("type", HostValue::String("column".into())), + ("children", HostValue::array([child])), + ]) + }; + let nest = |levels: usize, wrap: &dyn Fn(HostValue) -> HostValue| { + (1..levels).fold(leaf(), |node, _| wrap(node)) + }; + assert!( + Walk::new() + .run(&nest(100, &column), &mut String::new()) + .is_ok() + ); + assert_eq!( + Walk::new() + .run(&nest(101, &column), &mut String::new()) + .err(), + Some(WalkError::View(DEEP)) + ); + // An array inside children counts as a level: 50 columns of `[[node]]` put the leaf at level 101. + let arrays = |child: HostValue| column(HostValue::array([child])); + assert!( + Walk::new() + .run(&nest(50, &arrays), &mut String::new()) + .is_ok() + ); + assert_eq!( + Walk::new() + .run(&nest(51, &arrays), &mut String::new()) + .err(), + Some(WalkError::View(DEEP)) + ); + // Strings don't count: a string at level 101 is fine. + let strings = (1..100).fold(column(HostValue::String("x".into())), |node, _| { + column(node) + }); + assert!(Walk::new().run(&strings, &mut String::new()).is_ok()); +} + +/// A widget step's boundary is 202 values deep (widgets.md, "Native hosts"): a view of 100 levels crosses and walks, +/// one of 101 fails in phase view, nested children or arrays alike; a prop deeper than the boundary fails where it +/// crosses. +#[test] +fn a_native_step_takes_views_of_100_levels() { + let step = |view: &str| { + let program = format!("{}\nfunction view() {{\n{view}\n}}{ENTRY}", prelude()); + Program::new(&program, None).unwrap().run_step( + r#"{"phase":"init","data":null}"#, + None, + None, + ) + }; + let nested = |levels: usize, wrap: &str| { + format!( + "let node = ui.button(\"deep\", {{ onPress: (s) => s }})\nfor (let i = 1; i < {levels}; i++) node = {wrap}\nreturn node" + ) + }; + let id = vec!["0"; 100].join("/"); + let out = step(&nested(100, "ui.column([node])")).expect("100 levels"); + assert!(out.contains(&format!("\"id\":\"{id}\"")), "{out}"); + let id = std::iter::once("0") + .chain(vec!["0.0"; 49]) + .collect::>() + .join("/"); + let out = step(&nested(50, "ui.column([[node]])")).expect("100 levels in arrays"); + assert!(out.contains(&format!("\"id\":\"{id}\"")), "{out}"); + assert_eq!( + step(&nested(101, "ui.column([node])")), + Err(Error::View { + reason: DEEP.into() + }) + ); + assert_eq!( + step(&nested(51, "ui.column([[node]])")), + Err(Error::View { + reason: DEEP.into() + }) + ); + let too_deep = + step(r#"return ui.text("x", { extra: JSON.parse("[".repeat(210) + "]".repeat(210)) })"#); + assert!( + matches!(&too_deep, Err(e) if e.reason().contains("exceeds the maximum value depth of 202")), + "{too_deep:?}" + ); +} + +/// A function where none may go is the runtime's own `TypeError` to a program that catches it. +#[test] +fn a_caught_function_error_is_a_real_type_error() { + let program = format!( + "{}\nfunction view() {{\n try {{ __widget_emit(ui.text(\"x\", {{ f: () => 1 }})) }} catch (e) {{\n return ui.text([e instanceof TypeError, e.constructor === TypeError, e.name, e.message].join(\" | \"))\n }}\n}}{ENTRY}", + prelude() + ); + let out = Program::new(&program, None) + .unwrap() + .run_step(r#"{"phase":"init","data":null}"#, None, None) + .unwrap(); + assert!( + out.ends_with(r#""view":{"type":"text","text":"true | true | TypeError | Argument 1 to __widget_emit contains a function, which cannot be passed to the host."}}"#), + "{out}" + ); +} + +#[test] +fn a_key_with_a_lone_surrogate_is_a_program_error() { + let lone = psychoscript::HostString::from_utf16(&[0xd800]); + let view = HostValue::object([ + ("type", HostValue::String("column".into())), + ( + "children", + HostValue::Array(vec![Some(HostValue::object([ + ("type", HostValue::String("text".into())), + ("key", HostValue::String(lone)), + ]))]), + ), + ]); + assert_eq!( + Walk::new().run(&view, &mut String::new()).err(), + Some(WalkError::Uri) + ); +} + +/// The walk's cost on the biggest fixtures: +/// `cargo test --release -p widget-web --test tree -- --ignored --nocapture`. +#[test] +#[ignore = "timings: run in release with --ignored"] +fn timings() { + let all = fixtures(); + for name in ["grid-200", "builtin-suggestions"] { + let f = all.iter().find(|f| f.name == name).expect(name); + let view = host(&f.json["built"]); + let mut out = String::new(); + let runs = 400; + let mut best = f64::MAX; + for _ in 0..runs { + out.clear(); + let t = Instant::now(); + Walk::new().run(&view, &mut out).expect("walks"); + best = best.min(t.elapsed().as_secs_f64() * 1e6); + } + println!("{name}: {best:.1} µs (min of {runs}), {} bytes", out.len()); + } +} + +/// A native draw step: the commands `__widget_emit` gets are read as JSON reads them (functions and `undefined` fields +/// left out, an `undefined` item `null`), then checked and normalised; `[]` when `draw` returns nothing. The checks +/// themselves: `tests/draw.rs`. +#[test] +fn a_draw_step_emits_its_commands_as_json_reads_them() { + let draw = |source: &str| { + let program = format!("{}\n{source}{ENTRY}", prelude()); + Program::new(&program, None).unwrap().run_draw( + r#"{"phase":"draw","data":null,"state":{},"frame":{"id":"0/:c","width":2,"height":2}}"#, + None, + None, + ) + }; + assert_eq!( + draw(r##"function draw(state, data, frame) { + return ui.draw().rect(0, 0, 1, 1, "accent").commands.concat([["text", 1, 2, frame.key, undefined], ["rect", 0, 0, 1, 1, { u: undefined, f: () => 1, fill: "#fff" }]]) +}"##) + .unwrap(), + r##"[["rect",0,0,1,1,{"fill":"accent"}],["text",1,2,"c",{}],["rect",0,0,1,1,{"fill":"#fff"}]]"## + ); + assert_eq!( + draw("function draw() {\n return [[\"text\", 1, NaN, \"t\"]]\n}"), + Err(Error::Draw { + reason: "draw command 0: \"text\" argument 2 must be a finite number".into() + }) + ); + assert_eq!(draw("function draw() {}").unwrap(), "[]"); + assert_eq!(draw("").unwrap(), "[]"); + assert!(draw("function draw() { throw new Error('no') }").is_err()); +} + +/// Whole native steps on the biggest fixtures (the view emitted and walked here, functions as markers), and a draw +/// step of the heatmap (its commands emitted). +#[test] +#[ignore = "timings: run in release with --ignored"] +fn step_timings() { + let all = fixtures(); + for name in ["grid-200", "builtin-suggestions", "builtin-heatmap"] { + let f = all.iter().find(|f| f.name == name).expect(name); + let input = f.json["input"].to_string(); + let native = Program::new(&f.program(), None).unwrap(); + let mut best = f64::MAX; + let mut output = String::new(); + for _ in 0..200 { + let t = Instant::now(); + output = native.run_step(&input, None, None).expect("runs"); + best = best.min(t.elapsed().as_secs_f64() * 1e6); + } + println!("{name}: native step {best:.0} µs (min of 200)"); + if name == "builtin-heatmap" { + let state: Value = serde_json::from_str::(&output).unwrap()["state"].clone(); + let draw = serde_json::json!({ "phase": "draw", "data": f.json["input"]["data"], "state": state, + "frame": { "id": "0", "t": 0, "dt": 0, "width": 640, "height": 320, "scale": 2, "pointer": null, + "dark": true, "fullscreen": false, "close": null } }) + .to_string(); + let mut best = f64::MAX; + for _ in 0..200 { + let t = Instant::now(); + native.run_draw(&draw, None, None).expect("draws"); + best = best.min(t.elapsed().as_secs_f64() * 1e6); + } + println!("{name}: native draw step {best:.0} µs (min of 200)"); + } + } +} diff --git a/packages/widgets-rs/rust-toolchain.toml b/packages/widgets-rs/rust-toolchain.toml new file mode 100644 index 00000000000..58eef2ccd48 --- /dev/null +++ b/packages/widgets-rs/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "1.99.1" +profile = "minimal" +components = ["rustfmt", "clippy"]